“Don’t look down upon anyone, the less remarkable. Often do something unexpected.” Hello, I am Mengyangchen, come and study with me!

The article directories

  • 01. Description of the Filter
  • 02.Filter Quick Start
  • 03. Filter
  • 4. The Filter case
  • 05. Dynamic proxy
  • 6. Summary of the Listener
  • 07.ServletContextListener

01. Description of the Filter

Filters and Listeners are two advanced features in the Servlet specification that, unlike servlets, are not used to process client requests.

Filter Modifies the Request and Response objects. A Filter is called a Filter, whose basic function is to intercept the Servlet invocation process of the Servlet container, so as to realize some special functions before and after the Servlet responds. This is like a sewage purification device in real life, which can be regarded as a filter for filtering sewage impurities.

When the browser accesses a target resource in the server, the Filter intercepts the request, preprocesses it in the Filter, and then forwards the request to the target resource.

When the server receives the request, it responds to it. During the process, the server sends the response result to the filter and processes the response result before sending it to the client.

Filter function: general to complete the general operation. For example, login authentication is used to determine whether a user has logged in. Unified coding processing, sensitive character processing, etc.

A Filter is a class that implements the Javax.servlet. Filter interface

Three methods are defined in javax.servlet.filter.

The Listener listens for context,session, and Request events.

02.Filter Quick Start

Steps: 1. Define a class that implements the interface javax.servlet.filter.

2. Copying method

3. Configure the interception path 3.1.web.xml Configuration 3.2. annotations Configuration Javax.servlet.filter defines three methods

