출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]

컨트롤러 구현

 

 

@Controller 애노테이션 이용을 권장하며,

@Controller & @RequestMapping 는 구현을 위한 필수 애노테이션이다.

@Controller Controller 클래스 정의 
@RequestMapping HTTP요청 URL을 처리할 Controller 메소드 정의 
@RequestParam HTTP 요청에 포함된 파라미터 참조 시 사용 
@ModelAttribute HTTP 요청에 포함된 파라미터를 모델 객체로 바인딩

                                 @ModelAttribute의 ‘name’으로 정의한 모델 객체를 다음 View에게 사용 가능

 

 

 

문법

1. 요청 URL만 선언할 경우

@RequestMapping("/요청url")

2. 요청방식을 지정한 경우

@RequestMapping( value="/요청url" method=RequestMethod.메서드방식(ex)get/post)

 

Controller의 처리 결과를 보여줄 View 지정 방법 / 메소드의 반환 값에 따른 view page지정 방법

1. ModelAndView인 경우

setViewName() 메소드 파라미터로 설정

2. String인 경우

메소드의 리턴 값

 

 

 

예제

 

RequestMapping 예제 - 요청방식 지정에 따른 경우 

package com.aia.firstspring.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.aia.firstspring.member.domain.LoginRequest;

@Controller
@RequestMapping("/member/login")
public class memberLoginController {
	//사용자의 요청 url 처리해야될 기능, 메서드를 바인딩 하는 것이 컨트롤러다.
	
	// @RequestMapping(value = "/member/login", method = RequestMethod.GET)
		@RequestMapping(method = RequestMethod.GET)
		public ModelAndView getLoginForm() {
			return new ModelAndView("member/loginForm"); // setViewName과 동일, 
		}
		
		// @RequestMapping(value = "/member/login", method = RequestMethod.POST)
		@RequestMapping(method = RequestMethod.POST)
		public ModelAndView login() {

			ModelAndView mav = new ModelAndView();
			mav.setViewName("/member/login"); // 로그인 되었을 때 보이는 페이지 -> mapping에 밸류가 동일해서 오류 생김
			return mav;
		}

	}

 

 

 

사용자의 파라미터값을 받는 방법
1. HttpServletRequest 객체 이용
2. @RequestParam(폼의 네임속성)
3. 커맨드 객체(Beans) 이용

 

 

 

@RequestParam 예제 = @RequestParam(폼의 네임속성) 

package com.aia.firstspring.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.aia.firstspring.member.domain.LoginRequest;

@Controller
@RequestMapping("/member/login")
public class memberLoginController {
	//사용자의 요청 url 처리해야될 기능, 메서드를 바인딩 하는 것이 컨트롤러다.
	
	// @RequestMapping(value = "/member/login", method = RequestMethod.GET)
		@RequestMapping(method = RequestMethod.GET)
		public ModelAndView getLoginForm() {
			return new ModelAndView("member/loginForm"); // setViewName과 동일, 
		}
		
		// @RequestMapping(value = "/member/login", method = RequestMethod.POST)
		@RequestMapping(method = RequestMethod.POST)
		public ModelAndView login(
				@RequestParam("uid") String uid,
				@RequestParam("pw") String pw) {
			//리퀘스트파람이 파라미터를 받아올 수 있게 해준다.

			ModelAndView mav = new ModelAndView();
			mav.setViewName("/member/login"); // 로그인 되었을 때 보이는 페이지 -> mapping에 밸류가 동일해서 오류 생김
			mav.addObject("uid", uid);
			mav.addObject("pw", pw);
			
			return mav;
		}

	}

.

 

HttpServletRequest = HttpServletRequest 객체 이용 

 

package com.aia.firstspring.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.aia.firstspring.member.domain.LoginRequest;

@Controller
@RequestMapping("/member/login")
public class memberLoginController {
	//사용자의 요청 url 처리해야될 기능, 메서드를 바인딩 하는 것이 컨트롤러다.
	
