Filter
Filter:过滤器,用来过滤网站的数据,如处理中文乱码、登陆验证等。
1. 步骤
编写一个类,实现Filter接口,并重写对应的方法。
package com.gs.filter; import jakarta.servlet.*; import java.io.IOException; /** * @author admin */ public class CharacterEncodingFilter implements Filter { @Override public void init(FilterConfig config) throws ServletException { } @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); chain.doFilter(request, response); } }
在
web.xml
中配置Filter<filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.gs.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/hello/*</url-pattern> </filter-mapping>