当前位置:网站首页>Filter filter
Filter filter
2022-07-19 07:25:00 【INSIGNER】
1 Concept
- filter The filters are javaWeb One of the three components .
- It's also an interface
- The main function is to intercept requests , Filtering response
The main application scenarios are .
- Permission check
- Diary operation
- Business management
- ....
1.1 Filter example
This is a filter used to determine whether the user has logged in .
public class ManagerFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
// Conduct Filter Business
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
Object user = httpServletRequest.getSession().getAttribute("user");
if (user == null) {
httpServletRequest.getRequestDispatcher("/pages/user/login.jsp").forward(servletRequest,servletResponse);
} else {
//filterChain The function is similar to request forwarding .
filterChain.doFilter(servletRequest,servletResponse);
}
}
@Override
public void destroy() {
}
}
web.xml Configuration in
<servlet>
<servlet-name>BookServlet</servlet-name>
<servlet-class>com.atguigu.web.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookServlet</servlet-name>
<url-pattern>/manager/bookServlet</url-pattern>
</servlet-mapping>
<filter>
<filter-name>ManagerFilter</filter-name>
<filter-class>com.atguigu.filter.ManagerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>ManagerFilter</filter-name>
<url-pattern>/pages/manager/*</url-pattern>
<!-- Here, you need to ensure that the address of the filter and the request service are the same , This is the access address to be blocked by the filter -->
<url-pattern>/manager/bookServlet</url-pattern>
</filter-mapping>
As can be seen from the above example
- xml in Of an object url There can be more than one .
- The filter has no specific access address , All addresses must be the addresses of other components that already exist , It's the same with Filter Corresponding to , A project will not have only one place to check whether the user logs in .
1.2 working principle

This is how the filter example above works . Of course , A real project cannot be so simple .
1.3 Life cycle
- Construction method
- init Initialization method
front 1、2 Bu huizai web Execute... At startup . Namely Servlet Not yet created FIlter And we're done . - doFilter Filtration method
The first 3 Step will be executed for each interception - destroy The destruction
The first 4 Step , stop it web Execution of the project .
1.4 FilterConfig class
FilterConfig when Filter Configuration file for
and Servlet be similar Tomcat Each creation Filter A corresponding FilterConfig class , Contains Filter Configuration information .
FilterConfig The role of
- get Filter The name of filter-name
- get Filter Is the initialization parameter of init-param Initialize parameters
- obtain ServletContext object
java Code :
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("2.Filter Of init(FilterConfig filterConfig) initialization ");
// 1、 obtain Filter The name of filter-name The content of
System.out.println("filter-name The value of is :" + filterConfig.getFilterName());
// 2、 To get in web.xml Configured in init-param Initialize parameters
System.out.println(" Initialize parameters username The value of is :" + filterConfig.getInitParameter("username"));
System.out.println(" Initialize parameters url The value of is :" + filterConfig.getInitParameter("url"));
// 3、 obtain ServletContext object
System.out.println(filterConfig.getServletContext());
}
A complete point Filter xml To configure
<!--filter The tag is used to configure a Filter filter -->
<filter>
<filter-name>AdminFilter</filter-name>
<filter-class>com.atguigu.filter.AdminFilter</filter-class>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost3306/test</param-value>
</init-param>
</filter>
1.5 FilterChain Filter chain
You can pack here FilterChain The image is called a two-way Chain .
This chain is linked and the order cannot be changed . If Filter02 If there is an error, it will return directly , No more to Servlet send data , If Servlet error , The system returns no direct error .
Post code has no format restrictions . The only thing to notice , He wrote that filterChain.doFilter() hinder ,Filter The order of execution of is determined by ,Filter stay xml The order of definitions in determines , Cannot be changed in the program .
Add post code
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
try {
filterChain.doFilter(servletRequest,servletResponse);
// The program runs all the way from the last business to here , Ensure that the database operation is absolutely correct .
JdbcUtils.commitAndClose();// Commit transaction
} catch (Exception e) {
JdbcUtils.rollbackAndClose();// Roll back the transaction
e.printStackTrace();
throw new RuntimeException(e);// Throw the anomaly to Tomcat Manage and display friendly error pages
}
}
1.6 Filter Configuration of connection path
At the beginning of the path / It stands for http://ip:port/ Project path
1.6.1 Precise configuration
<url-pattern>/target.jsp</url-pattern>
1.6.2 Directory configuration
<url-pattern>/pages/manager/*</url-pattern>
1.6.3 Suffix path
<url-pattern>/*.html</url-pattern>
Filter The filter only cares about whether the requested address matches , Does not care if the requested resource exists , That's about the wrong page .
1.7 ThreadLocal Use
ThreadLocal characteristic :
- You can associate a data for the current thread , But only one ( It's OK map And access data )
- Every ThreadLocal object , Only one data can be associated for the current thread , If you want to associate multiple , You can only use multiple ThreadLocal Object instances .
- Every ThreadLocal Object instances are defined in static type
- ThreaLocal Data stored in , When the thread is destroyed . Will be JVM The virtual machine is automatically released .
Usage method
// establish ThreadLocal object
public static ThreadLocal<Object> threadLocal = new ThreadLocal<Object>();
// Set up threadLocal Value
threadLocal.set("value");
// get threadLocal Value
threadLocal.get(); // Values can be obtained without parameters
Use ThreadLocal The benefits of , No matter what ThreadLocal new Where is the , Each thread is unique , It can prevent high concurrency , Release data error .
1.8 Use Filter and ThreadLocal Portfolio Management jdbc Business
Principle analysis :
Transaction rollback is set in Filter Post code of , Be sure to throw exceptions when processing transactions , Otherwise, the transaction cannot return .
Set the error interface , There is no need to set error jump for the error page alone , Just configure , If an error occurs, the system will automatically go to the error page .
<!--error-page Label configuration , After server error , Auto jump page -->
<error-page>
<!--error-code Is the wrong type -->
<error-code>500</error-code>
<!--location The label indicates . The page path to jump to -->
<location>/pages/error/error500.jsp</location>
</error-page>
边栏推荐
- 网络知识-04 网络层-ICMP协议
- m基于matlab的MIMO信道容量分析,对比了不同天线数量;非码本预编码SVD,GMD;码本预编码DFT,TxAA以及空间分集
- regular expression
- Security自动登录与防CSRF攻击冲突解决办法
- Quickly understand redirection
- What if the website is hijacked?
- M analysis of anti-interference performance of high-speed frequency hopping communication system based on Simulink
- 网络知识-04 网络层-IPv6
- 爬虫基础—爬虫的基本原理
- Product Case Interviews
猜你喜欢

Cracking Metric/Business Case/Product Sense Problems

Pytorch learning diary (II)

m基于matlab的协作mimo分布式空时编码技术的仿真

深度学习笔记 Coursera Deep learning Notes

Summary of Statistics for Interview

论文阅读:Deep Residual Learning in Spiking Neural Networks

Pytorch learning notes (I)

Network knowledge-05 transport layer UDP

Legendary game setup tutorial

m基于Simulink的高速跳频通信系统抗干扰性能分析
随机推荐
The use and differences of dictionaries, tuples and lists,
用for循环怎么输出数字菱形啊
Minecraft integration package [gtnh] gray Technology: new vision server building tutorial
Review of Linear Algebra
Dictionary, use of sets, conversion of data types
Data analysis and visualization -- the shoes with the highest sales volume on jd.com
Pytorch learning diary (4)
2021-10-25 browser compatibility problems
m基于matlab的BTS天线设计,带GUI界面
Sword finger offer question brushing record - offer 06 Print linked list from end to end
How do you know whether the network needs to use advanced anti DDoS server? How to choose the computer room is also very important, as well as the stability of the later business
Summary of Statistics for Interview
m在VBLAST协作MIMO系统分部使用LDPC,Turbo,卷积三种信道编译码进行误码率matlab仿真
PyTorch学习日记(三)
Review of Linear Algebra
m基于simulink的16QAM和2DPSK通信链路仿真,并通过matlab调用simulink模型得到误码率曲线
Paper reading: deep residual learning in spiking neural networks
Product Case Interviews
网络知识-05 传输层-TCP
Pytorch learning diary (4)