This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021 “.

Author: Java Academic Party

Repositories: Github, Gitee

Blogs: CSDN, Nuggets, InfoQ, Cloud + Community

Public account: Java Academic Party

Special statement: the original is not easy, shall not be reproduced or copied without authorization, if you need to reproduce can contact xiaobian authorization

Copyright notice: part of the text or pictures in the article comes from the Internet and Baidu encyclopedia, if there is infringement, please contact xiaobian as soon as possible. Wechat search public Java academic party contact xiaobian.

Everybody is good! I am your old friend Java Academic Party, today continue to share with you the Servlet specification, Servlet (Server apet) is short for Java Servlet, called small service program or service connector, written in Java server-side program, has the characteristics of platform and protocol independent. The main function is to interactively browse and generate data and generate dynamic Web content.

The narrow sense of Servlet refers to an interface implemented by Java language, and the broad sense of Servlet refers to any class that implements this Servlet interface. Generally, people understand Servlet as the latter. Servlets run in Java-enabled application servers. In principle, servlets can respond to any type of request, but most of the time servlets are only used to extend HTTP-based Web servers.

The first Java Web Server to support the Servlet standard was JavaSoft, and since then, several other Java-based Web servers have started to support standard servlets.

1. Introduction to Servlet specifications

The Servlet container, as the name suggests, houses Servlet objects

  1. The Servletg specification comes from one of the JAVAEE specifications
  2. Function:
    1. In the Servlet specification, specify the dynamic resource file development step
    2. In the Servlet specification, specify the HTTP server to invoke dynamic resource file rules
    3. In the Servlet specification, specify the HTTP server to manage dynamic resource file instance object rules

2. Servlet interface implementation class

  1. The Servlet interface is derived from an interface under the Servlet specification that contains jar packages provided by the HTTP server.

  2. Javax.servlet.servlet (javax.servlet.servlet)

  3. In the servlet specification, the dynamic resource file that the HTTP server can call must be an implementation class of the servlet interface. Example: class Student{// not a dynamic resource file, Tomcat cannot be called} class Teacher implements Servlet{

Tomcat has the right to call Servlet obj = new Teacher(); obj.doGet(); }

3. Servlet interface implementation class development steps

  • Step 1: Create a Java class that inherits from the HttpServlet parent class, making it a Servlet interface implementation class.

  • Step 2: Override the two methods of the HttpServlet parent class. DoGet or doPost

    ​ get

    Web browser ——-> oneservlet.doget ()

    ​ post

    Browser ——-> oneservlet.dopost ()

  • Step 3: Register the Servlet interface implementation class information to the Tomcat server

    [Website] --> [web] --> [WEB-INF] --> web.xmlCopy the code

    Hand the classpath address of the Servlet interface implementation class to Tomcat

    <servlet>
        <! Declare a variable store servlet interface to implement class classpath -->
        <servlet-name>mm</servlet-name> 
        <! Declare the classpath of a servlet interface implementation class.
        <servlet-class>com.com.yunbocheng.cntroller.OneServlet</servlet-class>
    </servlet>
    
    Tomcat String mm = "com.yunbocheng.controller.OneServlet"
    
    <! To make it easier for users to access the Servlet interface implementation class, you need to set a short request alias -->
    <servlet-mapping>
        <servlet-name>mm</servlet-name>
        <! -- Set short request alias, alias must start with "/" when written -->
        <url-pattern>/one</url-pattern>
    </servlet-mapping>    
    Copy the code

    If the browser now asks Tomcat for the OneServlet address

    http://localhost:8080/myWeb/one

4. Lifecycle of Servlet objects

  1. Instance objects of all Servlet interface implementation classes on the site can only be created by the HTTP server.

    Developers cannot manually create instance objects of Servlet interface implementation classes directly.

  2. By default, the HTTP server receives the first request for the current Servlet interface implementation class

    • Automatically creates an instance object of this Servlet interface implementation class.

    • In the case of manual configuration, the HTTP server is required to automatically create a Servlet interface implementation class at startup

    Instance object of

    <servlet>
        <! Declare a variable store servlet interface to implement class classpath -->
        <servlet-name>mm</servlet-name> 
        <! Declare the classpath of a servlet interface implementation class.
        <servlet-class>com.com.yunbocheng.cntroller.OneServlet</servlet-class>
        <! Enter an integer greater than 0 -->
        <load-on-startup></load-on-startup>
    </servlet>
    Copy the code
  3. During the running of our HTTP server, only one instance object can be created from a Servlet interface implementation class.

  4. When the HTTP server is down, all Servlet objects for the site are automatically destroyed.

