In depth analysis of Java Web

Posted by Deltran on Fri, 24 Dec 2021 01:57:44 +0100

1. Basic concepts

1.1. Static web

1.2 dynamic web

2. web server

  • lIS
  • Tomcat

3,Tomcat

  • The default port number of tomcat is 8080
  • mysql: 3306
  • http: 80
  • https: 443

4,Http

4.1 concept

  • Http: (Hypertext Transfer Protocol) is a simple request response protocol, which usually runs on TCP; port: 80
  • Https: Secure Hypertext transmission protocol; Port: 443

4.2 two times

  • http1.0
    • HTTP/1.0: after the client can connect to the web server, it can only obtain one web resource and disconnect
  • http2.0
    • HTTP/1.1: after the client can connect with the web server, it can obtain multiple web resources.

4.3 Http request

  • Client – Request – server
Request URL:https://www.baidu.com / request address
Request Method:GET    get method/post method
Status Code:200 OK    Status code: 200
Remote((remote) Address:14.215.177.39:443

Accept:text/html  
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.9    language
Cache-Control:max-age=0
Connection:keep-alive

1) Request line

  • Request method in request line: GET
  • Request method: get, post, head, delete, put, trace
    • get: the request can carry few parameters with limited size. The data content will be displayed in the URL address bar of the browser. It is unsafe but efficient
    • post: there is no limit on the number and size of parameters that the request can carry. The data content will not be displayed in the URL address bar of the browser. It is safe but inefficient

2) Message header

Accept: Tell the browser what data types it supports
Accept-Encoding: Which encoding format is supported  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language: Tell the browser its locale
Cache-Control: Cache control
Connection: Tell the browser whether to disconnect or remain connected when the request is completed
HOST: host..../

4.4 Http response

  • Server – response client
Cache-Control:private    Cache control
Connection:Keep-Alive    connect
Content-Encoding:gzip    code
Content-Type:text/html   type 

1) Responder

Accept: Tell the browser what data types it supports
Accept-Encoding: Which encoding format is supported  GBK   UTF-8   GB2312  ISO8859-1
Accept-Language: Tell the browser its locale
Cache-Control: Cache control
Connection: Tell the browser whether to disconnect or remain connected when the request is completed
HOST: host..../.
Refresh: Tell the client how often to refresh;
Location: Repositioning the web page;

2) Response status code

  • 200: request response succeeded 200
  • 3xx: request redirection · redirection: you go back to the new location I gave you;
  • 4xx: resource not found 404 · resource does not exist;
  • 5xx: server code error 500 502: gateway error

5,Maven

6,Servlet

  • Servlet is a technology for sun company to develop dynamic web
  • Servlet is a server-side technology
  • The Servlet receives the user request and responds to the request

6.1 class I structure

6.2,web.xml configuration

<!--statement/register-->
<servlet>
    <servlet-name>hello</servlet-name>
    <servlet-class>com.tuwer.HelloServlet</servlet-class>
</servlet>
<!--mapping-->
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/h/hello</url-pattern>
</servlet-mapping>

mapping problem

  • You can specify one, multiple, common, and default mapping paths
<!--One-->
<servlet-mapping>
    <servlet-name>hello</servlet-name>    
    <url-pattern>/hello</url-pattern>
