日期:2014-05-16 浏览次数:20308 次
request.setCharacterEncoding("utf-8");
<filter> <filter-name>EncodingFilter</filter-name> <filter-class>leko.macleo.filter.EncodingFilter</filter-class> <init-param> <param-name>languageconfig</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>EncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
package leko.macleo.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.Filter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class EncodingFilter implements Filter { private FilterConfig filterConfig; private String enconfig; /** * Constructor of the object. */ public EncodingFilter() { super(); } // Handle the passed-in FilterConfig public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; //获得,web.xml文件中配置languageconfig 的值,我在web.xml文件中配置了languageconfig 的值为:utf-8; this.enconfig=this.filterConfig.getInitParameter("languageconfig"); System.out.println("过滤器初始化成功!"); } public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) { try { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; HttpSession session = request.getSession(); if (this.enconfig!=null) { request.setCharacterEncoding(this.enconfig); response.setCharacterEncoding(this.enconfig); System.out.println("过滤器处理中:"+this.enconfig); } //处理权交给下一个过滤器; // 这里放到达目的地前(进入)处理代码 filterChain.doFilter(req, res); // 这里放到达目的地(离开)的处理代码 } catch (IOException e) { e.printStackTrace(); } catch (ServletException e) { e.printStackTrace(); } } /** * Destruction of the servlet. <br> */ public void destroy() { // Just puts "destroy" string in log // Put your code here this.filterConfig=null; this.enconfig=null; System.out.println("过滤器销毁成功!"); //System.out.println("过滤器销毁成功!"); } }