1.Java EE WEB new chapter:
- Basically sending data from Broswer (browser) to Server (server), called request, English name: request
Sending data from Server to Broswer is called response. English name: response
- Tomcat server directory
- bin: This directory is the directory where the command files of the Tomcat server are stored, such as: starting and closing tomcat
- conf: This directory is the directory where the configuration files of the Tomcat server are stored.
- lib: This directory is the core program directory of the Tomcat server.
- logs: The log directory of the Tomcat server.
- temp: The temporary directory of the Tomcat server, which stores temporary files.
- webapps: This directory is used to store a large number of webapps. (web application: web application)
- work: This directory is used to store the translated java files and compiled class files of JSP files.
3.Environment variables that Tomcat needs to configure:
- CATALINA_HOME
- JAVA_HOME
- bin directory under the Tomcat directory
2. Develop a webapp with Servlet (emphasis)
What are the development steps?
Step one: Create a new directory under webapps and name the project.
- Note: crm is the root directory of this webapp
Step 2: Create a directory under crm: WEB-INF
- Note: The name of this directory is stipulated by the servlet specification and must be all capitalized.
Step 3: Create a new directory under the WEB-INF directory: classes
- Note: The directory must be all lowercase, which is stipulated in the servlet specification. In addition, this directory stores the java compiled class files (bytecode files)
Step 4: Create a new directory under the WEB-INF directory: lib (optional)
- Note: If a webapp requires a third-party jar package, the jar package must be placed in the lib directory, and the name cannot be written casually. It must be in all lowercase. For example, the Java language needs a database driver to connect to the database, and the name of the jar package is It should be placed in the lib directory, which is stipulated by the servlet specification.
Step 5: Create a new file in the WEB-INF directory: web.xml
- Note: This file is required, and its name must be called web.xml. This file must be placed here. This is a configuration file that stores the correspondence between paths and class names.
-
It is best to copy this file from another webapp, and it is best not to write it by hand, it is not necessary.
-
“`xml
<?xml version="1.0" encoding="UTF-8"?>
</p></li>
</ul><p><web-app xmlns="https://jakarta.ee/xml/ns/jakartaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_5_0.xsd"
version="5.0"
metadata-complete="true"></web-app>
“`
- Step 6:write ajavaApplets,thisjavaSmall programs cannot be written casually,Must be real
nowservletinterface。- thisServletThe interface is not thereJDKamong。(noJavaSEGot it)
- Servletinterface(Servlet.class)yesOraclewhich provided
- ServletThe interface isJavaEEa member of the norm。
- TomcatThe server implementsServletspecification,soTomcatThe server also needs to useServletinterface。
- javaProgram source code can be anywhere,As long as the compiledclassfile intoWEB-INFunder the directoryclassesJust in the folder。
- Step 7:Compile what we wroteservletprogram。
- Environment variable configurationCLASSPATH=.;D:\dev\apache-tomcat-10.0.20\lib\servlet-api.jar
- The equal sign is followed byservlet-api.jarThe location of the package
- Add in front.;
- Step 8:After compilation, copy toWEB-INFunder the directoryclassesfolder。
-
Step 9:writeweb.xmlConfiguration information
- Terminology:existweb.xmlRegister inservlet
- Step 10:compile
-
Step 11:copyclassfiles and their directories toclassesmiddle。
3.aboutJavaEEVersion
- JavaEEThe highest version currently isJavaEE8
- OracleWillJavaEERegulate donations toApacheGot it
- ApacheBundleJavaEEChanged name,Never call againJavaEEGot it,henceforth calledjakartaEE
- Not in the futureJavaEEGot it,calledjakartaEE
- JavaEE8correspondingServletThe class name is:javax.servlet.Servlet
- JakartaEE9correspondingServletThe class name is:jakarta.servlet.Servlet
4.solveTomcatGarbled code problem
- turn upTomcatUnder the root directoryconffolder,Reviseloggin.propertiesdocument
- searchUTF-8Change toGBK(…handler…)
5.existservletConnect to database
-
<servlet> <servlet-name>first</servlet-name> <servlet-class>lapTop.Servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>first</servlet-name> <url-pattern>/first</url-pattern> </servlet-mapping>
-
The above is the configuration of the xml file, called registration servlet.
- `
Write whatever you want in <servlet-class> Very important, fill in the path where the java applet is located here
<url-pattern> Start with /, enter it in the browser address bar, the above is: http://127.0.0.1:8080/oa/first
- oa is the name of the javaweb project
6.Life cycle of Servlet object
- Servlet objects are managed by the Tomcat server.
- Tomcat server is also called WEB container.
- By default, Servlet objects are not created when the server starts.
- How to create a Servlet object when the server starts?
in web.xml<servlet></servlet> Add in<load-on-startup></load-on-startup>
- Fill in an integer. The smaller the number, the higher the priority.
- When sending a request to the server, first call the parameterless constructor (because the object has not been created yet), and then call the init method (the object has been created at this time). The init method is only called the first time it is sent, and the already created object is used thereafter. This shows that Tomcat's servlet is a singleton mode (fake singleton)
- How many times it is called after that, how many times the service method will be called
- When destroying, the destroy method is called. At this time, the object has not been destroyed. It is destroyed only after the method is called.
- When we write a parameterized constructor in a Servlet, it will result in:
- If there is no parameterless constructor, the browser will prompt a 500 error.
- 500 errors generally refer to errors that occur on the server side.
- In Servlet development, programmers are not recommended to create constructors.
- The init and Servlet construction methods take about the same time to create and have the same effect. So can the Servlet construction method replace the init method?
- cannot. Because Java web development specifications stipulate that Java programmers are not recommended to manually write constructors, because it is likely to cause the no-argument constructor to disappear and lead to errors.
- Adapter design pattern
- To implement all methods of the interface at once, the code looks unsightly
- You can set up an adapter, leave uncommon methods blank, change the core methods to abstract abstract types, and then set the adapter class to abstract.
- Use extends xxxAdapter when calling in the future.
- Write a GenericServlet class. This class is an abstract class that implements the service method.
- All servlet classes written in the future inherit GenericServlet and override the service method.
- How to transform the GenericServlet class to make it more convenient for writing subclass programs?
- Execute the parameterless init() method in the parameterized init method, and let the subclass rewrite the parameterless init method, so that the code in the parameterized init() method can be retained.
- In the init method, the local variables of the parameter ServletConfig are stored in member variables.
- Return the ServletConfig of the member variable in the getServletConfig() method.
7.ServletConfig
- You can call the method of the ServletConfig object directly using this. (Inherits GenericServlet)
- Commonly used methods in ServletConfig:
- getInitParameterNames() gets the names of all init elements
- getInitParameterName(String name) Enter the string name to get the value of the init element.
- getServletName() gets the name of the current Servlet
- getServletContext()
7.Extension:Enumeration
- Common methods
- hasMoreElements() determines whether there are more elements
- nextElement() returns the value of the current element and moves the pointer to the next element
8.ServletContext
-
A webapp has only one ServletContext object.
-
Tomcat creates a ServletContext object when it starts and destroys it when it shuts down.
-
ServletContext common methods
-
getInitParameterNames(), obtains a context collection, which stores all context-param contents, and returns enumeration
<String>
-
getInitParameter(String name), obtains the value through the name of the context. Return String.
getContextPath()
Get the root path of the application (project name)
```java //ObtainwebThe real path of a file in the directory。Notice:This file is inwebunder the directory String realPath = application.getRealPath("/index.jsp"); ``` </code></pre> <ul> <li>Methods in ServletContext can only be called through the ServletContext object.</p></li> <li><p>ServletContext common methods (2) <pre><code class="language-java line-numbers">application.setAttribute(String name,Object obj); </code></pre></li> </ul> Setting the ServletContext attribute is equivalent to caching and global sharing. <pre><code>```java context.getAttribute(String name); ``` </code></pre> Get the ServletContext attribute. As long as it is created in a Servlet, the value of this attribute can be accessed in any Servlet. <h2>9.HTTP protocol</h2> <ul> <li>The HTTP protocol is a hypertext transfer protocol developed by the W3C.</li> <li>What is hypertext? : Not ordinary text, such as streaming media: sounds, pictures, videos, etc.</li> <li>HTTP not only supports ordinary text, but also can transmit streaming media: sounds, pictures, videos, etc.</li> <li>HTTP request protocol (B->S) The browser sends a request to the server. The request includes four parts</li> <li>request line</li> <li>Request header</li> <li>blank line</li> <li>Request body</li> <li>HTTP response protocol (S->B) The server receives the browser's request and calls it a response. The response consists of four parts.</li> <li>status line</li> <li>response header</li> <li>blank line</li> <li>response body</li> </ul> <h2>9.Extension: Template method design pattern</h2> <ul> <li>Template method of template class:</li> <li>Define the core algorithm skeleton, and the implementation of specific methods can be postponed to subclasses.</li> <li>Template classes are generally abstract classes.</li> <li>Template methods generally need to be modified with final to prevent the core algorithm from being modified.</li> <li>Singleton mode:</li> <li>Abstract factory pattern:</li> </ul> <h2>10.HttpServlet</h2> <ul> <li>What are the classes under the http package?</li> <li>jakarta.servlet.http.HttpServlet</li> <li>jakarta.servlet.http.HttpServletRequest</li> <li>jakarta.servlet.http.HttpServletResponse</li> </ul> <h2>11. Set up WEB welcome page</h2> <ul> <li>By default, index.html/index.jsp/index.htm will be found in the WEB folder.</p></li> <li><p>Or configure it manually in web.xml: <pre data-language=HTML><code class="language-markup line-numbers"><welcome-file-list> <welcome-file>XXX.html</welcome-file> </welcome-file-list> </code></pre></li> </ul> (Looking from the root of the webapp directory by default) <ul> <li>You can set up multiple welcome pages, and the welcome pages at the top will have higher priority.</p></li> <li><p>You can set a dynamic Sevlet as the welcome page</p></li> <li><p>Note: Fill in the request path of the Servlet in welcome-file, and no slash is needed in the header. <pre data-language=XML><code class="language-markup line-numbers"><welcome-file-list> <welcome-file>http</welcome-file> </welcome-file-list> <servlet> <servlet-name>http</servlet-name> <servlet-class>com.httpservlet.HttpServletTest</servlet-class> </servlet> <servlet-mapping> <servlet-name>http</servlet-name> <url-pattern>/http</url-pattern> </servlet-mapping> </code></pre></li> </ul> <h2>12.HttpServletRequest interface</h2> <ul> <li>The format of data submitted by the front end: username=abc&userpwd=abc&hobby=1&hobby=2&hobby=3</p></li> <li><p>Using <code>Map<String,String[]></code> method to store the front-end key and value</p></li> <li><p>If it is <code>Map<String,String></code> format, then the value of the subsequent key will overwrite the previous one.</p></li> <li><p>The data types submitted by the front-end form are all String</p></li> <li><p>Common methods of HTTPServletRequest interface:</p></li> <li><p> ```java Map
getParameterMap() //Get Map Enumeration getParameterNames() //Get all keys in the Map collection String[] getParameterValues(String name)//Get the value of the Map collection based on the key String getParameter(String name) //It is most commonly used to get the first element in the one-dimensional array of value ``` - Step 6:write ajavaApplets,thisjavaSmall programs cannot be written casually,Must be real
Request to jump:
- Servletobjects cannot be created by usjavaProgrammer comesnew,must useHttpServletRequestobject's request forwarder:
RequestDispatcher getRequestDispatcher(String path)
returnRequestDispatchertypeRequestDispatcherThe object hasforward(request,response)method can pass the currentservletofrequestandresponseobject
This will allow content in the requested domain to be shared。
combine together,final version:
request.getRequestDispatcher(String path).forward(request,response);
- pathinside isweb.xmlconfigured inservlet-mappingneutralurl-pattrn。
-
The forwarded content is not necessarilyservlet,can behtml…etc.
-
Notice:pathby"/"start,No project name。
-
String getParameter(String name) and Object getAttribute(String name) What is the difference? the first is:Data sent by the user in the browser。 The second one is:servletRequest data bound in the domain。
-
ServletRequest other methods:
getRemoteAddr() gets the client IP address
getContextPath() gets the root path of the application
getMethod() gets the request method
getRequestURI() gets the requested URI: /project name/…
getServletPath() gets the servlet path: without project name
13. Design a pure Servlet single page (oa project)
-
- Design database:
- Use the dept table in scott
-
- Design page:
-
index.html main page
- list.html list page
- detail.html detail page
- modify.html modify page
- add.html new page
-
- Function:
-
delete
- New
- list
- Details
- Revise
-
- Implement functions:
-
EZ for me
14.Web application forwarding and redirection
- Forward:
- request.getRequestDispatcher(“/path”).forward(request,response);
- After the request is forwarded, the path in the browser address bar remains unchanged.
- Redirect:
- response.sentRedirect("/project name/path");
- The browser's address will change after forwarding.
- When redirecting, the browser sends two requests to the server, so the final path will change.
- Note: request.getContextPath() can obtain the root path of the application.
15. Develop Servlet based on annotations
- The first annotation: @WebServlet
import jakarta.servlet.annotation.WebServlet;
- @WebServlet attribute:
* name attribute: used to specify the servlet name, equivalent to <servlet-name>
* urlPatterns attribute: used to specify the mapping path of the Servlet, multiple strings can be specified<url-pattern>
* loadOnStartUp attribute: used to specify whether to load the Servlet when the server starts, equivalent to <load-on-startup>
* Important: value attribute: equivalent to the urlPatterns attribute, specifying the mapping path, but in the annotation, the attribute name equal to value can be omitted. In other words, we can write Servlet mapping like this:
* @WebServlet(“/url”)
2. How to use the annotation object: @annotation object (attribute name = attribute value, attribute name = attribute value)
16. Use template method design pattern to optimize oa project
- To solve the problem of class explosion, use a DeptServlet to complete all functions.
- Perform different functions according to the path returned by the front end, such as doList, doAdd, etc.
17. Analyze the shortcomings of using pure Servlet to develop web applications
High coupling requires writing front-end code in a java program.
- Unable to get timely prompts when errors occur.
- The code is not beautiful and error-prone.
solve:
- Let a program translate the front-end code to generate servlet code. This is the next technology: JSP
17.1 About the session mechanism of B/S structure
- Session, English name: session
-
The principle of session:
-
The browser stores a sessionid, and the server stores a sessionid. If the two IDs match, a session can be found.
- The first time request.getSession() is called, there is no sessionid. Create a new sessionid. This sessionid is stored in the browser cache, and then the sessionid is sent to the browser.
- Second call: The browser sends the sessionid to match with the server and finds a session.
-
Why does the session expire when the browser is closed:
-
Because the cache will disappear when the browser is closed, and when the browser is reopened, there will be no previous sessionid on the browser side.
- Browser cache status via cookie
-
Is there any way to invalidate the session:
-
- Timeout mechanism: available in web.xml file
<session-config>
<session-timeout>30</session-timeout>
</session-config>
- The session setting will expire after more than 30 minutes.
-
- Manual destruction: such as the safe exit button when exiting the online banking system.
- Use session.invalidate() method
-
To disable cookies in your browser:
-
The server sends the cookie normally, but the browser refuses to accept it, causing a new sessionid to be created every time.
17.2 About Cookies
- Each session corresponds to a sessionid
- For session-related cookies, this cookie is saved in the browser's "running memory".
- The cookie is ultimately stored in the browser client.
- Session saves the session state on the server side.
- Cookies can be saved to your hard drive.
- The role of cookies
- Save session state
- Cookie classic case:
- No login required for 126 mailboxes within 30 days. Implementation principle:
- The user enters the correct username and password and chooses not to log in for 30 days. The browser will save the cookie on the hard disk. When logging in within 30 days, the cookie will be loaded and the information will be automatically submitted to the server. The server will receive the cookie and obtain the username and password. , the login is successful after passing the verification.
- The cookie stores name and value.
- response.addCookie(Cookie cookie) The server sends cookies to the browser
- cookie.setMaxAge(int seconds) sets the cookie expiration time.
- If the cookie validity time is not set, it will be stored in the browser's running memory, the browser will be closed, and the cookie will disappear.
- As long as the cookie validity time is set to be greater than 0, it will be saved to the hard disk file.
- Set the cookie validity period equal to 0 and delete the cookie file. It is mainly used to delete cookies with the same name.
- Setting the cookie validity period to less than 0 means that the cookie will not be stored in the hard disk file, but will be placed in the browser's running memory.
- Use cookies to implement the login-free function for ten days:
- Add a checkbox to avoid logging in for ten days and set the name and value. This will be submitted to the server side with the submit button.
- After the server determines that the login is successful, it determines whether it has received data from the check box. If so, it creates two new cookies to store the user name and password.
- The welcome page is changed to a custom welcome servlet. Here, it is judged whether the cookie is empty. If it is empty, it jumps to the login page. If it is not empty, it traverses each cookie and obtains two cookies named username and userpwd as the user name and password. Save it.
- Obtain the username and password of the cookie and verify the database. If correct, it will jump directly to dept/list. If it is incorrect, it will jump to the index.jsp login page.
- **Important: Delete the cookie when exiting the system, use the same name overlay method, set a cookie with the same name, set the value to null, and finally respond.addCookie()
- Note: The path must be the same when overwriting! ! ! SetPath was used before, so the path must be consistent when deleting, otherwise it will be regarded as a new cookie! ! ! !
18.JSP
- My first JSP program
- There is an index.jsp file outside the WEB-INF directory. This file has no content.
- Open the browser to visit, a blank page.
- JSP is actually a Servlet class
- The first access of JSP is relatively inefficient because neither the java file nor the compiled class file is generated.
- Content written directly in JSP will be placed in out.print, which is equivalent to writing front-end code.
- JSP response garbled problem:
- Add <%@page contentType="UTF-8"%> at the beginning
- Indicates that the character set used is UTF-8
- How to write java program in JSP?
- <%javacode,What is written on this side is consideredjavaprogram,translated toserviceinternal;%>
- Comments for JSP:
- <%–Comment–%>
- How to translate to outside the service method
- <%!%>
- This syntax is rarely used and is not recommended because:
- Outside the method body, there are thread safety issues under high concurrency when modifying static variables and instance variables.
- JSP output format:
- Output a java variable to the browser:
- out.write() can only output character-related values.
- out.print() can output values of numbers, characters, etc.
- Conveniently output the value of java variables
- Previously: <% out.write(n)%>
- Improvement: <%=n%>
- n will be translated into out.print() brackets
- n is a variable. Note: there is no semicolon after the variable.
- If you want to output multiple variables at one time, use the + sign to connect them, which is the same as Java syntax.
- JSP syntax summary:
-
Written directly, it is output in html, translated into out.print(""); directly translated into double quotation marks, it is used as a string by the Java program and printed on the web page.
-
<%%> is java code (remember to add; semicolon)
-
The code in <%!%> is translated outside the service method and used to define member variables, methods, static code blocks, etc.
-
The code in <%=%> is translated into out.print(), which is equivalent to outputting java variables. It is translated into out.print() without ""
-
<%@page %>
-
page directive, set the content of the response through contentType
- <%@page import="java.util.List"%>Import package in jsp
- <%@page errorPage="/error.jsp"%>Direct to error.jsp after error
- <%@page isErrorPage="true"%> allows the use of Exception, one of the nine built-in objects of JSP, and is used in conjunction with <%exception.printStackTrace()%>.
-
JSP nine built-in objects
-
HttpServletRequest request request domain
- HttpServletResponse response
- PageContext pageContext page request domain
- HttpSession session session domain
- exception = JspRuntimeLibrary.getThrowable(request)
- ServletContext application application domain
- ServletConfig config
- JspWriter out
- Object page
- 4 scope sizes:
- pageContext < request < session < application
- The above four scopes have methods: setAttribute(), getAttribute(), removeAttribute()
- Scope usage principle: Use as small a scope as possible.
19. Further optimization of the oa project
- Implement login function:
- Step 1. Design the database table with username and password.
- Step 2. Design a web page that requires user name and password. There is a login button. Click to submit the data to the background.
- Step 3. Write a servlet in the background to verify the user name and password.
- Login successful: jump to list and display information
- Login failed: Login failed page or return to login page
EL expression
Expression Language is a part of jsp. It has three major functions:
-
- You can obtain data in the scope
-
- Convert data into string
-
- Output data to the browser
The format of EL expression: ${expression}
The expression writes the name when setAttribute! ! Do not add "" double quotes
EL expressions need to output specific values in a certain class and are connected with dots. What is connected here is the get method, which has nothing to do with member variables.
When an EL expression fetches data from a domain, it fetches data in ascending order of the domain.
pageContext < request < session < application
EL expressions have four implicit fields:
- pageScope
- requestScope
- sessionScope
- applicationScope
There are two methods for fetching data in EL expressions:
- .
-
[“”]
-
[] Entering the array element subscript between square brackets can also extract the element of the subscript. For example
${usernames[0]}
-
If you store an array within an array:
- Then you can use
${depts[0].dname}
to get the dname value in the array with subscript 0. -
How to locally ignore EL expressions? :
-
\${} preceded by a backslash
- If you want to disable EL expressions globally, use ${@ page isELIgnore = “true”}
-
Get the root of the application through an EL expression:
-
There is no implicit request object in the EL expression, but there is pageContext, so:
- ${pageContext.request.contextPath}
- EL expression implicit objects:
- pageContext
- param
- paramvalues
- initParam
# JSTLtag library
* what isJSTLtag library?
* help us reducejavacode
* usage:use `<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>Import core library`
* ```
<c:forEach items="{list}" var="d">
Department Number:{d.deptno}<br>
Department name:{d.dname}<br>
</c:forEach>
```java
items is the collection to be traversed (EL expression can be used), var is the variable that stores the elements in the collection
</code></pre>
<p><c:if test="{empty param.username}">
<h1>Username can not be empty!</h1>
</c:if>
```java
- The value in test must be of boolean type, and EL expressions can be used.
```
<c:forEach var="i" begin="0" end="10" step="1">
i:${i}<br>
</c:forEach>
```c
Equivalent tofor(int i = 0;i <= 10;i++){System.out.println(i)}
- varStatusThe object hascountAttributes,from1Start incrementing,Mainly used for numbering/serial number。
-
```
<c:forEach var="i" begin="0" end="10" step="1" varStatus="v">
serial number{v.count} i:{i}<br>
</c:forEach>
```java
-
```
<c:choose>
<c:when test="{param.age<12}">
child
</c:when>
<c:when test="{param.age < 18}">
teenager
</c:when>
<c:when test="{param.age<30}">
youth
</c:when>
<c:when test="{param.age < 55}">
middle aged
</c:when>
<c:otherwise>
elderly
</c:otherwise>
</c:choose>
```xml
Similar toif else if else
Transformationoa
useELexpression andJSTLTag library transformationoaproject。
learn:
HTMLThere is one in <base >
Label,You can set the root path of the project
Any path that does not begin with"/"started,will be added in frontbaseLabel。
Dynamic acquisitionbaseall paths in(useELexpression)
```
protocol:{pageContext.request.scheme} http
server name:{pageContext.request.serverName} localhost
The port number:{pageContext.request.serverPort} 8080
Item name:{pageContext.request.contextPath} oa
```xml
filter
- Filter inherits Filter class
- Configure the Filter class in xml:
```
<filter>
<filter-name>filter1</filter-name>
<filter-class>com.listener.Filter1</filter-class>
</filter>
<filter-mapping>
<filter-name>filter1</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
```java
* filter-mappingThe order ofFilterexecution priority
- Configure using annotationsFilter:@WebFilter({“*.do”})
- When using annotations, the order of execution is sorted by class name.。
- chain.doFiltermethod can be executed nextFilter,if there is notFilter,Execute the same pathservlet。
- Filterlife cycle?
- Filterlife cycle andservletObject consistent。
- andservletThe difference is that:It will be instantiated when the server startsFilterobject,andservletWon't。
- Filterpriority ratioservlethigh。
- rewriteoaproject
Design Patterns:chain of responsibility design pattern
- Loop call,Works like a stack。
- To keep changes closed,Expand the principle of openness。
listenerListener
- The listener isServleta member of the norm
- ServletWhat listeners are provided in the specification?
- jakarta.servletBao Xia
- ServletContextListener
- ServletContextAttributeListener
- ServletRequestListener
- ServletRequestAttributeListener
- jakarta.servlet.httpBao Xia:
- HttpSessionListener
- HttpSessionBindingListener
- HttpSessionAttributeListener
- HttpSessionIdListener
- HttpSessionActivationListener
- Steps to implement a listener:
-
<listener>
<listener-class>com.listener.ListenerTest</listener-class>
</listener>
-
Or annotation: @WebListener
- The listener is called at special times and is automatically called by the server without the intervention of the web programmer.
- Classes that inherit ServletContextAttributeListener do not need @WebListener
Realize the function of counting online people