RequestDispatcher forward method
FRAMEWORK/SERVLET 2014. 11. 5. 17:59RequestDispatcher forward :
Hello, we are going to learn about RequestDispatcher forward method in servlet API.
Why is it needed?
The need may arise such that when a request is made for some specific resource, and the resource cannot handle the operations those are needed, it can simply delegate those operations to another resource and another resource serves the request with its own response.
How to do it?
Servlet specification defines an interface called RequestDispatcher. RequestDispatcher forward can be used for this purpose. As per javadoc,
- Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.
- Forward method:
- Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. This method allows one servlet to do preliminary processing of a request and another resource to generate the response.
Step 1: Create a dynamic web project.
Create a new dynamic web project in eclipse named ServletJSPExamples .
Step 2: Create and configure DispatcherServlet.
Create a servlet named DispatcherServlet which will use RequestDispatcherforwardto some other resource, in this case, Hello.jsp .
Configure it in web.xml
Step 3: Create Hello.jsp
Create Hello.jsp in WebContent folder in eclipse.
Step 4: Run application.
Deploy your application in tomcat and hit url as per your application. As our application name is ServletJSPExamples , the url will behttp://localhost:8080/ServletsJSPExamples/DispatcherServlet
You will see the output as Hello page.
Explanation:
We got the output as Hello page. that’s fine, but what is happening here. Let us understand step by step.
- In DispatcherServlet , we created a PrintWriter object so that response can be written.
- After out.println(); statement, a RequestDispatcher is created for Hello.jsp using RequestDispatcher rd =request.getRequestDispatcher("Hello.jsp");
- rd.forward(request, response); i.e. RequestDispatcher forward method sends HttpServletRequest and HttpServletResponse objects to the resource for which RequestDispatcher is created. So in this case, it’s Hello.jsp .
- Control is forwarded to Hello.jsp and the contents are written to response. The response is committed and sent to the client.
The figure will elaborate the same.
'FRAMEWORK > SERVLET' 카테고리의 다른 글
RequestDispatcher include method (0) | 2014.11.05 |
---|---|
서블릿이란 (0) | 2014.11.05 |
jsp 와 servlet 의 차이 (0) | 2014.11.05 |
서블릿 (0) | 2014.11.05 |