日期:2014-05-18 浏览次数:21260 次
package tools; import javax.servlet.http.HttpServlet; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.FilterChain; public class EncodingFilter extends HttpServlet implements Filter { private FilterConfig config = null; private String targetEncoding = "GBK"; public void init(FilterConfig filterConfig) { this.config = filterConfig; this.targetEncoding = config.getInitParameter("encoding"); } public void destroy() { config = null; targetEncoding = null; } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { ServletRequest request = (ServletRequest) servletRequest; try { request.setCharacterEncoding(targetEncoding); filterChain.doFilter(servletRequest, servletResponse); } catch (Exception ex) { ex.printStackTrace(); } } }
<filter> <filter-name>EncodingFilter</filter-name> <filter-class>[color=#FF0000]db.EncodingFilter[/color]</filter-class> <init-param> <param-name>encoding</param-name> <param-value>[color=#0000FF]GBK[/color]</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <filter> <filter-name>HelloFilter</filter-name> <filter-class>com.tarena.filter.HelloFilter</filter-class> </filter> <filter-mapping> <filter-name>HelloFilter</filter-name> <url-pattern>/hello</url-pattern> </filter-mapping> <filter> <filter-name>AppendFilter</filter-name> <filter-class>com.tarena.filter.AppendFilter</filter-class> </filter> <filter-mapping> <filter-name>AppendFilter</filter-name> <url-pattern>/hello</url-pattern> </filter-mapping> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>com.tarena.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>charset</param-name> <param-value>gbk</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </fi