	// @RequestMapping(value = "/member/login", method = RequestMethod.GET)
		@RequestMapping(method = RequestMethod.GET)
		public ModelAndView getLoginForm() {
			return new ModelAndView("member/loginForm"); // setViewName과 동일, 
		}
		
		// @RequestMapping(value = "/member/login", method = RequestMethod.POST)
		@RequestMapping(method = RequestMethod.POST)
		public ModelAndView login(
				HttpServletRequest request) {

			
			String userId = request.getParameter("uid");
			String userPw = request.getParameter("pw");
			
			ModelAndView mav = new ModelAndView();
			mav.addObject("userId", userId);
			mav.addObject("userPw",userPw);
			
			return mav;
		}

	}

 

커맨드 객체 = (Beans) 이용 

이때 객체간의 파라미터 이름이 같아야 한다!!!!!!

package com.aia.firstspring.member.domain;

public class LoginRequest {

	
	// 변수의 이름이 form에있는 name과 같아야 한다.
	String uid;
	String pw;
	
	public String getUid() {
		return uid;
	}
	public void setUid(String uid) {
		this.uid = uid;
	}
	public String getPw() {
		return pw;
	}
	public void setPw(String pw) {
		this.pw = pw;
	}
	@Override
	public String toString() {
		return "LoginRequest [uid=" + uid + ", pw=" + pw + "]";
	}
	
	
}
package com.aia.firstspring.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.aia.firstspring.member.domain.LoginRequest;

@Controller
@RequestMapping("/member/login")
public class memberLoginController {
	//사용자의 요청 url 처리해야될 기능, 메서드를 바인딩 하는 것이 컨트롤러다.
	
	// @RequestMapping(value = "/member/login", method = RequestMethod.GET)
		@RequestMapping(method = RequestMethod.GET)
		public ModelAndView getLoginForm() {
			return new ModelAndView("member/loginForm"); // setViewName과 동일, 
		}
		
		// @RequestMapping(value = "/member/login", method = RequestMethod.POST)
		@RequestMapping(method = RequestMethod.POST)
		public ModelAndView login(
				HttpServletRequest request,
				LoginRequest loginRequest) {
			
			// login("cool","1111")
			System.out.println(loginRequest);
			
			String userId = request.getParameter("uid");
			String userPw = request.getParameter("pw");
			
			ModelAndView mav = new ModelAndView();
			mav.addObject("userId", userId);
			mav.addObject("userPw", userPw);
			//mav.addObject("loginRequest", loginRequest); 
			//안해도 공유가 됨 변수이름은 클래스 이름의 앞글자를 소문자로 바꾼 것으로 됨
			
			return mav;
		}

	}

 

 

 

 

MVC : List 타입의 프로퍼티 바인딩 처리하기 예제

 

 

아이템 목록 : OrderItem.java

package com.aia.firstspring.domain;

public class OrderItem {
	
	private String itemId;
	private String number;
	private String remark;
	public String getItemId() {
		return itemId;
	}
	public void setItemId(String itemId) {
		this.itemId = itemId;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public String getRemark() {
		return remark;
	}
	public void setRemark(String remark) {
		this.remark = remark;
	}
	@Override
	public String toString() {
		return "OrderItem [itemId=" + itemId + ", number=" + number + ", remark=" + remark + "]";
	}
	
	

}

 

주소 목록 : Address.java

package com.aia.firstspring.domain;

public class Address {
	
	private String zipcode;
	private String address1;
	private String address2;
	public String getZipcode() {
		return zipcode;
	}
	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}
	public String getAddress1() {
		return address1;
	}
	public void setAddress1(String address1) {
		this.address1 = address1;
	}
	public String getAddress2() {
		return address2;
	}
	public void setAddress2(String address2) {
		this.address2 = address2;
	}
	