</servlet-mapping>
<!--Multiple-->
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello1</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello2</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello3</url-pattern>
</servlet-mapping>
<!--currency-->
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/hello/*</url-pattern>
</servlet-mapping>
<!--default-->
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
  • You can specify mapping paths such as suffixes or prefixes
<!--You can customize the suffix to implement request mapping
      Be careful,*The path of the project mapping cannot be preceded
      hello/sajdlkajda.do
      -->
<servlet-mapping>
    <servlet-name>hello</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
  • Priority issues

    The inherent mapping path is specified with the highest priority. If it is not found, the default processing request will be taken

6.3,ServletContext

Singleton mode: it represents the current web application and is unique

1) Data sharing

Data sharing between different servlets can be realized

  • Can be shared across session s; E.g. statistics of online personnel

2) Get initialization parameters

  • web. Configuring initialization parameters in XML
<!--Configure some web Application initialization parameters-->
<context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
  • Get parameters
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // this indicates the current application itself
    // Req can also get req getServletContext();
    ServletContext context = this.getServletContext();
    String url = context.getInitParameter("url");
    resp.getWriter().print(url);
}

3) Request forwarding

ServletContext context = this.getServletContext();
RequestDispatcher requestDispatcher = context.getRequestDispatcher("/db");
requestDispatcher.forward(req,resp);

When a request is forwarded, the data in the request scope will be carried forward

There is no need to explicitly add getContextPath() to the forwarded url

4) Read resource file

  • Properties class
  • classpath path
  • File stream
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties");

    Properties prop = new Properties();
    prop.load(is);
    String user = prop.getProperty("username");
    String pwd = prop.getProperty("password");

    resp.getWriter().print(user+":"+pwd);
}

6.4,HttpServletResponse

Response to client

1) Overview

HttpServletResponse is an interface that inherits from the ServletResponse interface

public interface HttpServletResponse extends ServletResponse {}
  • Method responsible for sending data to browser
public interface ServletResponse {
   public ServletOutputStream getOutputStream(); 
} 
  • Method responsible for sending response header to browser
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String varl,long var2)
void addDateHeader(String var1,long var2)
void setHeader(String var1,String var2);
void addHeader(String var1,String var2);
void setIntHeader(String var1,int var2);
void addIntHeader(String varl,int var2);
  • Response status code

2) Download File

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1. Get the file path to download
    String filePath = "xxx.jpg";
    // 2. Get file name
    String filename = filePath.substring(filePath.lastIndexOf("\\")+1);

    // 3. Set Header: support Chinese
    resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf8"));

    // 4. Get file input stream
    //InputStream bis = new FileInputStream(filePath);
    // BufferedInputStream is more efficient
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(filePath),1024);

    // 5. Create buffer
    byte[] bytes = new byte[1024];

    // 6. Get output stream
    ServletOutputStream os = resp.getOutputStream();

    // 7. Write buffer
    int length = 0;
    while((length = bis.read(bytes)) > 0){
        // 8. Output
        os.write(bytes,0,length);
    }

    // 9. Shut down
    bis.close();
    os.close();
}

3) Verification code

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // ---Define image---
    BufferedImage image = new BufferedImage(80, 20, BufferedImage.TYPE_INT_BGR);

    // ---Get a brush---
    Graphics2D g = image.createGraphics();

    // ---Set background---
    // Set color
    g.setColor(Color.darkGray);
    // Painting background
    g.fillRect(0, 0, 80, 20);

    // ---Draw string---
    // Set color and font
    g.setColor(Color.RED);
    g.setFont(new Font(null,Font.PLAIN,18));
    // Draw string
    g.drawString(getRandomString(4),2,15);

    // ---Response output---
    // Browser refresh in 3 seconds
    resp.setHeader("refresh","3");
    // Content format
    resp.setContentType("image/png");
    // Cancel cache
    resp.setDateHeader("expires",-1);
    resp.setHeader("Cache-Control","no-cache");
    resp.setHeader("Pragma","no-cache");
    // Output: write pictures to the output stream
    ImageIO.write(image,"png",resp.getOutputStream());
}

/**
 * Random number of new words (letters, numbers)
 * @param n Number of random numbers
 * @return character string
 */
private String getRandomString(int n) {
    if (n < 1) {
        n = 1;
    }
    String baseStr = "0123456789abcdefghijklmnopqrstuvwxyz";
    Random r = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < n; i++) {
        int s = r.nextInt(baseStr.length());
        sb.append(baseStr.substring(s,s+1));
    }
    return sb.toString();
}

4) Redirect

@override
protected void doGet(HttpservletRequest req, HttpservletResponse resp) throws ServletException, IOException {

    resp. sendRedirect("/r/img");//redirect
    
    /* Equivalent to
    resp. setHeader("Location","/r/img");
    resp. setstatus (302);
    */
}

6.5,HttpServletRequest

HttpServletRequest represents the request of the client. The user accesses the server through the HTTP protocol. All the information in the HTTP request will be encapsulated in HttpServletRequest. Through this HttpServletRequest method, all the information of the client can be obtained

1) Overview

Similar to HttpServletResponse

HttpServletRequest is an interface that inherits from the ServletRequest interface

public interface HttpServletRequest extends ServletRequest {}

6.6 request forwarding and redirection

  • The same point: the jump of the page will be realized
differenceRequest forwardingredirect
Operation objectServletContext and ServletRequestHttpServletResponse
methodgetRequestDispatcher().forward()sendRedirect()
urlThe address bar url will not change
The data of the scope will be carried and forwarded, including getContextPath(), and there is no need to add it
The url of the address bar will change
getContextPath() should be added to the url

7,Cookie,Session

