[JavaWeb] Servlet series – template method design pattern, HttpServlet source code analysis, the welcome page of the Web site, about the WEB-INF directory

Hits: 0

Article directory

19 Template Method [Design Patterns]

19.1 What are design patterns?

  • A fixed solution to a problem. (Can be reused.)

19.2 What design patterns do you know?

GoF Design Patterns:

  • Usually we call 23 design patterns. (Gang of Four: Design pattern proposed by a group of 4)
  • singleton pattern
  • factory pattern
  • proxy mode
  • facade pattern
  • Chain of Responsibility Design Pattern
  • Observer pattern
  • Template Method Design Pattern

JavaEE Design Patterns:

  • DAO
  • DTO
  • VO
  • AFTER
  • poo

19.3 What is the template method design pattern?

  • The core algorithm skeleton is defined in the template method of the template class, and the specific implementation steps can be delayed to the subclass.

  • The template class is usually an [abstract class] . The template method in the template class defines the core algorithm. This method is usually final (but it may not be final)

  • [The abstract method] in the template class is the method whose implementation is uncertain, and the unsure how to implement it is left to the subclass to do.

20 HttpServlet [source code] analysis

The HttpServlet class is specially prepared for the HTTP protocol. It is more suitable for development under the HTTP protocol than GenericServlet.

20.1 Which package is HttpServlet under?

  • jakarta.servlet.http.HttpServlet

20.2 What interfaces in the [servlet] specification have we been exposed to so far?

  • jakarta.servlet.Servlet core interface (interface)
  • jakarta.servlet.ServletConfig Servlet configuration information interface (interface)
  • jakarta.servlet.ServletContext Servlet context interface (interface)
  • jakarta.servlet.ServletRequest Servlet request interface (interface)
  • jakarta.servlet.ServletResponse Servlet response interface (interface)
  • jakarta.servlet.ServletException Servlet exception (class)
  • jakarta.servlet.GenericServlet Standard generic servlet class (abstract class)

20.3 What are the classes and interfaces under the http package?

​ jakarta.servlet.http.*;

  • jakarta.servlet.http.HttpServlet (HTTP protocol-specific servlet class, abstract class)
  • jakarta.servlet.http.HttpServletRequest (HTTP protocol specific request object)
  • jakarta.servlet.http.HttpServletResponse (HTTP protocol specific response object)

20.4 What information is encapsulated in the HttpServletRequest object?

  • HttpServletRequest, referred to as the request object.
  • The entire content of the request protocol is encapsulated in HttpServletRequest.
  • The Tomcat server (WEB server) parses all the data in the “request protocol”, and then encapsulates all the data into the request object.
  • That is to say, as long as we face HttpServletRequest, we can get the data in the request protocol.

The HttpServletResponse object is specifically used to respond to the HTTP protocol to the browser.

20.5 Servlet Lifecycle

  • User’s first request
    • The Tomcat server invokes the parameterless constructor through the reflection mechanism. Create a servlet object. (The object corresponding to the Servlet class configured in the web.xml file.)
    • The Tomcat server calls the init method of the Servlet object to complete the initialization.
    • The Tomcat server calls the service method of the Servlet object to process the request.
  • User’s second request
    • The Tomcat server calls the service method of the Servlet object to process the request.
  • User’s third request
    • The Tomcat server calls the service method of the Servlet object to process the request.
    • The Tomcat server calls the service method of the Servlet object to process the request.
  • server shutdown
    • The Tomcat server calls the destroy method of the Servlet object to prepare for the destruction.
    • The Tomcat server destroys the servlet object.

20.6 HttpServlet source code analysis:

public  class  HelloServlet  extends  HttpServlet  {
     // When the user requests for the first time and creates the HelloServlet object, this parameterless constructor will be executed. 
    public  HelloServlet ()  {
    }

    //override overrides the doGet method 
    //override overrides the doPost method
}

public abstract class GenericServlet implements Servlet, ServletConfig,
        java.io.Serializable {

    // When the user requests for the first time, this init method will be executed after the HelloServlet object is created for the first time. 
    public  void  init (ServletConfig config)  throws ServletException {
         this .config = config;
         this .init();
    }
    // When the user requests for the first time, after the init(ServletConfig config) with parameters is executed, this init() without parameters will be executed 
    public  void  init ()  throws ServletException {
         // NOOP by default
    }
}

