当前位置:网站首页>Filter
Filter
2022-04-21 11:23:00 【Carbon water carbon water】
Filter
Tips
Usually to multiple Servlet Code for unified processing , Can be written in Filter in
effect :
- Log messages : Which needs to be recorded IP, When and what requests were accessed , Which parameters are passed in …
- Record exception log : Handle global exceptions
- Control access rights : Some or all functions of the system can only be used after logging in .
- Character set settings
Example
This is the login page login.jsp <br>
<form action="/loginServlet" method="get">
user name :<input type="text" name="username"/> <br>
The secret code :<input type="password" name="password"/> <br>
<input type="submit" />
</form>
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
resp.setContentType("text/html; charset=UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
if ("admin".equals(username) && "123456".equals(password)) {
req.getSession().setAttribute("user",username);
resp.getWriter().write(" Login successful !!!");
} else {
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
}
@WebFilter("/*")
public class AdminFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException,ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpSession session = httpServletRequest.getSession();
Object user = session.getAttribute("user");
// If it is equal to null, It means you haven't logged in yet
if (user == null) {
servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
return;
} else {
// Let the program continue to access the user's target resources
filterChain.doFilter(servletRequest,servletResponse);
}
}
}
If you don't use annotations , You need to in web.xml Middle configuration
<!--filter The tag is used to configure a Filter filter -->
<filter>
<!-- to filter Make up an alias -->
<filter-name>AdminFilter</filter-name>
<!-- To configure filter Full class name of -->
<filter-class>com.atguigu.filter.AdminFilter</filter-class>
</filter>
<!--filter-mapping To configure Filter The interception path of the filter -->
<filter-mapping>
<!--filter-name Indicates to which... The current interception path is given filter Use -->
<filter-name>AdminFilter</filter-name>
<!--url-pattern Configure interception path / Indicates that the request address is :http://ip:port/ Project path / Mapping to IDEA Of web Catalog /admin/* Indicates that the request address is :http://ip:port/ Project path /admin/* -->
<url-pattern>/admin/*</url-pattern>
</filter-mapping>
Life cycle
@WebFilter("/*")
public class MyFilter implements Filter {
public MyFilter() {
System.out.println("1. Construction method , Execute when starting the server ");
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("2. Initialization method , Execute when starting the server ");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("3.doFilter, Accessing any page that passes through this filter will execute ");
// Follow up
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
System.out.println("4.destroy, Execute when shutting down the server ");
}
}
FilterConfig class
Tips
Filter Filter profile class ,Tomcat Each creation Filter When , It will also create a FilterConfig class
The setting of interception path is the same as Servlet Medium url-pattern Set up
Filter effect :
- obtain Filter The name of filter-name The content of
- To get in Filter Configured in init-param Initialize parameters
- obtain ServletContext object
Example
@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
//org.apache.catalina.core.ApplicationContextFacade@d359b2b
System.out.println(filterConfig.getServletContext());
}
<!--filter The tag is used to configure a Filter filter -->
<filter>
<!-- to filter Make up an alias -->
<filter-name>AdminFilter</filter-name>
<!-- To configure filter Full class name of -->
<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>
FilterChain Filter chain
-
In more than one Filter When the filter is executed , they Priority of execution , By web.xml The order of configuration in , From top to bottom
-
all filter And target resources are executed in the same thread by default
-
Multiple Filter When jointly executed , They all use the same Request object
-
If a Filter Not written in doFilter, So it's time to Filter Start back to , Don't go any further
That is, the server thinks that the execution has been completed

版权声明
本文为[Carbon water carbon water]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204211122217979.html
边栏推荐
猜你喜欢

教你轻松解决CSRF跨站请求伪造攻击

【leetcode】647. Palindrome substring

pgpool-II 4.3 中文手册 - 入门教程

10000 yuan gift pool play "Lighthouse" prize essay attack

54000 stars all return to zero. Project Author: I regret it very much

Rhino software plug-in rhino plug-in visual studio create your first plug-in
![[high quality original] share some unknown and super easy-to-use API functions in sklearn module](/img/7c/5663e808d96ab38397d09226121187.png)
[high quality original] share some unknown and super easy-to-use API functions in sklearn module

Nocalhost for dapr remote debugging

Reading material: Information Technology Yearbook

Xftp文件名称显示乱码解决方法
随机推荐
万元礼品奖池 玩转「Lighthouse」有奖征文来袭
Unix哲学与高并发
[interview ordinary people vs Expert Series] understanding of B tree and B + tree
Teach you to easily solve CSRF Cross Site Request Forgery Attack
package. json
IDEA的LeetCode力扣插件设置
产品分享:Qt+OSG教育学科工具之地理三维星球
ES6新特性(7)之Proxy代理/Model模块/import/export
Matlab GUI application - lottery (animation demonstration)
MATLAB GUI---PicZoom动画演示
中天钢铁18个产品捧“金杯”
LocalDate、LocalDateTime、Date之间的互转
MATLAB---进度条动画演示
粉笔科技推行OMO一体化模式 双核驱动营收快速增长
Introduction to Alibaba's super large-scale Flink cluster operation and maintenance system
[lighthouse] intranet penetration FRP construction
pgpool-II 4.3 中文手册 - 入门教程
塔米狗资讯|国资委发言:支持上市公司采用企业并购融资手段拓展主业
1. Precision marketing practice Alibaba cloud odpscmd precision marketing data processing
OV代码签名和EV代码签名证书区别