웹 컨테이너로부터 RequestDispatcher 인터페이스를 얻어 현재 페이지 내에 다른 URL이나 페이지를 포함 시킬 수 있고, 또한 특정 페이지로 현재 request 정보를 유지하며 이동할 수 있다.


예제는 이전 포스팅(에러 처리 and URL 이동 )에 사용한 소스를 수정하여 작성한다.

추가: successPage.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
 
<%
  String val1 = request.getParameter("val1");
  String val2 = request.getParameter("val2");
  String sum = request.getParameter("sum");
%>   
     
     
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
    <title>Success</title>
  </head>
  <body>
    <center>
      계산이 완료되었습니다. <br/>
      <%= val1 %> + <%= val2 %> = <%= sum %>
    </center>
  </body>
</html>


calcServlet.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.study;
 
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class CalcServlet extends HttpServlet {
    public void init() {
    }
     
    public void service(HttpServletRequest _request, HttpServletResponse _response)
            throws IOException, ServletException {
        String val1 = _request.getParameter("val1");
        String val2 = _request.getParameter("val2");
        int sum = 0;
         
        try {
            int iVal1 = Integer.parseInt(val1);
            int iVal2 = Integer.parseInt(val2);
            sum = iVal1 + iVal2;
            System.out.println("합: " + sum);
             
            // ServletContext 객체 얻음
            ServletContext context = this.getServletContext();
             
            // RequestDispatcher 객체 얻음
            RequestDispatcher dispatcher = context.getRequestDispatcher("/successPage.jsp?sum=" + sum);
             
            // request, response 값을 가지고 페이지 이동
            dispatcher.forward(_request, _response);
             
            // request, response 값을 가지고 페이지 포함
            //dispatcher.include(_request, _response);
             
        } catch(Exception _ex) {
            _response.sendError(588, "숫자로 변환할 수 없는 데이터가 입력되었습니다.");
            return;
        }
    }
     
    public void destroy() {
    }
}


정상적으로 계산되었을 경우 아래와 같이 나타난다.


 

Posted by 후니아부지
: