时间:2021-07-01 10:21:17 帮助过:8人阅读
public class SetCharacterEncodingFilter implements Filter { class Request extends HttpServletRequestWrapper { public Request(HttpServletRequest request) { super(request); }
public String toChi(String input) { try { byte[] bytes = input.getBytes(”ISO8859-1″); return new String(bytes, “utf-8″); } catch (Exception ex) { } return null; }
private HttpServletRequest getHttpServletRequest() { return (HttpServletRequest) super.getRequest(); }
public String getParameter(String name) { return toChi(getHttpServletRequest().getParameter(name)); } public String[] getParameterValues(String name) { String values[] =getHttpServletRequest().getParameterValues(name); if (values != null) { for (int i = 0; i < values.length; i++) { values[i] = toChi(values[i]); } } return values; } }
public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { HttpServletRequest httpreq = (HttpServletRequest) request;
if (httpreq.getMethod().equals(”POST”)) {
request.setCharacterEncoding(”utf-8″);
} else { request = new Request(httpreq); }
chain.doFilter(request, response); }
public void init(FilterConfig filterConfig) throws ServletException { } }
然后在WEB-INF目录下的web.xml文件,配置下过虑器,
<filter> <filter-name>SetCharacterEncodingFilter</filter-name> <filter-class>peom.SetCharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>SetCharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
这里要注意的是:路径、代码尽量放在前面,最好是<web-app 的后面