7.1 conversation

  • Session: users open a browser, click many hyperlinks, access multiple web resources, and close the browser. This process can be called session;
  • Stateful conversation: when a classmate comes to the classroom next time, we will know that the classmate has been here, which is called stateful conversation;

7.2. Two techniques for saving sessions

  • Cookie

    Client Technology (response, request)

  • Session

    Server technology, which can save the user's Session information; You can put information or data in the Session!

7.3,Cookie

Cookie is a class in package javax servlet. Http

Replicable and serializable

package javax.servlet.http;

public class Cookie implements Cloneable, Serializable{}

1) Create Cookie

// constructor 
Cookie(String name, String value)

2) Set validity period

// Set validity period: in seconds
cookie.setMaxAge(24 * 60 * 60);

If the Cookie has no validity period, or if the validity period is 0, it will not be saved after closing the browser

3) Get key name

cookie.getName();

4) Get value

cookie.getValue();

5) Add Cookie

// Add the Cookie to the response object and output it to the browser
response.addCookie(cookie);

6) Get Cookie

// Gets the cookie array of the client
Cookie[] cookies = request.getCookies();

7) Access Chinese

// code
Cookie cookie1 = new Cookie("username", URLEncoder.encode("abc test","utf8"));

// decode
String name = URLDecoder.decode(cookie.getValue(),"utf8");

cookie: usually saved in the local user directory appdata;

  • A Cookie can only save one message
  • A web site can send multiple cookies to the browser and store up to 20 cookies
  • The Cookie size is limited to 4kb
  • Browser limit 300 cookie s

7.4,Session

1) Overview

  • The server will create a Seesion object for each user (browser);
  • A Session monopolizes a browser. As long as the browser is not closed, the Session exists;
  • After the user logs in, it can access the whole website! – > Save user information; Save cart information

HttpSession is an interface in package javax servlet. Http

package javax.servlet.http;

public interface HttpSession {}

2) The difference between Session and cookie

  • Cookie is to write the user's data to the user's browser, and the browser saves it (multiple can be saved)
  • Session writes the user's data to the user's exclusive session and saves it on the server (saves important information and reduces the waste of server resources)
  • The Session object is created by the server

3) Usage scenario

  • Save the information of a logged in user
  • Shopping cart information

4) Get Session

HttpSession session = request.getSession();

5) Attribute attribute

public Object getAttribute(String name);

public void setAttribute(String name, Object value);

public void removeAttribute(String name);

public Enumeration<String> getAttributeNames();

6)ID

public String getId();

7)isNew

// Judge whether the Session is newly created
public boolean isNew();

8)ServletContext

public ServletContext getServletContext();

9) Lapse

(1) Direct failure

public void invalidate();

(2) Set validity period

  • Call method
//(in seconds)
setMaxInactiveInterval(int interval);
  • web. Configuration in XML
<session-config>
    <!--Unit: minutes-->
    <session-timeout>5</session-timeout>
</session-config>

8,JSP

Java Server Pages: Java server-side pages, like servlets, are used for dynamic Web technology!

8.1 essence of JSP

JSP is essentially a Servlet

8.2. Servlet corresponding to JSP

Each JSP file corresponds to a java file (Servlet), which is saved in the work directory of the Tomcat server

For example: index jsp —> index_ jsp. java


8.3 basic grammar

1) JSP expression

<% = start,% > end

In the middle are the values and objects that can be output directly

Used to output the program to the client

<%= new java.util.Date()%>

2) JSP script fragment

<% start,% > end

In the middle is the java code fragment, which will be added to the corresponding java class of JSP_ In the jspService() method

<% 
   int sum = 0;
   for (int i = 1; i <=100 ; i++) {
       sum+=i;    
   }    
   out.println("<h1>Sum="+sum+"</h1>");  
%>

3) JSP declaration

<%! Beginning,% > end

java code segments can be written in the middle to define attributes and methods, which will be added to the java class corresponding to JSP, not_ In the jspService() method

<%!    
    static {      
    	System.out.println("Loading Servlet!");    
    }    
    private int globalVar = 0;    
    public void kuang(){      
        System.out.println("Entered the method Kuang!");    
    }  
%>

4) JSP comments

<% -- start, --% > end

Write notes in the middle

JSP comments will not be displayed on the client, and HTML will!

<%--
    JSP notes
    Will not be displayed on the client, HTML Yes!
--%>

8.4. JSP instruction

<%@page args.... %>

<!-- Splice pages and combine the two pages into one -->
<%@include file="" %>

