Write in front: Recently, I have been reviewing the previous content and learning algorithms, so I did not continue to learn new knowledge, so I stopped for a longer period of time and formally returned to learn new knowledge from today!
Filter: Filter
- Concepts:
- Life's filters: water purifiers, air purifiers, bandits,
- Filters in the web: When accessing a server's resources, filters can intercept requests and perform special functions.
- Functions of the filter:
- Usually used to complete common operations.For example: login validation, uniform encoding processing, sensitive character filtering...
- Quick Start:
- Steps:
- Define a class to implement the interface Filter
- Replication Method
- Configure Interception Path
- web.xml
- annotation
- Steps:
- Code:
@WebFilter("/*")//This filter is executed before all resources are accessed public class FilterDemo1 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("filterDemo1 Executed...."); //Release filterChain.doFilter(servletRequest,servletResponse); } @Override public void destroy() { } }
- Filter details:
- web.xml configuration
<filter> <filter-name>demo1</filter-name> <filter-class>cn.itcast.web.filter.FilterDemo1</filter-class> </filter> <filter-mapping> <filter-name>demo1</filter-name> <!-- Intercept Path --> <url-pattern>/*</url-pattern> </filter-mapping>
- Filter Execution Process
- Execute filter
- Post-release resources
- Go back and execute the code below the filter release code
- Filter life cycle approach
- Init: After the server starts, a Filter object is created and the init method is called.Execute only once.For loading resources
- doFilter: Executes each request when a resource is intercepted.Execute multiple times
- Destroy: The Filter object was destroyed after the server was shut down.If the server shuts down normally, the destroy method is executed.Execute only once.Used to release resources
- Detailed filter configuration
- Intercept path configuration:
- Specific resource path: /index.jsp The filter will only be executed if the index.jsp resource is accessed
- Intercept directory: /user/* When accessing all resources under/user, the filter will be executed
- Suffix name interception: *.jsp accesses all suffix-named JSP resources and the filter is executed
- Intercept all resources: /* When accessing all resources, the filter will be executed
- Intercept configuration: how resources are accessed
- Note Configuration:
- Set dispatcherTypes property
- REQUEST: Default value.Browser requests resources directly
- FORWARD: Forward access to resources
- INCLUDE: Contains access resources
- ERROR: Error jumping resources
- ASYNC: Asynchronous access to resources
- web.xml configuration
- Set <dispatcher></dispatcher>tab
- Filter chain (configuring multiple filters)
-
Execution order: If there are two filters: filter 1 and filter 2
- Filter 1
- Filter 2
- Resource Execution
- Filter 2
- Filter 1
-
Question of filter order:
- Annotation Configuration: Compare by string comparison rule of class name, small value is executed first
*For example: AFilter and BFilter, AFilter executes first. - web.xml Configuration: Who Defines Above and Who Executes First
- Annotation Configuration: Compare by string comparison rule of class name, small value is executed first
- Case:
- Case 1_Logon Verification
- Requirements:
- Access resources for the day17_case case.Verify that it is logged on
- If you are logged in, you will be released directly.
- If you are not logged in, jump to the login page and prompt "You are not logged in, please log in first".
- Requirements:
- Case 1_Logon Verification
package cn.itcast.web.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * Logon Authentication Filter */ @WebFilter("/*") public class LoginFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { System.out.println(req); //0. Cast HttpServletRequest request = (HttpServletRequest) req; //1.Get Resource Request Path String uri = request.getRequestURI(); //2.Determine if login-related resource paths are included,Be careful to exclude css/js/picture/Resources such as Authentication Codes if(uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/fonts/") || uri.contains("/checkCodeServlet") ){ //Yes, the user just wants to log in.Release chain.doFilter(req, resp); }else{ //Not included, need to verify user logon //3.From Get session Get in user Object user = request.getSession().getAttribute("user"); if(user != null){ //Logged in.Release chain.doFilter(req, resp); }else{ //Not logged in.Jump to login page request.setAttribute("login_msg","You are not logged in yet, please log in"); request.getRequestDispatcher("/login.jsp").forward(request,resp); } } // chain.doFilter(req, resp); } public void init(FilterConfig config) throws ServletException { } public void destroy() { } }
- Case 2 Sensitive Word Filtering
-
Requirements:
- Sensitive vocabulary filtering for data entered in day17_case
- Sensitive Vocabulary Reference Sensitive Vocabulary.txt
- If sensitive, replace with ***
-
Analysis:
- Enhance the request object.Enhanced acquisition parameter related methods
- Release.Delivery Proxy Object
-
Enhance the functionality of the object:
- Design patterns: some common ways to solve fixed problems
- Decoration Mode
- proxy pattern
- Concepts:
- Real object: the object being proxied
- Proxy object:
- Proxy mode: Proxy objects proxy real objects to enhance the function of real objects
- Implementation:
- Static Proxy: There is a class file describing the proxy mode
- Dynamic proxy: Form proxy classes in memory
- Steps to achieve:
- Proxy objects and real objects implement the same interface
- Proxy object= Proxy.newProxyInstance();
- Call a method using a proxy object.
- Enhancement Method
Agent conceptual analysis: Code implementation:
package cn.itcast.web.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; /** * Sensitive Vocabulary Filter */ @WebFilter("/*") public class SensitiveWordsFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { //1. Create proxy objects to enhance getParameter methods 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 //Determine whether it is getParameter Method if(method.getName().equals("getParameter")){ //Enhanced Return Value //Get 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; } //Determine if the method name is getParameterMap //Determine if the method name is getParameterValue return method.invoke(req,args); } }); //2.Release chain.doFilter(proxy_req, resp); } private List<String> list = new ArrayList<String>();//Sensitive Vocabulary Collection public void init(FilterConfig config) throws ServletException { try{ //1.Get the true path to the file ServletContext servletContext = config.getServletContext(); String realPath = servletContext.getRealPath("/WEB-INF/classes/Sensitive vocabulary.txt"); //2.read file BufferedReader br = new BufferedReader(new FileReader(realPath)); //3.Add each row of data to the file list in String line = null; while((line = br.readLine())!=null){ list.add(line); } br.close(); System.out.println(list); }catch (Exception e){ e.printStackTrace(); } } public void destroy() { } }
Listener: Listener
- Concept: One of the three components of the web.
- Event monitoring mechanism
- Event: One thing
- Event source: where the event occurred
- Listener: an object
- Register listeners: Bind events, event sources, and listeners together.Execute listener code when an event occurs on the event source
- ServletContextListener: Listens for creation and destruction of ServletContext objects
- Method:
- void contextDestroyed(ServletContextEvent sce): This method is called before the ServletContext object is destroyed
- void contextInitialized(ServletContextEvent sce): This method is called when a ServletContext object is created
- Steps:
- Define a class to implement the ServletContextListener interface
- Replication Method
- To configure
- web.xml
<listener> <listener-class>cn.itcast.web.listener.ContextLoaderListener</listener-class>
- Specify initialization parameters
- Notes:
- @WebListener
31 original articles were published, 4 were praised, and 868 were visited