본문 바로가기

WEB

[WEB] Forward & Redirect 개념과 차이점, 예제

웹에서 페이지를 전환할때 Forward 방식과 Redirect 방식 이렇게 2가지를 제공합니다. 예제를 보면서 이해해봅시다.

 

 

 

[Forward 방식]

 

  • 응답을 위임하여 처리
  • Web Container 차원에서의 페이지 이동만 존재
  • 실제로 웹 브라우저는 다른 페이지로 이동했음을 알 수 없음
  • 그렇기 때문에 웹 브라우저에는 최초에 호출한 URL이 표시
  • 현재 실행중인 페이지와 forward에 의해 호출된 페이지는 request와 resonse 객체를 공유

 

 

 

 

[Redirect 방식]

 

  • 페이지 자체를 이동하여 처리
  • Web Container는 redirect 명령이 들어오면 웹 브라우저에게 다른 페이지로 이동하라는 명령을 내림
  • 즉, 다른 페이지를 호출해서 이동
  • 웹 브라우저는 URL을 redirect된 주소로 변경
  • 새로운 페이지에서는 request, response 객체가 새롭게 생성 (공유하지 않음)

 

 


 

 

예제

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/index.jsp</title>
</head>
<body>
   	<a href="test/busan.jsp">부산가기</a>
   	<a href="test/inchon.jsp">인천가기</a>
</body>
</html>

 

Forward 방식 - 부산가기 링크

Redirect 방식 - 인천가기 링크

 

 

 

 

Forward 방식 예제

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	RequestDispatcher rd=request.getRequestDispatcher("/test/loginform.jsp");
	rd.forward(request,response);
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/test/busan</title>
</head>
<body>

</body>
</html>

forward(request, response)로 페이지를 이동합니다.

request와 response를 인자로 보내주어 공유하는 모습을 볼 수 있습니다.

URL을 보면 loginform.jsp로 변경되지 않은 것을 볼 수 있습니다.

 

 

 

 

 

 

Redirect 방식 예제

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	String cPath=request.getContextPath();
	response.sendRedirect(cPath+"/test/loginform.jsp");
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>/test/inchon</title>
</head>
<body>

</body>
</html>

요청이 빠르게 2번 왔다고 생각하시면됩니다.

URL을 보면 loginform.jsp로 변경된 것을 볼 수 있습니다.