본문 바로가기

동방프로젝트

Model을 통해 컨트롤러에서 뷰에 데이터 전달

package survey;

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

@Controller	//스프링mvc에서 컨트롤러로 사용됨
@RequestMapping("/survey") //"/survey"경로 요청에 대해 실행하는 메서드
public class SurveyController {
	@GetMapping	//url뒤에 surveyForm붙임으로써 진입가능
	public String form() {
		return "survey/surveyForm";
	}
	
	//커맨드객체 ansData란 이름의 AnsweredData를 받아야 진입가능
	@PostMapping
	public String submit(@ModelAttribute("ansData") AnsweredData data) {
		return "survey/submitted";
	}
}

Model model을 통해, 설문 항목을 컨트롤러에서 생성해 뷰로 전달하는 방식으로 변경하고자 한다.

<%@ page contentType="text/html; charset=utf-8" %>
<!DOCTYPE html>
<html>
<head>
<title>설문조사</title>
</head>
<body>
	<h2> 설문조사</h2>
	<form method="post">
	<p>
	1.역할<br/>
	<label><input type="radio" name="responses[0]" value="서버">
	서버개발자</label>
	<label><input type="radio" name="responses[0]" value="프론트">
	프론트개발자</label>
	<label><input type="radio" name="responses[0]" value="풀스택">
	풀스택개발자</label>
	</p>

	<p>
	2.애용개발도구<br/>
	<label><input type="radio" name="responses[1]" value="Eclipse">
	Eclipse</label>
	<label><input type="radio" name="responses[1]" value="intellij">
	intellij</label>
	<label><input type="radio" name="responses[1]" value="Sublime">
	Sublime</label>
	</p>
	
	<p>
	3.하고픈말<br/>
	<input type="text" name="responses[2]">
	</p>
	<p>
	<label>응답자위치:<br>
	<input type="text" name= "res.location">
	</label>
	</p>
	
	<p>
	<label>응답자나이:<br>
	<input type="text" name= "res.age">
	</label>
	</p>
	
	<input type="submit" value="전송">
	</form>
</body>
</html>

 

public String handlestep2(
	 	@RequestParam(value="agree", defaultValue="false") Boolean agreeVal,
	 	Model model) {
	  		if(!agreeVal) return "register/step1";
		  		
	  		model.addAttribute("registerRequest", new RegisterRequest());
	  		return "register/step2"; 
		//agree요청 파라미터의 값을 읽어와 agreeVal 파라미터에 할당. 요청 파라미터 값이 없으면 false문자열이 값이됨
	}

다음과 같은 코드의 인자를,

Model model을 RegisterRequest registerRequest로 변경이 가능. 이 때, model.addAttribute코드는 필요없음.

이는, <form:form> 태그 이용시, 커맨드객체가 반드시 필요한데, 최초에 폼을 보여주는 요청에 대해 <form:form> 태그를 사용하려면 폼 표시 요청이 왔을때에도 커맨드객체를 생성해 모델에 저장해야하기 때문

 

이름을 명시적으로 지정하고자 할 땐, @ModelAttribute를 사용. 가령 "/login"요청 경로에서, GET방식이면 로그인 폼을, POST방식에선 로그인을 처리하도록 구성코자 할 때ㅡ

@Controller
@RequestMapping("/login")
public class LoginController {

	@GetMapping
    public String form(@ModelAttribute("login") LoginCommand loginCommand() {
    	return "login/loginForm";
    }

	@PostMapping
    public String form(@ModleAttribute("login") LoginCommand loginCommand) {
    	//처리
    }

'동방프로젝트' 카테고리의 다른 글

ControllerAdvice  (2) 2021.02.08
jdbcTemplate 중복코드 제거  (2) 2021.02.08
스프링이 제공하는 폼 태그 사용이전 jsp  (1) 2021.01.31
spring의 transactional&proxy  (2) 2021.01.25
8과 queryForObject()  (2) 2021.01.23