230202 Spring 화면보내기2 @ModelAttribute, RedirectAttributes
@ModelAttribute 어노테이션
-Request와 모델이 합쳐진 형태
-전달받은 파라미터를 Model에 담아서 화면까지 전달하려 할 떄 사용되는 어노테이션
-ex)@ModelAttribute("받을값")사용할 변수
-값을 받으면서 넘겨준다.
@RequestMapping("/result")
public String result(@RequestParam("num") String aaa, Modle model){
model.addAttribute("num",aaa);
return "response/result";
}
를
@RequestMapping("/result")
public String result(@ModelAttribute("num") String aaa){
//여기서 처리는 aaa로
return "response/result";
}
로.
-단일변수를 받을 때는 받을 값이 그대로
-객체를 받을 때는 받은 값을 넘겨줄 이름이 넘어감
예시
@RequestMapping("/result04")
public String result04(@ModelAttribute("article")ReqVO vo) {
System.out.println("화면데이터:"+vo.toString());
return "response/result04";
}
에서, 넘어온 데이터를 article이란 이름으로 넘겨주겠다는 뜻. 그럼 받은 화면에선 article이란 이름을 사용하여 객체를 불러올 수 있다.
+)이때, 넘어오는 데이터 형식이 비슷하여 이전에 사용하던 vo를 사용하였지만 원래는 만들어주는 것이다.
RedirectAttribute 객체
-리다이렉트 이동시 파라미터 값을 전달하는 방법
-ex)addFlashAttribute()
리다이렉트
리다이렉트:다시 브라우저로 요청한다. 즉, 다시 Controller로 요청을 보낸다.
mvc에서 리다이렉트를 쓰는 경우 : 데이터는 다 버리고 원하는 화면으로 강제로 이동할 때.
방법은 간단하다. return에 redirect:를 붙여주면 된다.
이때, 웬만하면 절대경로로 적는 편이 좋다.
리다이렉트는 데이터를 다 버린다! 모델데이터는 보낼 수 없다.
리다이렉트는 새 경로를 보내는 것
return "home";이면
http://localhost:8282/basic/response/login로 홈 화면을 띄우는데,
return "redirect:/";이면 경로가
http://localhost:8282/basic/로 홈 화면을 띄운다.
리다이렉트시 모델데이터를 보내려면 RedirectAttributes 변수명.addFlashAttribute()를 사용
리다이렉트시 한번만 사용 가능. 1회성 데이터 저장. 그래서 redirect된 페이지에서 새로고침을 하면 사라진다.
리다이렉트는 막쓴다고 좋은게 아님. 적재적소에 사용할 것.
ResponseController.java
package com.simple.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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.simple.command.ReqVO;
@Controller
@RequestMapping("/response")
public class ResponseController {
//1.화면
@RequestMapping("/ex01")//입력경로
public String ex01() {
return "response/ex01";//출력경로
}
//@ModelAttribute = req+model
@RequestMapping("/result03")
public String result03(@ModelAttribute("num") String aaa) {
System.out.println("화면데이터:" + aaa);
return "response/result03";
}
@RequestMapping("/result04")
public String result04(@ModelAttribute("article")ReqVO vo) {
System.out.println("화면데이터:"+vo.toString());
return "response/result04";
}
///////////////////////////////////////////////////////////////
//redirect이동과 redirectAttribute
//스프링에서 redirect는 다시 컨트롤러를 태우는 요청입니다.
//redirectAttribute는 redirect시에 1회성 데이터를 저장할 수 있습니다.
@RequestMapping("/redirect_login")
public String loginView() {
return "response/redirect_login";
}
@RequestMapping(value="/login", method=RequestMethod.POST)
public String login(@RequestParam("id")String id,
@RequestParam("pw")String pw,
RedirectAttributes ra) {
if(id.equals(pw)) {
System.out.println("home 실행됨");
ra.addFlashAttribute("msg", "환영합니다"); //1회성 데이터
return "redirect:/"; //다시 home컨트롤러를 태워 보냄 -model을 사용할 순 없음
}else {
ra.addFlashAttribute("msg", "아이디 비밀번호가 일치하지 않습니다.");
return "redirect:/response/redirect_login"; //"redirect:/절대경로"
}
}
}
ex01.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>res ex01</h3>
<a href="result01">model객체 사용</a>
<a href="result02">modelAndView객체 사용</a>
<a href="result03?num=10">modelAttr단일값</a>
<form action="result04" method="post">
<input type="text" name="name"/>
<input type="number" name="age"/>
<input type="submit" value="modelAttr 객체"/>
</form>
</body>
</html>
result03.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
result03화면<br/>
넘어온값:${num}
</body>
</html>
콘솔출력문
화면데이터:10
ReqVO.java
package com.simple.command;
import java.util.List;
public class ReqVO {
private String name;
private int age;
private List<String> inter;
//기본생성자
public ReqVO() {}
//생성자
public ReqVO(String name, int age, List<String> inter) {
super();
this.name = name;
this.age = age;
this.inter = inter;
}
//getter setter
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getInter() {
return inter;
}
public void setInter(List<String> inter) {
this.inter = inter;
}
@Override
public String toString() {
return "ReqVO [name=" + name + ", age=" + age + ", inter=" + inter + "]";
}
}
result04.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
result04화면<br/>
넘어온값:${article.name }, ${article.age }
</body>
</html>
콘솔출력문
화면데이터:ReqVO [name=aaa, age=32, inter=null]
-기존에 사용했던 VO를 재사용해서 inter값은 없다.
redirect_login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>redirect 사용해보기</h3>
<form action="login" method="post">
<input type="text" name="id" />
<input type="password" name="pw" />
<input type="submit" value="확인" />
</form>
${msg}
</body>
</html>