通过过滤器(Filter)解决JSP的Post和Request中文乱码问题
程序员文章站
2022-06-11 14:14:30
jsp代码:
import javax.servlet.*;
import javax.servlet.http.*;
public class char...
jsp代码:
import javax.servlet.*; import javax.servlet.http.*; public class charsetfilter implements filter { public void destroy() { } public void dofilter(servletrequest request, servletresponse response, filterchain chain) { try { httpservletrequest httprequest = (httpservletrequest)request; string method = httprequest.getmethod().tolowercase(); if(method.equals("post")) { //如果是post,即表单方法,直接设置charset即可 request.setcharacterencoding("utf-8"); } else if(method.equals("get")) { //如果是get方法 request.setcharacterencoding("utf-8"); request = new httpservletrequestwrapper((httpservletrequest)request) { public string getparameter(string str) { try { return new string(super.getparameter(str).getbytes("iso-8859-1"),"gbk"); } catch(exception e) { return null; } } }; } chain.dofilter(request, response); } catch(exception e){} } public void init(filterconfig filterconfig) { } }
过滤器配置:
<filter> <filter-name>charfilter</filter-name> <filter-class>charsetfilter</filter-class> </filter> <filter-mapping> <filter-name>charfilter</filter-name> <url-pattern>/*</url-pattern> <dispatcher>request</dispatcher> </filter-mapping>