Tuesday, 26 May 2015

RequestDispatcher in Servlet

RequestDispatcher in Servlet

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. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.
Version:
$Version$
Author:
Various
See Also:

Method Summary
 void
forward(ServletRequest request, ServletResponse response) 
          Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.
 void
include(ServletRequest request, ServletResponse response) 
          Includes the content of a resource (servlet, JSP page, HTML file) in the response.

Method Detail

forward

void forward(ServletRequest request,
             ServletResponse response)
             throws ServletException,
                    java.io.IOException
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.
For a RequestDispatcher obtained via getRequestDispatcher(), the ServletRequest object has its path elements and parameters adjusted to match the path of the target resource.
forward should be called before the response has been committed to the client (before response body output has been flushed). If the response already has been committed, this method throws an IllegalStateException. Uncommitted output in the response buffer is automatically cleared before the forward.
The request and response parameters must be either the same objects as were passed to the calling servlet's service method or be subclasses of the ServletRequestWrapper or ServletResponseWrapper classes that wrap them.
Parameters:
request - a ServletRequest object that represents the request the client makes of the servlet
response - a ServletResponse object that represents the response the servlet returns to the client
Throws:
ServletException - if the target resource throws this exception
java.io.IOException - if the target resource throws this exception
java.lang.IllegalStateException - if the response was already committed

include

void include(ServletRequest request,
             ServletResponse response)
             throws ServletException,
                    java.io.IOException
Includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes.
The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.
The request and response parameters must be either the same objects as were passed to the calling servlet's service method or be subclasses of the ServletRequestWrapper or ServletResponseWrapper classes that wrap them.
Parameters:
request - a ServletRequest object that contains the client's request
response - a ServletResponse object that contains the servlet's response
Throws:
ServletException - if the included resource throws this exception

java.io.IOException - if the included resource throws this exception





As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed to the user.



As you can see in the above figure, response of second servlet is included in the response of the first servlet that is being sent to the client.

How to get the object of RequestDispatcher

The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher. Syntax:

Syntax of getRequestDispatcher method

1.    public RequestDispatcher getRequestDispatcher(String resource);  

Example of using getRequestDispatcher method

1.    RequestDispatcher rd=request.getRequestDispatcher("servlet2");  
2.    //servlet2 is the url-pattern of the second servlet  
3.      
4.    rd.forward(request, response);//method may be include or forward  

Example of RequestDispatcher interface

In this example, we are validating the password entered by the user. If password is servlet, it will forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or password error!. In this program, we are cheking for hardcoded information. But you can check it to the database also that we will see in the development chapter. In this example, we have created following files:
  • index.html file: for getting input from the user.
  • Login.java file: a servlet class for processing the response. If password is servet, it will forward the request to the welcome servlet.
  • WelcomeServlet.java file: a servlet class for displaying the welcome message.
  • web.xml file: a deployment descriptor file that contains the information about the servlet.








index.html
1.    <form action="servlet1" method="post">  
2.    Name:<input type="text" name="userName"/><br/>  
3.    Password:<input type="password" name="userPass"/><br/>  
4.    <input type="submit" value="login"/>  
5.    </form>  

Login.java
1.    import java.io.*;  
2.    import javax.servlet.*;  
3.    import javax.servlet.http.*;  
4.      
5.      
6.    public class Login extends HttpServlet {  
7.      
8.    public void doPost(HttpServletRequest request, HttpServletResponse response)  
9.            throws ServletException, IOException {  
10.   
11.     response.setContentType("text/html");  
12.     PrintWriter out = response.getWriter();  
13.           
14.     String n=request.getParameter("userName");  
15.     String p=request.getParameter("userPass");  
16.           
17.     if(p.equals("servlet"){  
18.         RequestDispatcher rd=request.getRequestDispatcher("servlet2");  
19.         rd.forward(request, response);  
20.     }  
21.     else{  
22.         out.print("Sorry UserName or Password Error!");  
23.         RequestDispatcher rd=request.getRequestDispatcher("/index.html");  
24.         rd.include(request, response);  
25.                       
26.         }  
27.     }  
28.   
29. }  

WelcomeServlet.java
1.    import java.io.*;  
2.    import javax.servlet.*;  
3.    import javax.servlet.http.*;  
4.      
5.    public class WelcomeServlet extends HttpServlet {  
6.      
7.        public void doPost(HttpServletRequest request, HttpServletResponse response)  
8.            throws ServletException, IOException {  
9.      
10.     response.setContentType("text/html");  
11.     PrintWriter out = response.getWriter();  
12.           
13.     String n=request.getParameter("userName");  
14.     out.print("Welcome "+n);  
15.     }  
16.   
17. }  

web.xml
1.    <web-app>  
2.     <servlet>  
3.        <servlet-name>Login</servlet-name>  
4.        <servlet-class>Login</servlet-class>  
5.      </servlet>  
6.      <servlet>  
7.        <servlet-name>WelcomeServlet</servlet-name>  
8.        <servlet-class>WelcomeServlet</servlet-class>  
9.      </servlet>  
10.   
11.   
12.   <servlet-mapping>  
13.     <servlet-name>Login</servlet-name>  
14.     <url-pattern>/servlet1</url-pattern>  
15.   </servlet-mapping>  
16.   <servlet-mapping>  
17.     <servlet-name>WelcomeServlet</servlet-name>  
18.     <url-pattern>/servlet2</url-pattern>  
19.   </servlet-mapping>  
20.   
21.   <welcome-file-list>  
22.    <welcome-file>index.html</welcome-file>  
23.   </welcome-file-list>  
24. </web-app>  







No comments:

Post a Comment

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...