BACK-END/JSP

[JSP] forward, sendRedirect

이리53 2022. 3. 23. 13:21

forward, sendRedirect 비교

  forward(request, response) sendRedirect(location)
사용 방법 RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response)
response.sendRedirect(location)
이동 범위 동일 서버(project) 내 경로 동일 서버 포함 타 URL 이동 가능
location 기존 URL 유지(실제 이동 주소 확인 불가) 이동하는 page로 변경
객체 기존의 request, response가 그대로 전달 기존 request, response 소멸
새로운 request, response 생성
데이터 유지 request.setAttribute(name, date) request로는 불가능
session이나 cookie 이용

 

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String msg = request.getParameter("msg");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>to.jsp 입니다.</h1>
	<h2><%= msg %></h2>
</body>
</html>

 

forward.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String path = "to.jsp";
	RequestDispatcher dispatcher = request.getRequestDispatcher(path);
	dispatcher.forward(request, response);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>forward.jsp 입니다.</h1>
</body>
</html>

 

sendredirect.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%	
	String path = "to.jsp";
	response.sendRedirect(path);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>sendredirect.jsp입니다.</h1>
</body>
</html>

 

http://localhost:8080/bw/forward.jsp?msg=hello 접속 시

 

 

http://localhost:8080/bw/sendredirect.jsp?msg=hello 접속 시