JAVAWeb Listener, Filter, Interceptor, servlet difference
This is the fifth day of my participation in the August More text Challenge. For details, see: August More Text Challenge
1. Life cycle
At SpringBoot we can basically do web development with the Controller, However, in some cases, we need to use Filter, Servlet, Listener, Interceptor to complete some requirements The next main is to write about the Filter, Servlet, Listener, Interceptor understanding and in springBoot and web.xml writing methods and their differences
1.Filter
(1) Load an instance of the filter when starting the server and call init() to initialize the instance; (2) Only call method doFilter() for processing each request; (3) When the server is stopped, call destroy() to destroy the instance.
2.Listener
Servlet Listener Listener, it is realized the javax.mail Servlet. ServletContextListener interface server, it is also along with the start of the web application starts, initialized only once, destroyed along with the stop of web application.
3.Interceptor
Take the struts interceptor as an example. After struts.xml is loaded, the interceptors are initialized. When the intercept method is called when the action request comes in, the server stops destroying the Interceptor.
4.Servlet
Servlet: general inherit HttpServlet (general, general servlet by javax.mail. Servlet. GenericServlet implementation servlet interface. Javax.mail. Servlet. HTTP. HttpServlet implemented specially used in response to a HTTP request to the servlet, provides the corresponding standard HTTP request response doGet (), doPost () method). Once loaded, servlets are generally not removed from the container until the application server is shut down or restarted. However, when the container does the memory reclamation action, the servlet may be deleted. It is for this reason that the first access to the servlet takes much longer than subsequent access. The servlet is loaded and the initialization method is executed once on the first request (or when its entity is accessed after memory garbage collection), followed by the formal execution method, and then it is resident and executes the formal execution method each time it is requested. Entities are destroyed until a destroy method is performed when the server is shut down or cleaned up. (1) Load: load the instance of the Servlet when starting the server; (2) Initialization: Start when the Web server starts or when the Web server receives a request, or sometime in between. The init () method is responsible for the initialization; (3) Call: call only doGet() or doPost() from the first call to the doPost() method; (4) Destroy: When the server is stopped, call destroy() to destroy the instance.
2. Code presentation (SpringBoot and web.xml)
1.Filter
1.1 SpringBoot project
import org.springframework.stereotype.Component; import javax.servlet.*; import java.io.IOException; /** * DEMO */ @Component public class MyFilter implements Filter {@override public void init(FilterConfig) FilterConfig) throws ServletException{// After the server starts, } @override public void doFilter(ServletRequest ServletRequest ServletResponse ServletResponse ServletRequest, ServletResponse ServletResponse, FilterChain FilterChain) throws ServletException {// Execute the intercepting action. The detailed intercepting logic is written here. //doFilter: Execute each request for intercepted resources. System.out.println("MyFilter was executed....") ); / / release the try {filterChain. DoFilter (servletRequest, servletResponse); } catch (IOException e) { e.printStackTrace(); }} @override public void destroy() {// The Filter object is destroyed after the server is closed. }}Copy the code
2.1 Web.xml project
<? The 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" > <! -- filter configuration --> <filter> <filter-name>enCodingFilter</filter-name> <filter-class> com.wzy.filter.myfilter </filter-class> </filter> <filter-mapping> <filter-name>enCodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>Copy the code
import javax.servlet.*; import java.io.IOException; /** * DEMO */ public class MyFilter implements Filter {@override public void init(FilterConfig FilterConfig) throws ServletException{// After the server starts, } @override public void doFilter(ServletRequest ServletRequest ServletResponse ServletResponse ServletRequest, ServletResponse ServletResponse, FilterChain FilterChain) throws ServletException {// Execute the intercepting action. The detailed intercepting logic is written here. //doFilter: Execute each request for intercepted resources. System.out.println("MyFilter was executed....") ); / / release the try {filterChain. DoFilter (servletRequest, servletResponse); } catch (IOException e) { e.printStackTrace(); }} @override public void destroy() {// The Filter object is destroyed after the server is closed. }}Copy the code
2.Listener
2.1 SpringBoot Project (page request listening)
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan public class DemoMain { public static void main(String[] arg){ SpringApplication.run(DemoMain.class,arg); }}Copy the code
import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.annotation.WebListener; /** * Listener */ @webListener public class MyServletRequestListener implements ServletRequestListener {@override public void requestDestroyed(ServletRequestEvent servletRequestEvent) { System. The out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > destroy "); } @Override public void requestInitialized(ServletRequestEvent servletRequestEvent) { System. Out. Println (" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- > request to create "); }}Copy the code
2.2 In the Web.xml project (user count)
<? The 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"> <listener> <listener-class>MyHttpSessionListener</listener-class> </listener> <listener> <listener-class>MyServletContextListener</listener-class> </listener> </web-app>Copy the code
import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyServletContextListener implements ServletContextListener { @Override public void contextInitialized(ServletContextEvent servletContextEvent) { ServletContext sc = servletContextEvent.getServletContext(); sc.setAttribute("peopleNum", 0); } @override public void contextDestroyed(ServletContextEvent) {}}Copy the code
import javax.servlet.ServletContext; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * User listens to DEMO */ public class MyHttpSessionListener implements HttpSessionListener {@override public void SessionCreated (HttpSessionEvent HttpSessionEvent) {system.out.println (" HttpSession was created "); countPersion( httpSessionEvent.getSession().getServletContext(), true); } @override public void sessionDestroyed(HttpSessionEvent) {system.out.println (" HttpSession is destroyed "); countPersion(httpSessionEvent.getSession().getServletContext(), false); } @param isAdd */ public void countPersion(ServletContext sc, Boolean isAdd) {// synchronized (sc) {// get the number of people currently online Integer count = (Integer) sc.getAttribute("peopleNum"); If (isAdd) {sc.setattribute ("peopleNum", ++count); } else { sc.setAttribute("peopleNum", --count); }}}}Copy the code
2.3 supplement
1.ServletContextListener — Listens for the creation and destruction of a servletContext object
1.2 contextDestroyed(ServletContextEvent SCE) -- DestroyedCopy the code
2. ServletContextAttributeListener — listener servletContext object properties change
2.1 attributeAdded (ServletContextAttributeEvent scae) - to add attributes to perform 2.2 attributeRemoved (ServletContextAttributeEvent scae) - delete attribute execute 2.3 attributeReplaced (ServletContextAttributeEvent scae) - modify attributesCopy the code
3.HttpSessionListener — Listens for the creation and destruction of session objects
3.2 sessionCreated(HttpSessionEvent SE) -- Run when creating 3.2 sessionDestroyed(HttpSessionEvent SE) -- run when destroyingCopy the code
4. HttpSessionAttributeListener – to monitor changes in the session object attribute
4.1 attributeAdded(HttpSessionBindingEvent SE) -- Performed when an attribute is added. 4.2 attributeRemoved(HttpSessionBindingEvent SE) -- Performed when an attribute is deleted 4.3 attributeReplaced(HttpSessionBindingEvent SE) -- Executed when the attribute is changedCopy the code
5.ServletRequestListener — Listens for the creation and destruction of request objects
5.1 requestInitialized(ServletRequestEvent SRE) -- Executed when creation 5.2 requestDestroyed(ServletRequestEvent SRE) -- Executed when destructionCopy the code
6. ServletRequestAttributeListener – to monitor the request object properties change
6.1 attributeAdded (ServletRequestAttributeEvent srae) - to add attributes to perform 6.2 attributeRemoved (ServletRequestAttributeEvent srae) - delete attribute execute 6.3 attributeReplaced (ServletRequestAttributeEvent srae) - modify attributesCopy the code
3.Interceptor
3.1 SpringBoot project
@configuration public class LoginInterceptor implements HandlerInterceptor {@override public Boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Handler) throws Exception {// Check whether the current user has logged in. HttpSession Session = request.getSession(); User loginUser = (User)session.getAttribute("loginUser"); if ( loginUser == null ) { String path = session.getServletContext().getContextPath(); response.sendRedirect(path + "/login"); return false; } else { return true; }} /** * execute after the Controller method call, */ @override public void postHandle(HttpServletRequest Request, HttpServletResponse Response, Object Handler, ModelAndView ModelAndView) throws Exception {} /** * Execute this method after rendering the view. */ @Override public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception { } }Copy the code
2.2 Web. XML project
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**" /> <mvc:exclude-mapping path="/login" /> < MVC: exclude - mapping path = "/ shop / * *" / > / / static resource to intercept the interceptor wrong < bean class = "com. Wzy. Web. LoginInterceptor" > < / bean > </mvc:interceptor> </mvc:interceptors>Copy the code
import org.apache.catalina.User; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; Public class LoginInterceptor implements HandlerInterceptor {@override public Boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object Handler) throws Exception {// Check whether the current user has logged in. HttpSession Session = request.getSession(); User loginUser = (User)session.getAttribute("loginUser"); if ( loginUser == null ) { String path = session.getServletContext().getContextPath(); response.sendRedirect(path + "/login"); return false; } else { return true; }} /** * execute after the Controller method call, */ @override public void postHandle(HttpServletRequest Request, HttpServletResponse Response, Object Handler, ModelAndView ModelAndView) throws Exception {} /** * Execute this method after rendering the view. */ @Override public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler, Exception ex)throws Exception { } }Copy the code
3. Differences among the three
The title | Filter | Listener | Interceptor |
---|---|---|---|
Point of application | Web request, context | System-level objects, parameters, etc | Action, Web requests |
implementation | The callback function | Event listeners | A dynamic proxy |
Application scenarios | Control the application code and prevent the user from entering the interface without login | It is used to collect statistics on the number of online users and eliminate expired sessions | Intercept unlogged users |
Technical support | Servlet support | Servlet support | Spring provides support |
Corresponding interface | The Filter interface | The ServletContextListener interface and HttpSessionListener interface are both inherited from EventListener | HandlerInterceptor interface, HandlerInterceptorAdapter abstract class |
Level classification | system | system | The system |
4. To summarize
According to the above content, we can see that after a Web project is launched, these “artifacts” have a great importance to use, a good Web project will monitor, count, statistics and so on