更新:
服务端给客户端的响应也会经过过滤器
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//将“敏感词”转为 ***
servletRequest.setCharacterEncoding("UTF-8");
String name = servletRequest.getParameter("name");
name = name.replaceAll("敏感词", "***");
servletRequest.setAttribute("name", name);
System.out.println("这是过滤敏感词的过滤器");
filterChain.doFilter(servletRequest, servletResponse);
System.out.println("这是响应之后的过滤器");
}
输出为:
这是过滤敏感词的过滤器
张三***李四
这是响应之后的过滤器
分割线
首先,过滤器有什么用?
1、⽤来拦截传⼊的请求和传出的响应。
2、修改或以某种⽅式处理正在客户端和服务端之间交换的数据流。
过滤器的作用位置
上图中服务端的响应应该还有经过过滤器
如何使用?
与使⽤ Servlet 类似,Filter 是 Java WEB 提供的⼀个接⼝,开发者只需要⾃定义⼀个类并且实现该接⼝
即可
配置方式
xml文件配置
<filter>
<filter-name>charcater</filter-name>
<filter-class>com.trygzb.filter.CharacterFilter</filter-class>
</filter> <filter-mapping>
<filter-name>charcater</filter-name>
<url-pattern>/login</url-pattern>
<url-pattern>/test</url-pattern>
</filter-mapping
等于使用注解配置
@WebFilter("/login")
public class MyFilter implements Filter {
}
实现Filter接口,重写doFilter方法即可
在doFilter中对请求进行过滤
public class CharacterFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain) throws IOException, ServletException
{
servletRequest.setCharacterEncoding("UTF-8");
filterChain.doFilter(servletRequest,servletResponse);
}
}
注意:
doFilter ⽅法中处理完业务逻辑之后,必须添加filterChain.doFilter(servletRequest,servletResponse);
Filter的生命周期
init ⽅法:只调⽤⼀次,当 Filter 的实例化对象创建完成之后调⽤
doFilter:调⽤多次,访问 Filter 的业务逻辑都写在 Filter 中
destory:只调⽤⼀次,Tomcat 关闭时调⽤。
Filter小测试
统⼀处理中⽂乱码 + 屏蔽敏感词
@WebFilter("/test")
public class WordFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain) throws IOException, ServletException
{
servletRequest.setCharacterEncoding("UTF-8");
//将"敏感词"替换成"***"
String name = servletRequest.getParameter("name");
name = name.replaceAll("敏感词","***");
servletRequest.setAttribute("name",name);
filterChain.doFilter(servletRequest,servletResponse);
}
}
2.控制资源的访问权限(用户必须有用户名才能操作)
@WebFilter("/download.jsp")
public class DownloadFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse
servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");
if(name == null){
//不是登录状态
response.sendRedirect("/login.jsp");
}else{
filterChain.doFilter(servletRequest,servletResponse);
}
}
}