	@Override
	public String toString() {
		return "Address [zipcode=" + zipcode + ", address1=" + address1 + ", address2=" + address2 + "]";
	}
	
	

}

 

orderCommand.java

/ 커맨드는 이걸루 사용 

/ 주소랑 상품 묶어줌

package com.aia.firstspring.domain;

import java.util.List;

public class orderCommand {
	
	private List<OrderItem> orderItems; 
	private Address address;
	public List<OrderItem> getOrderItems() {
		return orderItems;
	}
	public void setOrderItems(List<OrderItem> orderItems) {
		this.orderItems = orderItems;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	@Override
	public String toString() {
		return "orderCommand [orderItems=" + orderItems + ", address=" + address + "]";
	}
	
	

}

 

컨트롤러 OrderControoler.java

GET / POST 타입 방식에 따른 리퀘스트맵핑

@ModelAttribute 애노테이션을 사용하여 모델명을 설정 (uo로 줄여줌)

package com.aia.firstspring.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.aia.firstspring.domain.orderCommand;

@Controller
@RequestMapping("/order/order")
public class OrderController {
	
	@RequestMapping(method = RequestMethod.GET)
	public String getOrderForm() {
	    	return "order/orderForm";
	}
	
	@RequestMapping(method = RequestMethod.POST)
	public String orderComplete(@ModelAttribute("uo") orderCommand order) {
		System.out.println(order);
		return "order/orderComplete";
	}

}

 

[VIEW-1]

입력받을 폼 > orderForm.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>주문</title>
</head>
<body>

	<h1>주문 폼</h1>
	<form method="post">
		<table border="1">
			<tr>
				<td rowspan="3">상품-1</td>
				<td>ID</td>
				<td><input type="text" name="orderItems[0].itemId"></td>
			</tr>
			<tr>
				<td>개수</td>
				<td><input type="number" name="orderItems[0].number"></td>
			</tr>
			<tr>
				<td>주의</td>
				<td><input type="text" name="orderItems[0].remark"></td>
			</tr>
			<tr>
				<td rowspan="3">상품-2</td>
				<td>ID</td>
				<td><input type="text" name="orderItems[1].itemId"></td>
			</tr>
			<tr>
				<td>개수</td>
				<td><input type="number" name="orderItems[1].number"></td>
			</tr>
			<tr>
				<td>주의</td>
				<td><input type="text" name="orderItems[1].remark"></td>
			</tr>
			<tr>
				<td rowspan="3">상품-3</td>
				<td>ID</td>
				<td><input type="text" name="orderItems[2].itemId"></td>
			</tr>
			<tr>
				<td>개수</td>
				<td><input type="number" name="orderItems[2].number"></td>
			</tr>
			<tr>
				<td>주의</td>
				<td><input type="text" name="orderItems[2].remark"></td>
			</tr>
			<tr>
				<td rowspan="3">주소</td>
				<td>우편번호</td>
				<td><input type="text" name="address.zipcode"></td>
			</tr>
			<tr>
				<td>주소1</td>
				<td><input type="text" name="address.address1"></td>
			</tr>
			<tr>
				<td>주소2</td>
				<td><input type="text" name="address.address2"></td>
			</tr>
			<tr>
				<td></td>
				<td><input type="submit"></td>
				<td></td>
			</tr>
		</table>

	</form>

</body>
</html>

[VIEW-2]

결과출력 > orderComplete.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>

	<h1>주문정보</h1>
	
	<h3>상품 주문 정보</h3>
	
	<c:forEach items="${uo.orderItems}" var="oi">
		<div>
			상품 ID : ${oi.itemId} / 개수 : ${oi.number}개 / 주의사항 : ${oi.remark} 	
		</div>	
	</c:forEach>
	
	<h3>배송지</h3>
	<div>
	
		우편번호 : ${uo.address.zipcode}
		주소1 :  ${uo.address.address1}
		주소2 :  ${uo.address.address2}
	</div>
	
</body>
</html>

 

+ Recent posts