5. The HttpServletResponse interface

  1. Introduction:
    • The HttpServletResponse interface is derived from the Servlet specification, and servlet-api.jar exists in Tomcat
    • The HttpServletResponse interface implementation class is provided by the Http server
    • The HttpServletResponse interface is responsible for writing the results of the doGet/doPost method execution to the response body for the browser
    • Developers are used to referring to objects modified by the HttpServletResponse interface as response objects.
  2. Main functions:
    1. Write the execution result to the response body in binary form.
    2. Set the value of the [content-type] attribute in the response header to control the browser to use the corresponding compiler to compile the response body binary data into text, image, video, command.
    3. Sets the [location] property in the response header to assign a request address to location to control the browser to send a request to the specified server.

6. It interfaces

  1. Introduction:
    1. The HttpServletRequest interface is derived from the Servlet specification, and servlet-api.jar exists in Tomcat
    2. The HttpServletRequest interface implementation class is provided by the Http server
    3. The HttpServletRequest interface is responsible for reading information from the Http request protocol packet when the doGet/doSet methods run
    4. The object that the HttpServletRequest interface decorates is called the request object by the developer
  2. Function:
    1. It is possible to test the [request line] information in the Http request package :(code is in the OneServlet class)
    2. Can read request parameters stored in the Http request header or request body :(code in the TwoServlet class and two.html three.html)
    3. You can request resource file calls to the Http server instead of the browser

7. Lifecycle of request object and response object

  1. After the Http server receives the Http request packet sent by the browser,

    Automatically generate a request object and a response object for the current Http request packet.

  2. When the child Http server calls the doGet/doPost method, it is responsible for combining the request object and the response object.

    Pass it as an argument to the method to make sure doGet/doPost executes correctly.

  3. Before the Http server pushes the Http response packet, it is responsible for associating the request object with the response object.

    Destroyed.

    The Request object and response object life cycles run through the processing of a request.

    Request object and Response Object are the representatives of users on the server side

8. Welcome resource files

  1. Premise:

    Users can remember the site name, but not the file name of the site resource

  2. Welcome resource file by default:

    When a user sends a default request for a web site, the Http server automatically returns it from the current web page

    Resource file of

    Normal request: http://localhost:8080/MyWeb/index.html

    The default request: http://localhost:8080/MyWeb

  3. Note: Each HTTP server is different for the default request, and the Tomcat server is used for simplification

    Single introduction, the rest of their own understanding.

  4. Tomcat has a default welcome resource file location rule

    • Rule location: Tomcat location /conf/web.xml

    • Rule command :(searches from index. HTML until it finds index. JSP, and returns if none is found

      404).

      <welcome-file-list>
      
      <welcome-file>index.html</welcome-file>
      <welcome-file>index.html</welcome-file>
      
      <welcome-file>index.htm</welcome-file>
      
      <welcome-file>index.jsp</welcome-file>
      
      </welcome-file-list>
      Copy the code
  5. Set the default welcome resource file rules for the current site (modify the default opening interface to look like you want)

    • Rule location: web/ web/WEB-INF/web.xml (change to the default request you want)

    • Rule command:

      <welcome-file-list>
      
      <welcome-file>login.html</welcome-file>(Login. HTML is the default custom request)</welcome-file-list>
      Copy the code
    • If you set default file location rules for websites, the Tomcat location rules become invalid

  6. Welcome that resource files can write to both static and dynamic resource files.

    <welcome-file-list>
    
    <! -- Dynamic resource file as the default welcome resource file, the leading slash must be removed -->
    <welcome-file>user/find</welcome-file>
    <! Static resource files welcome resource files by default.
    <welcome-file>login.html</welcome-file>(Login. HTML is the default custom request)</welcome-file-list>
    Copy the code

