Servlet forward and include methods

Keywords: Java JSP xml JavaEE

Original link: http://www.yiidian.com/servlet/servlet-dispatcher.html

Request Forwarding and Inclusion Using Servlet
The RequestDispatcher interface provides the ability to forward requests to another resource, which may be Html, Servlet, or Jsp.The interface can also be used for content containing other resources.

Method of 1 RequestDispatcher interface

The RequestDispatcher interface provides two methods.They are:

  • public void forward (ServletRequest request,ServletResponse response) thorws ServletException,java.io.IOException: Forward requests from a Servlet to another resource on the server (Servlet, JSP file, or HTML file).
  • public void include (ServletRequest request,ServletResponse response) throws ServletException,java.io.IOException: Includes the contents of a resource (servlet, JSP page, or HTML file) in the response.

As shown in the figure above, the response from the second Servlet is sent to the client.The response from the first Servlet will not be displayed to the user.

As shown in the figure above, the response from the second Servlet is contained in the response from the first Servlet before it is sent back to the user.

2 Get the object of RequestDispatcher

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

public  RequestDispatcher getRequestDispatcher(String resource);  

getRequestDispatcher method example:

RequestDispatcher rd=request.getRequestDispatcher("servlet2");  
//servlet2 is the url-pattern of the second Servlet
rd.forward(request, response);//This can be a forward or include method

3 RequestDispatcher case

3.1 Cases involving elements and process descriptions

In this case, we need to verify the password the user entered.If the password is yiidian, the request will be forwarded to WelcomeServlet, otherwise an error message will be displayed:'Sorry, the username or password is incorrect!'In this case, our user name and password are hard-coded, of course you can also change it to query from the database, you can refer to the later development case "Complete user login using Servlet".The following files are required for this case:

index.jsp file: Used to get input from the user.
LoginServlet.java file: The Servlet class used to process responses.If the user enters the correct password, it will forward the request to WelcomeServlet.
WelcomeServlet.java file: Servlet class for displaying welcome messages.
web.xml file: A Web deployment descriptor file that contains configuration information for all Servlet s.

3.2 Write an inde.jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>A little tutorial web-Request Forwarding and Containment</title>
    <meta http-equiv="content-type" content="text/html" charset="UTF-8">
</head>
<body>
<form action="servlet1" method="post">
    //User name: <input type="text" name="userName"/><br/>
    //Password: <input type="password" name="userPass"/><br/>
    <input type="submit" value="Sign in"/>
</form>
</body>
</html>

3.3 Writing LoginServlet

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
 * A little tutorial web - http://www.yiidian.com
 * Verify that the password is correct
 */
public class LoginServlet extends HttpServlet{

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String n=request.getParameter("userName");
        String p=request.getParameter("userPass");

        if(p.equals("yiidian")){
            RequestDispatcher rd=request.getRequestDispatcher("servlet2");
            rd.forward(request, response);
        }else{
            out.print("Sorry, the username or password is wrong!");
            RequestDispatcher rd=request.getRequestDispatcher("/index.jsp");
            rd.include(request, response);
        }
    }

}

3.4 Writing WelcomeServlet

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * A little tutorial web - http://www.yiidian.com
 * Welcome Page
 */
public class WelcomeServlet extends HttpServlet{

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String n=request.getParameter("userName");
        out.print("Welcome,"+n);
    }
}

3.5 Configuring web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>LoginServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>WelcomeServlet</servlet-name>
        <servlet-class>WelcomeServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/servlet1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>WelcomeServlet</servlet-name>
        <url-pattern>/servlet2</url-pattern>
    </servlet-mapping>

</web-app>

3.6 Running tests

Enter the yiidian password, if correct

!

Enter the wrong password

Welcome to my public number: A little tutorial.Get exclusively organized learning resources and daily dry delivery.
If you are interested in my series of tutorials, you can also follow my website: yiidian.com

Posted by stevengunn on Sat, 14 Mar 2020 15:55:00 -0700