Wednesday, October 10, 2012

Servlet RequestDispatcher

1.     RequestDispatcher 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.
2.    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.
3.   This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.

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. 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 sub classes of the ServletRequestWrapper  or   ServletResponseWrapper classes that wrap them.



packagecom.jsl.servlet;
packagecom.jsl.servlet;
importjava.io.IOException;
importjavax.servlet.*;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.*;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    response.sendRedirect("index.html");
    
    request.getRequestDispatcher("/welcome").forward(request,response);
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   
 }
}


      In this example the response has been committed, We are trying to forward to another servlet, It throws the IllegalStateException

Login.html

<!DOCTYPEHTMLPUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
 
   
   
   
   
  
  
    
User Login E-Mail
* Password *
</html>

LoginServlet.java

packagecom.jsl.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.*;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.*;
@WebServlet("/login")
publicclassLoginServletextendsHttpServlet {

privatestaticfinallongserialVersionUID = 1L;
protectedvoiddoGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
  RequestDispatcherrd=null;
  String email=request.getParameter("email");
  String password=request.getParameter("password");
  PrintWriter out=response.getWriter();
  response.setContentType("text/html");
  out.print("");
  out.print("<html><head>Login Page</head>");
  out.print("<body>");   
  if(email.equals(" ") &&password.equals(" ")){
   out.print("Please verify user name and password");
   rd=request.getRequestDispatcher("login.html");
   rd.include(request, response);
  }else{
   if(email.equals("admin@jsltech.com") &&password.equals("admin")){
    rd=request.getRequestDispatcher("welcome");
    rd.forward(request, response);
   }else{
   out.print("Please verify user name and password");
    rd=request.getRequestDispatcher("login.html");
    rd.include(request, response);
    }
   }
   
  out.print("</body>");
  out.print("</html>");
   
   
 }
protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
   doGet(request, response);
 }

}

Welcome.java

packagecom.jsl.servlet;
importjava.io.IOException;
importjava.io.PrintWriter;
importjavax.servlet.ServletException;
importjavax.servlet.annotation.WebServlet;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

@WebServlet("/welcome")
publicclass Welcome extendsHttpServlet {
 privatestaticfinallongserialVersionUID = 1L;
 protectedvoiddoPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {
  PrintWriter out=response.getWriter();
  response.setContentType("text/html");
  out.print("");
  out.print("<html><head>Login Page</head>");
  out.print("<body>"); 
   out.print("

Welcome to JSL Tech

"); out.print("Login Page"); out.print("</body>"); out.print("</html>"); } }

When click on

http://localhost:8080/Servlet_Example/login.html







      If user name or password wrong, then along with the error message the login page will be included


      If user name and password correct then action will go to the welcome servlet and display the output…



void include(ServletRequest request, ServletResponse response)

             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 theServletRequestWrapper or ServletResponseWrapper classes that wrap them.

      What is the difference between the include() and forward() methods?

include()
forward()
        The RequestDispatcherinclude() method inserts the the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet.  
   The RequestDispatcherforward() method is used to show a different resource in place of the servlet that was originally called.
      If you include a servlet or JSP document, the included resource must not attempt to change the response status code or HTTP headers, any such request will be ignored.
          The forwarded resource may be another servlet, JSP or static HTML document, but the response is issued under the same URL that was originally requested. In other words, it is not the same as a redirection.
              The include() method is often used   to include common "boilerplate" text or template markup that may be included by many servlets.
              The forward() method is often used where a servlet is taking a controller role; processing some input and deciding the outcome by returning a particular response page.


No comments:

Post a Comment

Spring Boot 3 : JWT with SecurityFilterChain, AuthorizeHttpRequests, RequestMatchers

pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0"...