RequestDispatcher
Methods:
rd.forward(request, response);//method may be include or forward
Login form Example of RequestDispatcher:
- The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be HTML, servlet or JSP.
- This interface can also be used to include the content of another resource also. It is one of the ways of servlet collaboration.
Methods:
- 1. public 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.
- 2. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:
- Includes the content of a resource (servlet, JSP page, or HTML file) in the response.
- The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher.
- Syntax:
- Example:
rd.forward(request, response);//method may be include or forward
Login form Example of RequestDispatcher:
- In this example, we are validating the password entered by the user.
- If the password is a servlet, it will forward the request to the WelcomeServlet, otherwise, it will show an error message: sorry username or password error!.
- In this program, we are checking for hardcoded information.
- In this example, we have created the following files:
- index.html file: for getting input from the user.
- Output:
- Login.java file: a servlet class for processing the response. If the password is sarthak, it will forward the request to the welcome servlet.
- Output:
- Welcome.java file: a servlet class for displaying the welcome message.
- Output:
- web.xml file: a deployment descriptor file that contains the information about the servlet.[In Netbeans, It will automatically created.]
Tags:
RequestDispatcher