Public class FilterTest1 implements Filter {@override public void init(FilterConfig) FilterConfig) throws ServletException {// Initializes the filter, called when the Web program is loading, Override public void doFilter(ServletRequest ServletRequest, ServletResponse ServletResponse, FilterChain FilterChain) throws IOException, ServletException {system.out. print(" I am a filter!" ); / / release, i.e., forwarded to the requested resource filterChain. DoFilter (servletRequest, servletResponse); Override public void destroy() {Override public void destroy() {Override public void destroy() {Copy the code

Web. XML configuration Cancel the annotation configuration and use the web. XML configuration.

 <filter>
        <filter-name>FilterTest1</filter-name>
        <filter-class>filter.FilterTest1</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>FilterTest1</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
Copy the code

03. Filter

Filter flow:

@WebFilter("/*") public class FilterTest2 implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {// This method is used to intercept the user's request, if it matches the intercepting path of the current filter. // Enhance the request object request message system.out.println (" I was executed request! ); chain.doFilter(req, resp); System.out.println(" I am executed response again! ") ); } public void init(FilterConfig config) throws ServletException { } }Copy the code

Intercepting path configuration: concrete resource path: /index.jsp Filters are executed only if the index.jsp resource is accessed.

2. Block directory: /user/* When accessing all resources under /uer, the filter will be executed.

3. Suffix name interception: the filter executes when *.jsp accesses all resources with a suffix name JSP.

4. Block all resources:

How resources are accessed: Request forward filters are not executed. 1. Annotation configuration. You can configure multiple values to set the dispatcherTypes property

REQUEST: indicates the default value. The browser directly requests resources. FORWARD: indicates that the browser forwards resourcesCopy the code

2. Web. XML comments

@webFilter (value = "/*",dispatcherTypes = dispatcherType. REQUEST) public class FilterTest3 implements Filter { public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {system.out. println(" I am executed!" ); chain.doFilter(req, resp); } public void init(FilterConfig config) throws ServletException { } } @WebFilter(value = "/*", DispatcherTypes = {DispatcherType. REQUEST, DispatcherType.FORWARD}) <filter> <filter-name>FilterTest1</filter-name> <filter-class>filter.FilterTest1</filter-class>  </filter> <filter-mapping> <filter-name>FilterTest1</filter-name> <url-pattern>/*</url-pattern> <dispatcher>FORWARD</dispatcher> </filter-mapping>Copy the code

Filter chain (multiple filters) :

Execute filter 1 first, then filter 2, then filter 2, then filter 1.

1. The annotation configuration compares the rules by the string of the class name, with the smaller ones executed first. For example, AFilter,BFilter AFilter is executed first.

2. Web. XML configuration:

<filter-mapping>
Copy the code

Whoever is defined above will execute first.

4. The Filter case

Case 1: Login Verification 1. Access certain resources and check whether they are logged in

2. If yes, the system permits the login.

3. If you have not logged in, the system displays you have not logged in, please log in first.

// @webfilter ("/*")// Public class FilterTest4 implements Filter {public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { //1. Request = (HttpServletRequest)req; String uri = request.getrequestURI (); //2. // Exclude login related resources, CSS/js/fonts, etc If (uri. The contains ("/login JSP ") | | uri. The contains ("/loginServlet ") | | uri. The contains ("/CSS/") | | uri. The contains ("/js/")) {/ / the user is like login, Release chain. DoFilter (the req, resp); GetSession ().getAttribute("user");}else{// Not included, need to verify whether the user is logged in //3. if(user! =null){// Allow chain.dofilter (req, resp); }else{request. SetAttribute ("login_msg"," If you want to login, please login first! ); request.getRequestDispatcher("/login.jsp"); } } } public void init(FilterConfig config) throws ServletException { } }Copy the code

Case 2: Filtering sensitive words

Analysis:



The case requires enhancements to the Request object.

What about enhancements? Functional design patterns for enhanced objects: Some common ways to solve fixed problems. Decoration mode:

Proxy mode: Concept: 1. Real object: the object being proxied. Proxy object 3. Proxy mode: The proxy object proxies the real object to enhance the real object. Implementation: 1. Static proxy describes the proxy mode in a class file.

2. Dynamic proxy

Form proxy classes in memory (dynamically generated in memory).



Note: Please read the following dynamic proxy knowledge and then see the implementation of case 2

Case 2:

1. Enhance the reqUSET object and enhance the methods related to obtaining parameters.

2. Release and pass the proxy object.

Code implementation:

/** * @webFilter ("/*") public class FilterSensitiveWords implements Filter {public void destroy() {} public  void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {// Create a proxy object, ServletRequest proxy_req=(ServletRequest) proxy.newProxyInstance (req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// Enhance getParameter method // Check if it is the method if(method.getName().equals("getParameter")){// Enhance the return value String value = (String)method.invoke(req,args); if(value! =null){ for(String str:list){ if(value.contains(str)){ value = value.replaceAll(str,"**"); } } } return value; } return method.invoke(req,args); }}); //2. Release chain. DoFilter (proxy_req, resp); } private List<String> list = new ArrayList<>(); Public void init(FilterConfig config) throws ServletException {try {//1. ServletContext ServletContext = config.getServletContext(); String realPath = servletContext.getRealPath("/WEB-INF/classes/SensitiveWords.txt"); Br = new BufferedReader(new FileReader(realPath)); String line =null; while ((line = br.readLine())! =null){ list.add(line); } br.close(); System.out.println(list); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }}}Copy the code

Test the servlet:

@WebServlet("/ServletSensitiveWordsTest") public class ServletSensitiveWordsTest extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String msg =request.getParameter("msg"); System.out.println(name+":"+msg); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); }}Copy the code

Results:



Key: Note the path problem:

SensitiveWords in the SRC source file directory.

1. Load the configuration file (obtain the real path of the file)

ServletContext servletContext = config.getServletContext();

String realPath = servletContext.getRealPath

(“/WEB-INF/classes/SensitiveWords.txt”);

05. Dynamic proxy

Implementation steps: 1. The proxy object implements the same interface as the real object.

2. Proxy object = proxy.newProxyInstance ();

3. Invoke methods using proxy objects.

4. Enhancement methods. Enhancement method: 1. Enhance the parameter list.

2. Enhance return value types.

3. Enhance method body execution logic. Practice understanding:

package proxy; public interface SaleComputer { public String sale(double money); public void show(); } /** * real class */ public class ASUS implements SaleComputer{@override public String sale { System.out.println(" spend "+money+" shoot a computer!" ); return "ASUS"; } @override public void show() {system.out.println ( ); }} public class ProxyTest {public static void main(String[] args) { Class loader: real object.getClass ().getClassLoader() 2. Array of interfaces: real objects.getClass ().getinterfaces () 3. Processor: new InvocationHandler() */ SaleComputer proxy_asus=(SaleComputer) Proxy.newProxyInstance(asus1.getClass().getClassLoader(), asus1.getClass().getInterfaces(), New InvocationHandler() {** ** Proxy logic to write methods: @param proxy proxy object @param Method The methods that the proxy object calls are wrapped as objects @param args When the proxy object calls a method, @override Public Object invoke(Object proxy, Method Method, Object[] args) throws Throwable {/* system.out.println (" This method executes..." ); System.out.println(method.getName()); /* Object obj = method.invoke(asus1,args); */ // enhance parameters; If (method.getName().equals("sale")){double money = (double)args[0]; Money * = 0.8; // Invoke this method with a real object. String obj = (String) method.invoke(asus1,money); // Enhance the return value type obj+"_ mouse pad "; }else { Object obj = method.invoke(asus1,args); return obj; }}}); //3. Call method String computer = proxy_asus.sale(9000); System.out.println(computer); }}Copy the code

6. Summary of the Listener

Concept: One of the three major components of the Web. Event monitoring mechanism In program development, it is often necessary to monitor some events, such as mouse click events, monitor keyboard press events, and so on.

Event: an action by the user, such as clicking a button…

Event source: The object that generated the event.

Listener: Listens for events that occur on event sources.

Register listeners: Bind events, event sources, and listeners together. When an event occurs on an event source, the listener code is executed.

ServletContextListener: Listens for the creation and destruction of a ServletContext object.

Void contextDestroyed(ServletContextEvent sCE) is called after the ServletContext object is created. void contextInitialized(ServletContextEvent sce)Copy the code

07.ServletContextListener

Steps: 1. Define a class that implements the ServletContextListener interface.

2. Copying method.

3. The configuration 1. Web. XML

<listener>
        <listener-class>listener/ServletContextListenerTest1</listener-class>
    </listener>
Copy the code

Specify initialization parameters:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/classes/applicationContext.xml</param-value>
    </context-param>
Copy the code

2. Annotate the configuration

@WebListener @WebListener public class ServletContextListenerTest1 implements ServletContextListener { // Listen for ServletContext creation, Override public void contextInitialized(ServletContextEvent sce) {// Load the resource file //1. ServletContext ServletContext = sce.getServletContext(); / / 2. Load the resource files String contextConfigLocation = servletContext. GetInitParameter (" contextConfigLocation "); / / 3. The real path String realPath = servletContext. GetRealPath (contextConfigLocation); Try {FileInputStream fis = new FileInputStream(realPath); System.out.println(fis); } catch (FileNotFoundException e) { e.printStackTrace(); }} // The ServletContext object is destroyed after the server is shut down. @override public void contextDestroyed(ServletContextEvent sce) {}}Copy the code

There is no such thing as perfection, only striving for the best. This heart without pressure, the results will be better.