【工程截图】
【web.xml】
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>FilterDemo01</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.Higgin.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> <!-- 过滤所有 --> </filter-mapping> </web-app>
【ServletTest01.java】
package com.Higgin.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class ServletTest01 */ @WebServlet("/ServletTest01") public class ServletTest01 extends HttpServlet { private static final long serialVersionUID = 1L; public ServletTest01() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.getWriter().write("中国 加油!China Come on!"); System.out.println("执行ServletTest01---"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
【CharacterEncodingFilter.java】
package com.Higgin.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; public class CharacterEncodingFilter implements Filter{ private FilterConfig filterConfig=null; private String defaultCharset="UTF-8"; //自己先设计一个缺省的编码 @Override public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig=filterConfig; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("进入doFilter()......"); String charset=filterConfig.getInitParameter("charset"); //获取配置文件的charset的value if(charset==null){ //未成功获取charset,就将缺省的defaultCharset赋值给charset charset=defaultCharset; } request.setCharacterEncoding(charset); response.setCharacterEncoding(charset); response.setContentType("text/html;character="+charset); chain.doFilter(request, response);//让目标资源执行,放行 } @Override public void destroy() { } }
【运行结果】