<%@taglib prefix="" %>
  • head.jsp

no need

<%@ page ...%>

<!DOCTYPE html>
<html>
<head>
    <!--head-->
</head>
<body>
  • foot.jsp

no need

<%@ page ...%>

</body>
</html>
  • index.jsp

no need

<%@ page ...%>
<%@include file="head.jsp"%>
...
<%@include file="foot.jsp" %>

8.5. JSP tag

<!-- Embedded pages are two pages in nature -->
<jsp:include page=""/>
    
<jsp:xxx />

8.6. EL expression ${}

Import dependent packages before using labels and expressions

There should also be relevant jar packages in the Tomcat running environment

<!-- JSTL Dependency of expression -->
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>
<!-- standard Tag library -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

8.7 JSTL label

The use of JSTL tag library is to make up for the shortage of HTML tags; There are many custom tags with the same functions as Java code!

  • Format label
  • SQL tag
  • XML tag
  • Core label
<c:out value="${}"/>

<c:if test="${}" var="">
    <c:out value=""/>
</c:if>

<c:choose>
    <c:when test="${}">
        
    </c:when>
    <c:when test="${}">
        
    </c:when>
    <c:otherwise>
        
    </c:when>
</c:choose>

<c:forEach var=" " items="${}">
    
</c:forEach>

8.8 built in objects

// Page context
PageContext pageContext;
// request    
HttpServletRequest request;
// response    
HttpServletResponse response;
// session    
HttpSession session;
// Project context    
SerlvetContext application;
// to configure    
SerlvetConfigconfig;
// Output stream    
JspWriter out;
// Current page    
Objext page = this;
// abnormal    
Exception exception;
  • Scope

    • page

      The saved data is only valid in the current page

    • request

      The saved data is only valid in one request, and the request forwarding will carry this data

    • session

      The saved data is valid only in one session, from opening the browser to closing the browser

    • application

      The saved data is valid when the service is running, from opening the server to closing the server

8.9,JavaBean

1) Overview

JavaBean generally refers to a common entity class (pojo)

  • There must be a parameterless constructor
  • Property must be private
  • There must be a corresponding get/set method

The ORM is generally used to map fields in the database

ORM: Object Relational Mapping

  • Table - > class
  • Fields - > Properties
  • Row record - > object

2) Usage in JSP

// Call class; The current page is valid
<jsp:useBean id="student" class="com.tuwer.pojo.Student" scope="page"/>
// Set attribute value    
<jsp:setProperty name="student" property="name" value="Xiao Zhang"/>
// Get value    
<jsp:getProperty name="student" property="name"/>    

8.10, 404 and 500 configurations

<error-page>
    <error-code>404</error-code>
    <location>/error/404.jsp</location>
</error-page>
<error-page>
    <error-code>500</error-code>
    <location>/error/500.jsp</location>
</error-page>

8.11. New web XML template

<?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_4_0.xsd"
         version="4.0"
         metadata-complete="true">

</web-app>

9,MVC

Model View Controller

10. Filter

10.1 overview

Filter interface

package javax.servlet;

public interface Filter {}

Function: data filtering

  • Permission check
  • Chinese garbled code
  • Bad text, pictures

10.2 use steps

Solve Chinese garbled code

1) Guide Package

Import related dependent packages

2) Define filter class

Implement javax servlet. Filter interface

package com.tuwer;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author Soil flavor
 * Date 2021/12/13
 * @version 1.0
 * Character filter
 */
public class CharacterFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Initialize filter!");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("utf8");
        response.setCharacterEncoding("utf8");
        System.out.println("Before filtration...");
        // Pass to next chain
        chain.doFilter(request,response);
        System.out.println("After filtration...");
    }

    public void destroy() {
        System.out.println("Destroy the filter!");
    }
}

3) On the web Configure Filter in XML

<!--Register filter-->
<filter>
    <filter-name>characterFilter</filter-name>
    <filter-class>com.tuwer.CharacterFilter</filter-class>
