1, Listener interface
1. Introduction
(1) One group comes from the interfaces under the Servlet specification, with a total of 8 interfaces. The servlet-api.jar package exists in Tomcat
(2) The listener interface needs to be implemented by the developers themselves. The jar package provided by the Http server does not have a corresponding implementation class
(3) The listener interface is used to monitor the change time of the life cycle of the scope object and the change time of the shared data of the scope object
2. Scope object
(1) In the Servlet specification, an object that considers that the server memory can provide a data sharing scheme between two servlets under certain conditions is called a scope object
(2) Classification:
In our last article, we introduced three kinds of objects when we introduced data sharing
ServletContext: global scope object
HttpSession: session scope object
HttpServletRequest: request scope object
3. Development specifications
(1) According to the actual listening object, select the corresponding listener interface for implementation
(2) Rewrite the listener interface to declare the listening event handling method
(3) Register the listener interface implementation class to the Http server in the web.xml file
4.ServletContextListener interface
(1) Function:
This interface is used to legally detect the initialization time and destruction time of global scope objects
(2) Listening event handling method:
public void contextInitlized() : In the global scope, the object is Http Server initialization called public void contextDestory() : In the global scope, the object is Http The call is triggered when the server is destroyed
5.ServletContextAttributeListener interface
(1) Function:
This interface is used to legally detect the change time of shared data of global scope objects
(2) Listening event handling method:
public void contextAdd() : Add shared data to the global scope object public void contextReplaced() : Update shared data on global scope objects public void contextRemove() : Delete shared data in global scope object
6. Change time of shared data of global data domain objects
ServletContext application = request.getServletContext(); application.setAttribute("key1",100); //Add shared data application.setAttribute("key1",200)// Update shared data pplication.removeAttribute("key1"); //Delete shared data
7. Usage
1. Create a new listener package. Under this package, select new Web listener
2. We found that the MyListener class inherits three listener interfaces: ServletContextListener, HttpSessionListener and HttpSessionAttributeListener, and the method framework has been rewritten. We can fill in code into the method to complete some operations when the scope object changes.
package listener; import jakarta.servlet.*; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; @WebListener public class MyListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener { public MyListener() { } @Override public void contextInitialized(ServletContextEvent sce) { /* This method is called when the servlet context is initialized(when the Web application is deployed). */ } @Override public void contextDestroyed(ServletContextEvent sce) { /* This method is called when the servlet Context is undeployed or Application Server shuts down. */ } @Override public void sessionCreated(HttpSessionEvent se) { /* Session is created. */ } @Override public void sessionDestroyed(HttpSessionEvent se) { /* Session is destroyed. */ } @Override public void attributeAdded(HttpSessionBindingEvent sbe) { /* This method is called when an attribute is added to a session. */ } @Override public void attributeRemoved(HttpSessionBindingEvent sbe) { /* This method is called when an attribute is removed from a session. */ } @Override public void attributeReplaced(HttpSessionBindingEvent sbe) { /* This method is called when an attribute is replaced in a session. */ } }
<listener> <listener-class>listener.MyListener</listener-class> </listener> If we inherit the listener interface manually, we need to paste the above code into the web.xml in The listener interface implementation class is directly created above with its own annotations @WebListener , Listener registration is not required
2, Filter interface
1. Introduction
(1) The interface from the Servlet specification exists in the servlet-api.jar package in Tomcat
(2) The developer is responsible for providing the filter interface implementation class, but the Http server is not responsible for providing it
(3) The filter interface intercepts the Http server before calling the resource file
2. Function
(1) Intercept the Http server to help the Http server detect the legitimacy of the current request
(2) Intercept the Http server and enhance the current request
3. Development steps
(1) Create a Java class to implement the Filter interface
(2) Override the doFilter method in the Filter interface
(3) web.xml registers the filter interface implementation class with the Http server
4.Filter intercept address
(1) Address format
<filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>Intercept address</url-pattern> </filter-mapping>
(2) Command function
The interception address informs Tomcat that it needs to call MyFilter filtering to intercept before calling what resource file
(3) Tomcat is required to call MyFilter to intercept when calling any file in the website
<url-pattern>/*</url-pattern>
(4) Tomcat is required to call MyFilter to intercept before calling all resource files in a folder
<url-pattern>/web/*</url-pattern>
(5) Tomcat is required to call MyFilter to intercept before calling a certain type of file under any folder
<url-pattern>*.html</url-pattern>
5. Code example
We now want to complete a login detection program. The submitted data include user name and age. Users younger than 18 are required to show that minors are not allowed to enter when trying to log in to the web page.
1. We first create a Filter class and rewrite its doFilter method to complete data filtering
In the new Filter class, the method framework to be rewritten has been written for you. Just fill in the code
With this annotation, there is no need to introduce the class path in web.xml, but the content in filter mapping still needs to be written
MyFilter code
package filter; import jakarta.servlet.*; import jakarta.servlet.annotation.*; import java.io.IOException; import java.io.PrintWriter; @WebFilter(filterName = "MyFilter") public class MyFilter implements Filter { public void init(FilterConfig config) throws ServletException { } public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { String age = request.getParameter("age"); if (Integer.valueOf(age) > 18) { chain.doFilter(request, response); } else { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.print("<center><font style='color:red;font-size:40px'>Minors are not allowed in!</font></center>"); } } }
2. Create web pages to submit data
check.html file
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <center> <form action="/myWeb/MyServlet" method="get"> user name: <input type="text" name="username"> Age: <input type="text" name="age"> <input type="submit" value="submit"> </form> </center> </body> </html>
3. Write a Servlet class to receive the request data of the browser
package controller; import jakarta.servlet.*; import jakarta.servlet.http.*; import jakarta.servlet.annotation.*; import java.io.IOException; @WebServlet(name = "MyServlet", value = "/MyServlet") public class MyServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("I have received the request"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
4. Configure the interception address in web.xml. It is required to intercept the data before submitting it to MyServlet
<filter-mapping> <filter-name>MyFilter</filter-name> <url-pattern>/MyServlet</url-pattern> </filter-mapping>
Open Tomcat, jump to check.html, enter the following data, and click Submit.