JSP/Servlet에는 현재 작업중인 페이지에서 다른 페이지로 이동하는 두 가지 방식의 페이지 전환 기능이 있다.
하나는 Forward이고 하나는 Redirect이다.
둘 다 다른 웹페이지로 이동하지만 행동 양태가 다르다.
- Forward : Web Container 차원에서 페이지 이동만 있다. 실제로 웹 브라우저는 다른 페이지로 이동했음을 알 수 없다.
그렇기 때문에, 웹 브라우저에는 최초에 호출한 URL이 표시되고 이동한 페이지의 URL정보는 볼 수 없다.
동일한 웹 컨테이너에 있는 페이지로만 이동할 수 있다.
현재 실행중인 페이지와 Forward에 의해 호출될 페이지는 request와 response객체를 공유한다.
- Redirect : Web Container는 Redirect명령이 들어오면 웹 브라우저에게 다른 페이지로 이동하라고 명령을 내린다.
그러면 웹 브라우저는 URL을 지시된 주소로 바꾸고 그 주소로 이동한다.
다른 웹 컨테이너에 있는 주소로 이동이 가능하다.
새로운 페이지에서는 request와 response객체가 새롭게 생성된다.
하지만 세션은 유지하기 때문에 세션에 파라미터를 저장하여 다음 페이지에서 꺼낼 수 있다. (클라이언트가 동일한 세션 ID를 사용하여 요청을 보내기 때문).
// servlet code
String serverName = request.getServerName();
int serverPort = request.getServerPort();
String contextPath = request.getContextPath();
String requestUrl = request.getRequestURL().toString();
String requestProtocol = requestUrl.substring(0,requestUrl.indexOf("://")+3);
String location = requestProtocol +serverName+":"+serverPort+contextPath+"/Servlet/sso.UserSignOnServ";
response.sendRedirect(location);
// jsp code
<%
// 세션에 데이터 저장
session.setAttribute("username", "JohnDoe");
String destination = "destination.jsp";
response.sendRedirect(destination);
//destination page 에서는 다음과 같이 세션에 저장한 값을 취할 수 있다.
// 세션에서 데이터 가져오기
//String username = (String) session.getAttribute("username");
%>