【WEB小工具】EncodingFilter—设置全局编码
1.我们知道,如果是POST请求,我们需要调用request.setCharacterEncoding("utf-8")
方法来设计编码。
1 public void doGet(HttpServletRequest request, HttpServletResponse response) 2 throws ServletException, IOException { 3 request.setCharacterEncoding("gbk"); //只适用于post提交,不适用于get 4 response.setCharacterEncoding("gbk"); 5 }
2.如果是GET请求,我们需要自己手动来处理编码问题。
3.如果我们使用了EncodingFilter,那么就处理了POST和GET请求的编码问题。
修改web.xml:
<!-- 处理全站请求编码。无论是GET还是POST,默认是UTS-8 --> <filter> <filter-name>EncodingFilter</filter-name> <filter-class>cn.itcast.filter.EncodingFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
EncodingFilter() 类源代码:
1 package cn.itcast.filter; 2 3 import java.io.IOException; 4 5 import javax.servlet.Filter; 6 import javax.servlet.FilterChain; 7 import javax.servlet.FilterConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.ServletRequest; 10 import javax.servlet.ServletResponse; 11 import javax.servlet.http.HttpServletRequest; 12 13 14 public class EncodingFilter implements Filter { 15 private String charset = "UTF-8"; 16 @Override 17 public void destroy() {} 18 19 @Override 20 public void doFilter(ServletRequest request, ServletResponse response, 21 FilterChain chain) throws IOException, ServletException { 22 HttpServletRequest req = (HttpServletRequest) request; 23 if(req.getMethod().equalsIgnoreCase("GET")) { 24 if(!(req instanceof GetRequest)) { 25 req = new GetRequest(req, charset);//澶勭悊get璇锋眰缂栫爜 26 } 27 } else { 28 req.setCharacterEncoding(charset);//澶勭悊post璇锋眰缂栫爜 29 } 30 chain.doFilter(req, response); 31 } 32 33 @Override 34 public void init(FilterConfig fConfig) throws ServletException { 35 String charset = fConfig.getInitParameter("charset"); 36 if(charset != null && !charset.isEmpty()) { 37 this.charset = charset; 38 } 39 } 40 }
梦想要一步步来!