web项目中的过滤器及其XML配置
过滤器Filter就像一个一个哨卡,用户的请求需要经过Filter
并且可以有多个过滤器
过滤器实现自动转换编码
过滤器实体:
package top.yibobo.web.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class EncodingFilter implements Filter{ private String encoder; @Override public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException { HttpServletRequest req=(HttpServletRequest)arg0; //设置请求对象的字符集 req.setCharacterEncoding(encoder); HttpServletResponse resp = (HttpServletResponse)arg1; resp.setContentType("text/html;charset="+encoder); arg2.doFilter(req, resp); System.out.println("完成字符集"+encoder+"转换"); } @Override public void init(FilterConfig filterConfig) throws ServletException { this.encoder=filterConfig.getInitParameter("encoder"); } }
XML文件的配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>jsp10</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 部署字符集转换过滤器 --> <filter> <filter-name>encodingFilter</filter-name> <filter-class>top.yibobo.web.filter.EncodingFilter</filter-class> <!-- 参数 --> <init-param> <param-name>encoder</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <!-- 过滤器拦截哪些URL --> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
/*代表的是过滤当前项目所有的页面。即每个页面都会经过过滤器,所以再也不用设置request和response的编码了
并且想要改成什么字符集编码,只需要在XML里面改一下就行,不需要动代码