// HttpServlet template class. 
public  abstract  class  HttpServlet  extends  GenericServlet  {
     // This service will be executed when the user sends the first request 
    // This service method will still be executed when the user sends the Nth request. 
    // This service method will be executed once as long as the user sends a request. 
    @Override 
    public  void  service (ServletRequest req, ServletResponse res) 
        throws ServletException, IOException {

        HttpServletRequest  request;
        HttpServletResponse response;

        try {
             // Downcast ServletRequest and ServletResponse to HttpServletRequest and HttpServletResponse with Http
            request = (HttpServletRequest) req;
            response = (HttpServletResponse) res;
        } catch (ClassCastException e) {
            throw new ServletException(lStrings.getString("http.non_http"));
        }
        // Call the overloaded service method.
        service(request, response);
    }

    // Both parameters of this service method are with Http. 
    // This service is a template method. 
    // Define the core algorithm skeleton in this method, and the specific implementation steps are delayed to the subclass to complete. 
    protected  void  service (HttpServletRequest req, HttpServletResponse resp) 
        throws ServletException, IOException {
         // Get the request method 
        // This request method may eventually be: "" 
        // Note: the request.getMethod() method obtains the request method, which may be seven One of the species: 
        // GET POST PUT DELETE HEAD OPTIONS TRACE
        String method = req.getMethod();

        // If the request method is a GET request, execute the doGet method. 
        if (method.equals(METHOD_GET)) {
             long lastModified = getLastModified(req);
             if (lastModified == - 1 ) {
                 // servlet doesn't support if-modified-since, no reason 
                // to go through further expensive logic
                doGet(req, resp);
            } else {
                long ifModifiedSince;
                try {
                    ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
                } catch (IllegalArgumentException iae) {
                    // Invalid date header - proceed as if none was set
                    ifModifiedSince = -1;
                }
                if (ifModifiedSince < (lastModified / 1000 * 1000)) {
                    // If the servlet mod time is later, call doGet()
                    // Round down to the nearest second for a proper compare
                    // A ifModifiedSince of -1 will always be less
                    maybeSetLastModified(resp, lastModified);
                    doGet(req, resp);
                } else {
                    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                }
            }

        } else if (method.equals(METHOD_HEAD)) {
            long lastModified = getLastModified(req);
            maybeSetLastModified(resp, lastModified);
            doHead(req, resp);

        } else  if (method.equals(METHOD_POST)) {
             // If the request method is a POST request, execute the doPost method.
            doPost(req, resp);

        } else if (method.equals(METHOD_PUT)) {
            doPut(req, resp);

        } else if (method.equals(METHOD_DELETE)) {
            doDelete(req, resp);

        } else if (method.equals(METHOD_OPTIONS)) {
            doOptions(req,resp);

        } else if (method.equals(METHOD_TRACE)) {
            doTrace(req,resp);

        } else {
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //

            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[1];
            errArgs[0] = method;
            errMsg = MessageFormat.format(errMsg, errArgs);

            resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, errMsg);
        }
    }


    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException{
        String msg = lStrings.getString("http.method_get_not_supported");
        sendMethodNotAllowed(req, resp, msg);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
        String msg = lStrings.getString("http.method_post_not_supported");
        sendMethodNotAllowed(req, resp, msg);
    }

}

Through the above source code analysis:
assuming that the request sent by the front-end is a get request, the method rewritten by the back-end programmer is doPost, assuming that the request sent by the front-end is a post request, and the method rewritten by the back-end programmer is doGet, what will happen? ?
An error like 405 occurs.
405 indicates an error in the front end, and the request sent is incorrect. inconsistent with the server. Not the way the server needs to request.

From the above source code, we can know that as long as the doGet method or doPost method in the HttpServlet class is executed, it must be 405.

How to avoid 405 errors?
The back-end rewrites the doGet method, and the front-end must send a get request. The back-end rewrites the doPost method, and the front-end must send a post request. This avoids 405 errors.

​ In fact, what kind of request needs to be sent by the front end should be decided by the back end. The way the back end lets you send it, the way the front end has to send it.
​​Some
people, you will see that in order to avoid 405 errors, in the Servlet class, both the doGet and doPost methods have been rewritten. This can indeed avoid the occurrence of 405, but it is not recommended, 405 errors are still useful. When it’s time to report an error, let him report an error. If you override doGet and doPost at the same time, you might as well override the service method directly. This way you can write less code.

20.7 The HelloServlet we wrote directly inherits HttpServlet and directly rewrites the service() method in the HttpServlet class?

  • Yes, you just don’t enjoy 405 errors. Enjoy nothing specific to the HTTP protocol.

