Servlet Chaining pages using RequestDispatcher
By candid | Posted : Dec 6, 2015 | Updated : Dec 6, 2015
A RequestDispatcher object can be used to forward a request to
the resource or to include the resource in a response. The resource can be
dynamic or static.
The pathname specified may be relative, although it cannot access outside
the current application.
This method returns null if the servlet container cannot return a
RequestDispatcher.
Forward
Forwards a request from a servlet to another resource (servlet or
JSP file) on the server.
We can use one servlet to do preliminary processing of a request
and another resource to generate the output response.
Any response from the first servlet will be automatically cleared
before forwarding to second servlet.
The forwared Servlet will be using the same request and response
object send by first servlet.
Include
Includes the content of a resource (servlet or JSP page) in the
response. In essence, this method enables programmatic server-side
includes.
The included servlet cannot change the response status code or set
headers of first servlet, any attempt to make a change is ignored.
Example
Html code
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Insert title here</title>
6. </head>
7. <body>
8.
9. Candidjava RequestDispatcher Forward example <br> <br>
10.
11. <form action="TestForwardController" method="post">
12.
13. Enter username :<input type="text" name="username"> <br>
14. Enter password :<input type="password" name="password"><b
r>
15. <input type="submit" value="Login">
16.
17.
18. </form>
19.
20. <br> <br><br><br>
21. Candidjava RequestDispatcher Include example <br> <br>
22. <form action="TestIncludeController" method="post">
23.
24. Enter username :<input type="text" name="username"> <br>
25. Enter password :<input type="password" name="password"><b
r>
26. <input type="submit" value="Login">
27.
28.
29. </form>
30.
31. </body>
32. </html>