</filter>
<!--Mapping: filtering url-pattern Request for-->
<filter-mapping>
    <filter-name>characterFilter</filter-name>
    <url-pattern>/h/*</url-pattern>
</filter-mapping>

10.3. Filter implements permission interception

Login case

  • Users access the personal center page
    • If you have successfully logged in, you can access
    • If you don't log in, you can't access it. Jump to the login page

  • jsp page

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
    <h2>Hello World!</h2>
    <a href="<%=request.getContextPath()%>/user/myhome.jsp">Chinese Center</a>
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sign in</title>
</head>
<body>
    <form action="<%=request.getContextPath()%>/login" method="post">
        account number:<input name="username" value="">
        <button type="submit">Sign in</button>
    </form>
</body>
</html>

myhome.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Personal Center</title>
</head>
<body>
    Welcome,<%=session.getAttribute("username")%>!
    <br/>
    <a href="<%=request.getContextPath()%>/logout">cancellation</a>
</body>
</html>
  • Servlet
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        if(username!=null){
            // Add user name
            req.getSession().setAttribute("username",username);
            // Redirect to personal Center
            resp.sendRedirect(req.getContextPath()+"/user/myhome.jsp");
        }else{
            // Redirect to login page
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Object username = req.getSession().getAttribute("username");
        if(username!=null){
            // Remove user name
            req.getSession().removeAttribute("username");
            // Redirect to login page
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • Filter
package com.tuwer;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Soil flavor
 * Date 2021/12/14
 * @version 1.0
 */
public class loginFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Start permission filter!");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Forced conversion: HttpServletRequest can get a session, but ServletRequest cannot get a session
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        Object username = req.getSession().getAttribute("username");
        // Not logged in
        if (username == null) {
            System.out.println(req.getContextPath());
            // Redirect to login page
            resp.sendRedirect(req.getContextPath()+"/login.jsp");
        }
        chain.doFilter(req,resp);
    }

    public void destroy() {
        System.out.println("Destroy permission filter!");
    }
}
  • web.xml
<!--Sign in-->
<servlet>
    <servlet-name>login</servlet-name>
    <servlet-class>com.tuwer.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>login</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

<!--cancellation-->
<servlet>
    <servlet-name>logout</servlet-name>
    <servlet-class>com.tuwer.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>logout</servlet-name>
    <url-pattern>/logout</url-pattern>
</servlet-mapping>

<!--filter-->
<filter>
    <filter-name>loginFilter</filter-name>
    <filter-class>com.tuwer.loginFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>loginFilter</filter-name>
    <url-pattern>/user/myhome.jsp</url-pattern>
</filter-mapping>
  • Get project root path

    All request links are based on the root path

<!--jsp page-->
<%=application.getContextPath()%>
    
<%=request.getContextPath()%>    

<%=session.getServletContext().getContextPath()%>
// java code 
request.getContextPath();

11. Listener listener

Monitor the occurrence of an event / action

  • Case: Statistics of online personnel; The number of sessions is the number of online people (sessions); By listening to the creation and destruction of sessions, the data is stored in the project context application (ServletContext) object

11.1. Define listener class

Implement the corresponding listener interface: the httpsessionlitener interface can monitor the creation and destruction of sessions

There are many kinds of listener interfaces

package com.tuwer;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @author Soil flavor
 * Date 2021/12/14
 * @version 1.0
 * Count the number of people online
 * session Quantity is the number of people online
 */
public class OnlineCountListener implements HttpSessionListener {

    /**
     * Listening session creation
     *
     * @param se
     */
    public void sessionCreated(HttpSessionEvent se) {
        // Get project context object
        ServletContext context = se.getSession().getServletContext();
        // Get online number
        Integer onlineCount = (Integer) context.getAttribute("onlineCount");

        if (onlineCount == null) {
            // First user
            onlineCount = new Integer(1);
        } else {
            // Number of users plus 1
            onlineCount = new Integer(onlineCount.intValue() + 1);
        }

        // Stored in the project context object ServletContext
        context.setAttribute("onlineCount", onlineCount);
    }


    /**
     * Listening session destroy
     *
     * @param se
     */
    public void sessionDestroyed(HttpSessionEvent se) {
        // Get project context object
        ServletContext context = se.getSession().getServletContext();
        // Get online number
        Integer onlineCount = (Integer) context.getAttribute("onlineCount");

        if (onlineCount == null) {
            // First user
            onlineCount = new Integer(0);
        } else {
            // Number of users minus 1
            onlineCount = new Integer(onlineCount.intValue() - 1);
        }

        // Stored in the project context object ServletContext
        context.setAttribute("onlineCount", onlineCount);
    }
}

11.2,web. Configuration in XML

<!--Listener: count the number of people online-->
<listener>
    <listener-class>com.tuwer.OnlineCountListener</listener-class>
</listener>

Only listener and listener class

A large number of listeners are used in GUI programming; For example: operation of monitoring window

Most listeners use adapter mode

Topics: Java Front-end Web Development server http