본문 바로가기
[study]이론정리/Spring Boot

Spring MVC - redirect 와 forward & redirect-flashScope-forward

by yoon9i 2024. 7. 2.

10> redirect 와 forward
(1) 문법:
          return "redirect:요청맵핑값"; // 이전 서블릿의 response.sendRedirect("") 동일
          return "forward:요청맵핑값"; // 이전 서블릿의 request.getRequestDispatcher("").forward(request, response) 동일


11> redirect-flashScope-forward
==> redirect 했음에도 불구하고 request scope 에 저장된 Model 을 사용할 수 있음.
    단, 한번만 가능.
==> RedirectAttributes 모델 + ra.addFlashAttribute("model", "홍길동"); 사용해야한다

  // flash
@GetMapping("/redirect-flash")
public String flash(RedirectAttributes ra) {
ra.addFlashAttribute("model", "홍길동");

return "redirect:hello";
}

 

package com.exam;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}
package com.exam.controller;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.exam.dto.LoginDTO;

@Controller
public class MainController {
	
	Logger logger = LoggerFactory.getLogger(getClass());
	
	// redirect 와 forward 타켓
	@GetMapping("/hello")
	public String hello() {
		return "hello";
	}
	
//	// redirect
//	@GetMapping("/redirect")
//	public String redirect() {
//		// http://localhost:8090/app/redirect 로 검색을해도
//		// http://localhost:8090/app/hello 로 변경됨
//		return "redirect:hello";
//	}
	
	// redirect
	@GetMapping("/redirect")
	public String redirect(ModelMap m) {
		m.addAttribute("model", "홍길동");
		
		return "redirect:hello";
	}
	// url 이 변경되기때문에 model 값을 가져올수없다.
	
	// forward
	@GetMapping("/forward")
	public String forward(ModelMap m) {
		m.addAttribute("model", "이순신");
		
		return "forward:hello";
	}
	// url 이 변경이 안되기때문에 model 값을 가져올수있다.
	
	// flash
	@GetMapping("/redirect-flash")
	public String flash(RedirectAttributes ra) {
		ra.addFlashAttribute("model", "홍길동");
		
		return "redirect:hello";
	}
}
package com.exam.dto;

public class LoginDTO {

	String userid;
	String passwd;
	
	public LoginDTO() {}

	public LoginDTO(String userid, String passwd) {
		this.userid = userid;
		this.passwd = passwd;
	}

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public String getPasswd() {
		return passwd;
	}

	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}

	@Override
	public String toString() {
		return "LoginDTO [userid=" + userid + ", passwd=" + passwd + "]";
	}
	
	
}
<%@ page 
         contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"        
%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

</head>
<body>
	<h2>hello.jsp</h2>
	모델값: ${model}<br>
</body>
</html>
# application.properties
logging.level.org.springframework=info

# tomcat port 번호 변경
server.port=8090

# context 명 변경
server.servlet.context-path=/app

# jsp의 경로와 확장자 지정
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
	http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.18</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.exam</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>11</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-devtools -->
		<dependency>
		    <groupId>org.springframework.boot</groupId>
		    <artifactId>spring-boot-devtools</artifactId>
		</dependency>
	<dependency>
		<groupId>org.apache.tomcat.embed</groupId>
		<artifactId>tomcat-embed-jasper</artifactId>
		<scope>provided</scope>
	</dependency> 
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
	</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

'[study]이론정리 > Spring Boot' 카테고리의 다른 글

Spring MVC - HandlerInterceptor (X 라고 가정)  (0) 2024.07.03
Spring MVC - FileUpload & download  (0) 2024.07.02
Spring MVC - Ajax + json 통신  (0) 2024.07.02
Spring MVC - Model Scope  (0) 2024.07.02
Spring MVC - Model 생성  (0) 2024.07.02