[Servlet] Redirect

์†Œ์ด๋Žยท2023๋…„ 12์›” 11์ผ
1

Servlet

๋ชฉ๋ก ๋ณด๊ธฐ
13/13
post-thumbnail

๐Ÿ“ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ(Redirect)

  • ์„œ๋ฒ„๊ฐ€ ํด๋ผ์ด์–ธํŠธ์—๊ฒŒ ํŠน์ • URL๋กœ ์ด๋™ํ•˜๋ผ๊ณ  ์•Œ๋ ค์ฃผ๋Š” ๊ณผ์ •์„ ์˜๋ฏธํ•œ๋‹ค. ์ผ๋ฐ˜์ ์œผ๋กœ ์‚ฌ์šฉ์ž๋ฅผ ํ•œ URL์—์„œ ๋‹ค๋ฅธ URL๋กœ ๋ณด๋‚ด๋Š” ๋ฐ ์‚ฌ์šฉ๋œ๋‹ค.
  • ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ ์‹คํ–‰ ์‹œ, ์„œ๋ฒ„๋Š” ํด๋ผ์ด์–ธํŠธ์—๊ฒŒ 300๋ฒˆ๋Œ€์˜ HTTP ์ƒํƒœ ์ฝ”๋“œ(Status Code)์™€ ๋‹ค์‹œ ์š”์ฒญํ•  ์œ„์น˜ ์ •๋ณด(Location)๋ฅผ ์‘๋‹ต์œผ๋กœ ๋ณด๋‚ด ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ ์ •๋ณด๋ฅผ ์•Œ๋ ค์ค€๋‹ค.
  • ์ •์ƒ์ ์œผ๋กœ ์ฒ˜๋ฆฌ๋  ๊ฒฝ์šฐ, 200๋ฒˆ๋Œ€์˜ HTTP ์ƒํƒœ ์ฝ”๋“œ๋Š” ๋งˆ์ง€๋ง‰ ์š”์ฒญ ์‹œ ์‘๋‹ต๋ฐ›๋Š”๋‹ค.
  • response.sendRedirect("ํด๋ผ์ด์–ธํŠธ๊ฐ€ ๋‹ค์‹œ ์š”์ฒญ ๋ณด๋‚ผ ์ฃผ์†Œ(Location)")

์ด๋ฏธ์ง€ ์ถœ์ฒ˜

๐Ÿ“ ์˜ˆ์‹œ

  • ํŽ˜์ด์ง€ 1 -> Servlet(๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ ๋ฐ ํŽ˜์ด์ง€ 2๋กœ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ) -> ํŽ˜์ด์ง€ 2์˜ ํ๋ฆ„์ด๋‹ค.
  • Servlet์—์„œ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ๋ฅผ ํ•  ๊ฒฝ์šฐ, ์ฝ˜ํ…์ธ  ํƒ€์ž…์€(response.setContentType())์€ ์„ค์ •ํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค. ์ฝ˜ํ…์ธ  ํƒ€์ž…์€ ์ตœ์ข…์ ์œผ๋กœ ์‘๋‹ต๋˜๋Š” ํŽ˜์ด์ง€์—์„œ ์„ค์ •ํ•œ๋‹ค.
// ๐ŸŸข src/main/java/com/test/lesson04/Lesson04Ex02.java

package com.test.lesson04;

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/lesson04/ex02")
public class Lesson04Ex02 extends HttpServlet {

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	// ๋ฐ์ดํ„ฐ ์ฒ˜๋ฆฌ(์ƒ๋žต)
        
 		// ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ
		response.sendRedirect("/lesson04/ex02/page2.jsp");
	}
	
}
<%-- ๐Ÿ”ต src/main/webapp/lesson04/ex02/page1.jsp --%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ํŽ˜์ด์ง€ 1</title>
</head>
<body>
	<h1>ํŽ˜์ด์ง€ 1์ž…๋‹ˆ๋‹ค.</h1>
	<a href="/lesson04/ex02">์„œ๋ธ”๋ฆฟ์˜ ๋ฆฌ๋‹ค์ด๋ ‰ํŠธ๋กœ ํŽ˜์ด์ง€ 2๋กœ ์ด๋™</a>
</body>
</html>
<%-- ๐Ÿ”ต src/main/webapp/lesson04/ex02/page2.jsp --%>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ํŽ˜์ด์ง€ 2</title>
</head>
<body>
	<h1>ํŽ˜์ด์ง€ 2์ž…๋‹ˆ๋‹ค.</h1>
</body>
</html>

๐Ÿ“ References

๐Ÿ”— https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections

0๊ฐœ์˜ ๋Œ“๊ธ€