9. The Http status code

  1. Introduction:

    1. A symbol consisting of three digits.
    2. Before sending the packet, the Http server writes the Http status code to the status line of the corresponding packet based on the processing of the request.
    3. Function:
      • If the Http server returns the corresponding resource file for this request. The Http status code informs the browser what to do with the result.
      • If the Http server fails to return the resource file for this request, use the Http status code to explain the service failure to the browser.
  2. Classification:

    1. Composition: 100– 599: Divided into 5 categories

      • 1XX: 100: notifies the browser that the returned resource file is not an independent resource file. After receiving the response package, the browser needs to continue to refer to other resource files that the Http server depends on.

      • 2XX: the most characteristic is 200, notify the browser this return resource file is a complete and independent file, clear

        Browsers do not need to ask for other associated files after receiving them.

      • 3XX: Most characteristic 302 notifies the browser that instead of returning a resource file content, it is returning a resource file

        The browser automatically initiates a request case based on the address to request the resource file.

        Response.sendredirect (” resource file address “) is written to location in the response header

        This behavior causes Tomcat to write the 302 status code to the status line

      • 4 xx:

        404: Notifies the browser that the service cannot be provided because the accessed resource file cannot be located on the server

        405: Notifies the browser that the server has located the accessed resource file (Servlet) but that the Servlet

        Cannot handle requests made by the browser, such as a link entered in the address bar

        The doPost method is only implemented in the implementation class

        405 is reported when processing a request from Get.

      • 5XX: 500 error in Java code, is the resource file found?

        It may be a null pointer exception or some other error, and there will be an error message on the server.

10. Call rules between multiple servlets

  1. Browsers can only access one resource file at a time (that is, only one Servlet can be requested at a time)

  2. Premise:

    Some requests are sent from the browser and often require multiple servlets on the server.

    However, the browser can only access one Servlet at a time, resulting in the user having to manually navigate through the browser

    Make multiple requests to get the service.

    This makes it difficult to obtain services and causes users to give up visiting the current site

  3. Rules for improving user experience:

    No matter how many servlets are involved in this request, the user only needs to [manually] tell the browser to initiate a request.

  4. Call rules between multiple servlets

    1. Redirect the solution
    2. Request forwarding scheme

