1.过滤器概述
过滤器,顾名思义就是对事物进行过滤的,在Web中的过滤器,当然就是对请求进行过滤,我们使用过滤器,就可以对请求进行拦截,然后做相应的处理,实现许多特殊功能。如登录控制,权限管理,过滤敏感词汇等
要在Javaweb项目中使用过滤器,实现Java - Servlet - Filter接口即可:
以下是一个模板,需要实现三个方法:
import javax.servlet.*; import java.io.IOException; public class CharacterEncodingFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { } @Override public void destroy() { Filter.super.destroy(); } }
2.使用过滤器解决中文编码异常问题
Javaweb默认网页内输出中文会发生乱码,我们可以通过如下两行来设置请求和响应编码,以解决这个问题:
servletResponse.setContentType("text/html;charset=utf-8");
但是当存在多个Servlet时势必会发生不便(产生大量冗余代码),此时可以通过过滤器解决:
重写doFilter方法:
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletResponse.setContentType("text/html;charset=utf-8"); // 必须要让过滤器继续通行 filterChain.doFilter(servletRequest, servletResponse); }
同时,在web.xml文件中也要进行配置:
<filter> <filter-name>EncodingFilter</filter-name> <filter-class>CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <!-- 过滤整个网站的请求 --> <url-pattern>/*</url-pattern> </filter-mapping>
如上即可解决乱码问题🧨
3.使用过滤器实现用户登录权限拦截
如下的doFilter过滤判断,如果用户的登录SESSION为null,则跳转登录页面:
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // 强转为HttpServletRequest格式 HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if (request.getSession().getAttribute("USER_LOGIN_SESSION") == null) { response.sendRedirect("/login.jsp"); } filterChain.doFilter(request, response); }