본문 바로가기
JSP/정리

[jsp] Forwarding(포워딩)

by 미네밍 2017. 1. 20.

<Forwarding>


포워딩이란, 내가 받은 무언가를 다른 것에게 위임한다는 의미이다.

위임은 2개의 클래스를 이용한다.


1. RequestDispatcher 클래스

RequestDispatcher를 나타내는 그림이다.

이 클래스에서는, 위임을 할 때 보내는 request 객체가 모두 동일하다.


한 Servlet에 다음과 같이 request 객체로 Attribute를 생성한다.

그리고 RequestDispatcher를 이용해 dispatcherJsp.jsp 파일로 forwarding 을 한다고 가정해보자.


requestObj.java (서블릿)

1
2
3
4
5
request.setAttribute("id""abc");
request.setAttribute("pw""12345");
        
RequestDispatcher dispatcher = request.getRequestDispatcher("/dispatcherJsp.jsp");
dispatcher.forward(request, response);
cs


dispatcherJsp.jsp

1
2
3
4
5
im dispatcherJsp
<hr/>
    
id = <%=request.getAttribute("id"%>
pw = <%=request.getAttribute("pw"%>
cs



이처럼 주소창에는 requestObj 라고 뜨지만, dispatcherJsp.jsp 파일의 내용인 것을 확인할 수 있다. 성공적으로 forwarding 이 이루어졌다.


이는 예시일 뿐, Servlet 에서 jsp 파일로 넘기는 것만이 아니라 jsp 상에서도 다른 컴포넌트에 위임을 할 수 있다.


2. HttpServletResponse 클래스


앞선 예와 동일하게 역시 요청을 위임하는 클래스이다.

요청을 받은 컴포넌트는, 클라이언트에게 response 를 한 후에 위임받은 컴포넌트로 다시 request 하는 식으로 이루어진다.


그렇기 때문에 위임받은 컴포넌트는 기존의 request 객체가 아닌, 새로운 request객체를 생성한다. 

따라서, 요청받은 컴포넌트와 위임받은 컴포넌트의 요청객체가 동일하지 않다.


redirect.jsp

1
2
3
4
5
<%
    request.setAttribute("id""abc");
    request.setAttribute("pw""12345");    
    response.sendRedirect("requestObj");
%>
cs


requestObj servlet에 redirect 를 하는 jsp 파일이다.


requestObj.java

1
2
3
4
5
6
7
8
9
10
String id = ( String )request.getAttribute("id");
String pw = ( String )request.getAttribute("pw");
        
response.setContentType("text/html; charset=EUC-KR");
PrintWriter writer = response.getWriter();
writer.print("<html><head></head><body>");
writer.print("Im RequestObj<br/>");
writer.print("id = " + id + "<br/>");
writer.print("pw = " + pw + "<br/>");
writer.print("</body></html>");
cs


다음과 같이 request 로부터 attribute 값을 받아와 출력하는 기능을 하지만,


jsp 의 request 객체와 같은 요청객체가 아니므로, null 값을 출력한다.

역시 jsp에서 servlet

'JSP > 정리' 카테고리의 다른 글

[jsp/spring] 외부파일  (0) 2017.02.03
[jsp/spring] DI  (0) 2017.02.03
[jsp/개발방법론] FrontController 패턴  (0) 2017.01.20
[jsp] JSTL  (0) 2017.01.20
[jsp] EL(Expression Language)  (0) 2017.01.19

댓글