11. Redirect the solution

  1. How it works: The user first notifes the browser to access OneServlet [manually], and when OneServlet is done, the TwoServlet address is written to the location property in the response header, causing Tomcat to write the 302 status code to the status line.

    After the browser receives the corresponding package, it reads the 302 state, which the browser automatically reads according to the response header

    The location property address makes a second request to access the TweServlet to do the rest.

  2. Implementation command:

    Response. sendeRedirect (” Request address “)

    Writes the address to the location property in the response header of the corresponding package

  3. Features:

    • Request address: you can send the address of the resource file in the current website to the browser.

      You can also send the url of the resource file to the browser.

      (http://ip address: port number/network name/resource name)

    • Number of requests: The browser must send at least two requests, but the user sent the first request manually. Subsequent requests are automatically sent by the browser.

    • Request mode: In the redirection solution, the address bar notifies the browser to initiate the next request, so the resource file called by the redirection solution must receive the request mode [GET].

  4. Disadvantages: The redirection ending solution requires multiple round trips between the browser and the server, and a lot of time is spent going back 8 times, increasing the user’s waiting time for service.

12. Request forwarding solution

  1. How it works: The user first manually asks the browser to access OneServlet, and when OneServlet is done, the current request object sends a request to Tomcat instead of the browser to invoke TwoServlet. Tomcat automatically calls TwoServlet to complete the rest of the tasks after receiving the TwoServlet.

  2. Implementation command: The request object sends the request to Tomcat instead of the browser

    1. Generate a resource file request report object from the current request object

      RequestDispatcher request = request. GetRequestDispatcher (“/resource file name “);

      Note: Resource file names must start with a “/”.

    2. Send the report object to Tomcat

      Report. Forward (current request object, current response object)

13. Implementation scheme of data sharing among multiple servlets

  1. Data sharing: When OneServlet is done, the resulting data is handed over to twoServlets for use.
  2. The Servlet specification provides four data sharing schemes
    1. The ServletContext interface
    2. Cookie interface
    3. The HttpSession interface
    4. HttpServleRequest interface

14. The ServletContext interface

  1. Introduction:

    1. Comes from an interface in the Servlet specification. Servlet-api.jar exists in Tomcat

      Responsible for providing this interface implementation class in Tomcat

    2. If two servlets are from the same site. Each other through the ServletContext of the site

      The instance object implements data sharing.

    3. Developers refer to the ServletContext object as a global scope object

  2. How it works: Every web site has a global scoped object, which is a Map where OneServlet can store a piece of data into the global scoped object, which other servlets in the current web site can use at this point.

  1. Global scope object life cycle

    1. During Http server startup, a global scoped object is automatically created in memory for the current web site.
    2. During Http server running, a web site has only one global scoped object
    3. Global scoped objects remain alive for the duration of the Http server
    4. Responsible for destroying global scoped objects in the current web site when the Http server is ready to shut down

    The global scoped object life cycle runs through the current web site

  2. OneServlet shares data with TwoServlet

    ! [] (img – blog. Csdnimg. Cn/img_convert…

15. The cookie interface

  1. Introduction:

    1. Cookies come from a utility class in the Servlet specification and exist in the servlets-api.jar provided by Tomcat

    2. If both servlets are from the same web site and serve the same browser/user

      Data is shared with cookie objects.

    3. Cookies store private data of the current user and improve service quality during data sharing

    4. In real life scenarios, cookies are equivalent to users getting [membership card] on the server.

  2. Working principle:Note: Cookies only exist in the request header of the request package, and in the response header of the response package.

  3. Implementation command: The same site OneServlet and TwoServlet use cookies to implement data sharing

16.Cookie destruction time

  1. By default, Cookie objects are stored in the browser’s cache,

    So as soon as the browser closes, the COokie object is destroyed.

  2. With manual Settings, you can ask the browser to accept cookies

    Store in the client computer hard disk, at the same time need to specify the Cookie in

    Lifetime on hard disk. Within the lifetime range, close browser close

    The client computer, shutting down the service, does not cause cookies to be destroyed.

    When the keepalive time reaches, the Cookie is automatically deleted from the hard disk

    cookie.setMaxAge(60); // The cookie lives on the hard disk for one minute.

  3. Note: it is very important to set the survival time above. Principle: When the specified time is reached, the Cookie will be automatically logged off and the user’s information will disappear. For example, when the membership card expires, it can not be used after the expiration, membership card expires, in fact, the Cookie inside the automatic destruction, at this time can not query the user’s information. Expired card.

17. The HttpSession interface

  1. Introduction:

    1. The HttpSession interface is derived from the next interface of the Servlet specification. Servlet-api.jar exists in Tomcat

      The implementation classes are provided by the Http server. Tomcat provides implementation classes that exist in servlet-api.jar.

      2. If two servlets are from the same site and serve the same browser/user,Copy the code

      The HttpSession object is used to share the data.

      3. HttpSession interface modifiers are called session scoped objects.Copy the code
  2. HttpSession vs. Cookie

    1. Storage location:

      Cookie: Stored on the client computer (browser memory/hard disk)

      HttpSession: Stored in server computer memory

    2. Data type:

      Cookie Object storage shared data type can only be String

      The HttpSession Object can store any type of shared data Object

    3. Number of data

      A Cookie object can store only one shared data and only one key-value pair

      A Cookie is a little box that can only hold strings

      HttpSession uses a Map collection to store shared data, so any amount of shared data can be stored

      HttpSession is a big box that can store any data type.

    4. reference

      Cookie is equivalent to the customer’s [membership card] on the server

      HttpSession is the client’s private safe on the server side.

    5. Command implementation:

    6. How does an Http server associate a user with an HttpSession: Cookie

    7. GetSession () differs from getSession(false)

      1. GetSession (): If the current user already has a private locker on the server,

        Ask Tomcat to return the private locker

        If the current user does not have a private locker on the server,

        Tomcat is required to create a new private locker for the current user.

      2. GetSession (false) : If the current user already has a private locker on the server,

        Ask Tomcat to return the private locker.

        If the current user does not have a private locker on the server,

        Tomcat will return NULL.

    8. HttpSession destruction time:

      1. Cookies that users associate with HttpSession can only be stored in the browser cache

      2. When the browser closes, it means that the user is cut off from his HttpSession relationship.

      3. Since Tomcat cannot detect when the browser is closed, it does not detect when the child browser is closed

        Causes Tomcat to destroy the HttpSession associated with the browser.

      4. To solve this problem, Tomcat sets the idle time for each HttpSession object.

        The default idle time is 30 minutes, if the current HttpSession object is idle for 30 minutes

        At this point Tomcat determines that the user has abandoned his HttpSession, at which point Tomcat will destroy it

        Drop this HttpSession.

    9. Manual setting of HttpSession idle time

      In the current web site /web/ web-INF /web.xml

      <session-config>
          <! The maximum idle time in the current site is 5 minutes -->
          <session-timeout>5</session-timeout>
      </session-config>
      Copy the code

Shopping cart management system demonstrates HttpSession interface usage

  1. Working principle diagram

19. HttpServletRequest interface implements data sharing

  1. Introduction:

    • In the same site, if two servlets are called through request forwarding,

      Share the same request protocol package with each other. A request protocol packet corresponds to only one request object,

      As a result, the same request object is shared between servlets

      Data is shared between the two servlets.

    • When a request object implements data sharing between servlets, developers refer to the request object as a request scoped object.

  2. Command implementation: When OneServlet invokes TwoServlet through request forwarding request, it needs to provide shared data to TwoServlet

    20. The Servlet specification extends the ——– listener interface

    1. Introduction:

      • One set of eight interfaces from the Servlet specification. The servlet-api.jar package exists in Tomcat
      • The listener interface needs to be implemented by the developer; the Http server provides jar packages without corresponding implementation classes
      • The listener interface is used to monitor the time when the scope object declaration cycle changes and the time when the scope object shared data changes.
    2. Scope object:

      • Under the Servlet specification, an object in server memory that is considered capable of providing a data sharing scheme between two servlets under certain conditions is called a scoped object.

      • Scoped objects under the Servlet specification:

        ServletContext: Global scope object

        HttpSession: session scoped object

        HttpServletResquest: Request scope object

    3. Listener interface implementation development specification: three steps

      • According to the actual situation of listening, select the corresponding listener interface to implement.
      • Overwrite listener interface declaration
      • On the Web, the XML file registers the listener interface implementation class with the Http server
    4. ServletContextListener interface:

      1. Function: This interface is used to legitimately detect the initialization and destruction of a global scope object.

      2. Listening event handling method:

        Publlic void contextInitlized() : called when the global scope object is initialized

        Public void contextDestory() : triggered when the global scope object is destroyed by the Http server

    5. ServletContextAttributeListener interface:

      1. Use this interface to legitimately detect changes in the shared data of global scoped objects

      2. Listening event handling method:

        Publlic void contextAdd() : Adds shared data to the global scope object

        Publlic void contextReplaced() : Updates shared data on a global scoped object

        Publlic void contextRemove() : Deletes shared data in the global scope object

    6. Global scope objects share data when data changes:

21. Servlet specification extension ———– Filter


22. Filters enhance intercepted requests

The diagram above represents a server with 100 servlets. You need to use the doPost method every time you call any Servlet,

When using doPos, you have to rewrite the encoding because doPost’s default encoding is not UTF-8, which will cause garbled characters when compiling Chinese

At this point, it would be troublesome to recompile all 100 servlets, so you can use listeners to filter all 100 servlets

Add the req,setCharacterEncoding(UTF-8) method to each Servlet, and you can re-encode 100 servlets at a time, which is huge

Development time.

23.Filter Intercepts the address format

  1. Command format:

    <filter-mapping>
        <fileter-name>OneFilter</fileter-name>
        <url-pattern>Intercept address</url-pattern>
    </filter-mapping>
    Copy the code
  2. Command function:

    OneFilter filtering is required before the intercepting address tells Tomcat which resource file to call

  3. Require Tomcat to call OneFilter interceptor before calling a specific file.

    <url-pattern>/ img/handsome guy. JPG</url-pattern>// This is the img folder under the handsome.jpgCopy the code
  4. Require Tomcat to call OneFilter interceptor before calling all resource files in a folder (development use)

    <url-pattern>/img/*</url-pattern>// All files in the img folder are blockedCopy the code
  5. Requires Tomcat to call OneFilter interception before calling a type of file in any folder (development use)

    <url-pattern>*.jpg</url-pattern>// Block JPG files in any folderCopy the code
  6. Tomcat is required to call any file on the site to invoke OneFilter interception

    <url-pattern>*</url-pattern>// All files in the web site are blockedCopy the code

24. Filters prevent malicious login behaviors

Token mechanism: fairly and double duty mechanism, when the user use account and password after login successfully, the first job is the login page will also give the user a new token, the token used in the resource file before the call of the second recognition, identified by only two times, only the resource file will be returned to the user’s browser.

Malicious behavior: He will not pass the first post, the user login page, will not get the token he wants, and will not be assigned a resource file on the second identification. The first post the malicious act passes (the user login post) will not get the token and will be intercepted at the second post.

<! HttpSession request for the current user -->
<! -- This method is equivalent to generating a private safe for the user in the user login interface, only in the login interface can allocate this cabinet, and the hacker over the wall did not go through the login page, so it will not be allocated to the private safe -->
<! The getSeeion method takes no arguments and creates a new private safe for the user without judgment -->
<! GetSession (false) is used everywhere else in the logon process. GetSession (false) is used everywhere else in the logon process. GetSession (false) is used everywhere else.
HttpSession session = request.getSession();
<! Request HttpSession for the current user on the server.
<! If the current user has a cabinet on the server, return the cabinet, otherwise return NUll-->
HttpSession session = request.getSession(false);   
if(session == null){
	response.sendRedirect("/myWeb/login_error.html");
	return;
}else{
	
}
Copy the code

JavaWeb general flow chart


26. Preventing malicious login by users (implementation of token mechanism)

In this case, the login page should display some relevant elements, such as login box, text box, JS code, etc. These are set to login so that the user can see these elements being used without any authentication. That is, direct release, no filter filtering.

The element associated with the login page is set to login.

HttpServletRequest request = (HttpServlrtRequest)servletRequset;
HttpSession session = null;  
// 1. Call the request object to read the URI of the request line in the request object package to learn who the user's resource file is
// myWeb/login. HTML or /myWeb/login
String uri = request.getRequestUrI();   
// 2. If the requested resource file is related to login [login. HTML or LoginServlet], it should be allowed unconditionally
// indexOf returns the first occurrence of the current login field in the uri string
// If the string does not exist in the URI, -1 is returned
// If it is not equal to -1, the uri string contains the file login, which means that the file is associated with our login
// The file is cleared unconditionally.
/* If the user only writes the name of the site to visit and does not provide the specific file to visit, then according to the rules of the site's default welcome file, he will look for the default resource file login. HTML in the web. XML file (which is also written by himself) and call */
if(uri.indexOf("login") != -1 || "/myWeb/".equals(uri)){
    // Return the intercepted request object and response object to Tomcat for release processing
    filterChain.doFilter(servletRequest,ServletResponse);
    return;
}
// 3. If the request is to access another resource file, you need to obtain the user's HttpSession on the server
// getSession(false); HttpSession is returned if it exists on the server, null if it does not exist, and no HttpSession is created
session = request.getSession(false);
// Check whether the user has an HttpSession, if there is, do not allow, if not (possible hacker)
if(session ! =null) {// Legitimate users return intercepted request objects and response objects to Tomcat for release processing
    filterChain.doFilter(servletRequest,ServletResponse);
    return;
}
// 4. If no Httpsession exists on the server, the login is considered malicious and the access is denied
// login_error.htm is your own folder in the Web directory, where you write some instructions not to access
request.getRequestDispatcher("/login_error.html").forward(servletRequest,ServletResponse);
Copy the code

Above project source code,Click planet to get it for freeplanet(making address)If I didn’t have my Github buddies. You can follow my wechat official account:Java academic lie prone, send Servlet, free to send you the project source code, the code is personally tested by xiaobian, absolutely reliable. It’s free to use.

——– after watching the big guys can pay attention to the small make up, will always update the small skills, free to share with you!! ———

Click planet to get to Github planet!! There are more fun technologies waiting for you to explore!!