1、过滤器是服务器端代码,Servlet 之前的组件(请求先进 Filter,再进 Servlet),用于拦截传入的请求响应,对请求进行某些统一处理(设置编码解决中文乱码问题)
2、监视、修改处理正在客户端和服务器之间传输的数据流。
过滤器就是处于客户端和 Servlet 之间的一个组件,对客户端和 Servlet 之间的数据传输进行处理。
public interface Filter { default void init(javax.servlet.FilterConfig filterConfig) throws javax.servlet.ServletException { /* compiled code */ } void doFilter(javax.servlet.ServletRequest servletRequest, javax.servlet.ServletResponse servletResponse, javax.servlet.FilterChain filterChain) throws java.io.IOException, javax.servlet.ServletException; default void destroy() { /* compiled code */ } }
@WebFilter({"/student","/user","/account"}) 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); } }