20.8 The final development steps of a Servlet class:

  • Step 1: Write a Servlet class that directly inherits HttpServlet
  • The second step: rewrite the doGet method or rewrite the doPost method, whoever rewrites, the javaweb programmer has the final say.
  • Step 3: Configure the Servlet class into the web.xml file.
  • Step 4: Prepare the front-end page (form form), the action value in the html page is “/project name/path”, and the request path can be specified in the form form.

21 Welcome page about a web site

21.1 What is the welcome page of a web site?

For a webapp, we can set its welcome page. After setting the welcome page, when you visit the webapp or the web site without specifying any “resource path”, your welcome page will be accessed by default.

Our general access methods are:

  • http://localhost:8080/servlet06/login.html This method specifies the login.html resource to be accessed.

If we access the way:

  • http://localhost:8080/servlet06 If we are visiting this site, no specific resource path is specified. It will visit the welcome page you set by default.

21.2 How to set the welcome page?

Step 1: I created a new file login.html in the web directory of the IDEA tool

Step 2: The following configuration is made in the web.xml file

  • <welcome-file-list>
    <welcome-file>login.html</welcome-file>
    </welcome-file-list>

  • Note: When setting up the welcome page, the path does not need to start with “/”. And this path is searched from the root of the webapp by default.

Step 3: Start the server and enter the address in the browser address bar

  • http://localhost:8080/servlet07

21.3 If a new directory is created under the root of the webapp, and another file is given in the directory, how should the welcome page be set?

  • Create a new page1 under the webapp root

  • Create a new page2 directory under page1

  • Create a new page.html page in the page2 directory

  • It should be configured like this in the web.xml file

    • <welcome-file-list>
      <welcome-file>page1/page2/page.html</welcome-file>
      </welcome-file-list>

    • Note: The path does not need to start with “/”, and the path is searched from the root of the webapp by default.

21.4 A webapp can have multiple welcome pages

  • <welcome-file-list>
    <welcome-file>page1/page2/page.html</welcome-file>
    <welcome-file>login.html</welcome-file>
    </welcome-file-list>

  • Note: The higher the priority, the higher the priority. If you can’t find it, keep looking down.

21.5 There is no need to configure the welcome page in the web.xml file when the filename is set to index.html.

This is because the kitty Tomcat server has been configured in advance.

There are actually two places to configure the welcome page:

  • One is in the web.xml file inside the webapp. (The configuration in this place belongs to the local configuration)

  • One is to configure in the CATALINA_HOME/conf/web.xml file. (The configuration in this place belongs to the global configuration)

    • <welcome-file-list>
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.htm</welcome-file>
      <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>

    • The global welcome page for the Tomcat server is: index.html index.htm index.jsp. If you do not have a partial welcome page for a web site, the Tomcat server will use index.html index.htm index.jsp as the welcome page for a web site.

  • Pay attention to the principle: the principle of local priority. (The principle of proximity)

21.6 Can the welcome page be a servlet?

  • sure.

  • Don’t think too much, the welcome page is a resource. Since it is a resource, it can be a static resource or a dynamic resource.

  • Static resources: index.html welcome.html …

  • Dynamic resources: Servlet classes.

  • step:

    • Step 1: Write a Servlet

      • public class WelcomeServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.print("<h1>welcome to bjpowernode!</h1>");
        }
        }
    • Step 2: Configure the servlet in the web.xml file

      • <servlet>
        <servlet-name>welcomeServlet</servlet-name>
        <servlet-class>com.bjpowernode.javaweb.servlet.WelcomeServlet</servlet-class>
        </servlet>
        <servlet-mapping>
        <servlet-name>welcomeServlet</servlet-name>
        <url-pattern>/fdsa/fds/a/fds/af/ds/af/dsafdsafdsa</url-pattern>
        </servlet-mapping>
    • Step 3: Configure the welcome page in the web.xml file

      • <welcome-file-list>
        <welcome-file>fdsa/fds/a/fds/af/ds/af/dsafdsafdsa</welcome-file>
        </welcome-file-list>

22 About the WEB-INF directory

  • A new file is created in the WEB-INF directory: welcome.html
  • Open a browser to visit: http://localhost:8080/servlet07/WEB-INF/welcome.html A 404 error occurred.
  • Note: Resources placed in the WEB-INF directory are protected. Direct access via path is not available on browsers. Therefore, static resources such as HTML, CSS, JS, and image must be placed outside the WEB-INF directory.

You may also like...

Leave a Reply

Your email address will not be published.