一. 前言
之前我们的项目中,只要编写过滤器,就需要实现Filter接口,并实现Filter中的三个方法,但是这样做存在很多问题,比如init方法和destroy方法很多时候我们并不需要在里面做任何操作,但是每次实现Filter接口都需要去重写,再比如doFilter方法的ServletRequest和ServletResponse参数每次都需要强转成HttpServletRequest和HttpServletResponse等等。
这些重复且繁琐的操作,我们便可以重写Filter来统一解决。
二. 重写Filter
重写Filter的操作非常简单,新建一个类,实现Filter接口,将之前复杂且繁琐的操作实现即可:
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public abstract class HttpFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; this.doFilter(request,response,filterChain); } public abstract void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException; @Override public void destroy() { } }
因为doFilter是抽象方法,所以HttpFilter 也要变成抽象类,接下来,我们编写过滤器的时候,只需要继承我们的编写的HttpFilter即可,继承HttpFilter的类不需要强制重写init和destroy,但是必须重写doFilter:
package com.oaec.day07.filter; import com.alibaba.fastjson.JSON; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; @WebFilter(urlPatterns = "/hello") public class LoginFilter extends HttpFilter { //init和destroy不需要强制重写,根据需要选择是否重写即可 @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { //这里面不需要再次强转HttpServlet,直接使用request和response即可 } }
现在,只要我们访问/hello,Tomcat就会先执行Filter中的doFilter方法,并在该方法中调用子类实现的doFilter方法
三. 使用重写的Filter设置字符集
之前我们每个Servlet中都需要手动设置字符集,这同样也是一个繁琐且重复的操作,我们可以手动编写一个过滤器,给所有的页面设置字符集
import com.oaec.day08.util.HttpFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter(urlPatterns = "/*") public class CharacterEncodingFilter extends HttpFilter { @Override public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); filterChain.doFilter(request,response); } }
请登录之后再进行评论