Filter功能
在HttpServletRequest到达Servlet之前,拦截客户的HttpServletRequest。根据需要检查HttpServletRequest,也可以修改HttpServletRequest 头和数据。
在HttpServletResponse到达客户端之前,拦截HttpServletResponse。根据需要检查HttpServletResponse,也可以修改HttpServletResponse头和数据。
Filter实现
- 在web.xml配置filter
<filter>
<filter-name>EncodingFiler</filter-name>
<filter-class>com.my.king.EncodingFiler</filter-class>
</filter>
<filter-mapping>
<filter-name>EncodingFiler</filter-name>
<!--拦截所有请求-->
<url-pattern>/*</url-pattern>
</filter-mapping>
:在<filter-mapping>
里面还可以添加<dispatcher></dispatcher>
- 创建EncodingFiler类实现Filter接口
public class EncodingFiler implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//解决post乱码
servletRequest.setCharacterEncoding("UTF-8");
//解决返回乱码
servletResponse.setContentType("text/html;charset=UTF-8");
HttpServletRequest request = (HttpServletRequest)servletRequest;
HttpServletResponse response = (HttpServletResponse)servletResponse;
String servletPath = request.getServletPath();
if(servletPath.startsWith("/user")) {
System.out.println("拦截");
HttpSession session = request.getSession(false);
if (session != null) {
System.out.println("拦截session");
Object name = session.getAttribute("name");
if (name != null) {
System.out.println("拦截name");
filterChain.doFilter(servletRequest,servletResponse);
} else {
response.sendRedirect(request.getContextPath()+"/index.jsp");
return;
}
}
} else {
System.out.println("未拦截");
filterChain.doFilter(servletRequest,servletResponse);
}
}
@Override
public void destroy() {
}
}
多个过滤器Filter执行顺序
防止中文乱码过滤器
项目使用spring框架时。当前台JSP页面和Java代码中使用了不同的字符集进行编码的时候就会出现表单提交的数据或者上传/下载中文名称文件出现乱码的问题,那就可以使用这个过滤器。
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name><!--用来指定一个具体的字符集-->
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name><!--true:无论request是否指定了字符集,都是用encoding;false:如果request已指定一个字符集,则不使用encoding-->
<param-value>false</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>