출처: https://dololak.tistory.com/502
위 블로그의 내용을 정리했습니다!!
forward()include()sendRedirect()forward(), include()
forward()와 비교해서 좋은 점: 리다이렉트하면 현재 어플리케이션 이외의 다른 자원의 경로를 요청할 수 있으나, RequestDispatcher은 현재 처리중인 서블릿이 속해있는 웹 어플리케이션 범위 내에서만 요청을 제어할 수 있다.a.jsp → b.jsp)service(), doGet(), doPost() 등RequestDispatcher dispatcher = request.getRequestDispatcher("URL");참고
스프링 로드맵 인강에서는service()메서드를 사용했기 때문에 바로RequestDispatcher dispatcher = request.getRequestDispatcher("URL");위 코드 한줄로 RequestDispatcher을 얻을 수 있었다.
ServletContexts는 서블릿 이름, url 경로(절대경로만)를 이용해 호출대상을 지정할 수 있게 한다.
ServletContext context = this.getServletContext();
RequestDispatcher dispatcher = context.getNamedDispatcher("helloServlet");ServletContext context = this.getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher("/hello");
/a.jsp를 요청/a.jsp가 forward()를 실행하여 /b.jsp로 제어를 넘김/b.jsp의 처리 결과를 응답대상 자원
- forward()가 제어를 넘기는 대상 자원은 Servlet 또는 JSP 페이지다.
- (JSP도 최종적으로는 서블릿이다)

/dispatch로 요청이 넘어오면 DispatchTest 서블릿에서 요청을 처리forward()를 통해 /hello로 제어 넘김forward()실행시 HttpServletRequest, HttpServletResponse 객체를 넘겨줌/hello로 제어가 넘어오면 다음 작업을 처리/dispatch: dispatchTest 서블릿@WebServlet(name = "dispatchTest", urlPattern = "/dispatch")
public class DispatchTest extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
request.setAttribute("name", "gamza");
RequestDispatcher dispatcher = request.getRequestDispatcher("/hello");
dispatcher.forward(request, response);
}
}
/hello: helloServlet 서블릿@WebServlet(name = "helloServlet", urlPattern = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=utf-8");
Printwriter w = response.getWriter();
w.println("<HTML>");
w.println("<head><title>HELLO</title></head>");
w.println("<body>");
w.println(""HELLO " + request.getAttribute("name"));
w.println("</body>");
w.println("</html>");
}
}
forward()는 제어를 넘기기 전에 출력 버퍼를 비운다a.jsp → b.jsp로 호출시 a.jsp에서 어떤 내용을 버퍼에 출력했더라도 무시됨b.jsp의 출력 내용만 브라우저에 전달된다.