Get请求,Post请求乱码问题解决方案

之所以出现乱码,主要是由于编码和解码采用的方法不同。

因此保证编码解码格式一致是避免乱码发生的重要前提。


问题背景:JavaWeb技术下,Tomcat作为容器,发送请求的时候出现乱码问题。


下面以两种常见的请求方式为例讲解乱码问题的解决方法。

1.Post方式请求乱码。

    自从Tomcat5.x以来,Get方式和Post方式提交的请求,tomcat会采用不同的方式来处理编码。

对于Post请求,Tomcat会使用request.setCharacterEncoding和response.setCharacterEncoding方法设置的编码格式进行处理。

如果未设置,则默认都采用iso-8859-1编码。因此如果在发送Post请求的时候出现乱码,常见的解决方法如下:

a)  request.setCharacterEncoding("utf-8");

b)  String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
(当然response的编码也不要忘记设置成utf-8的)

【注】:上面提供的是两种不同的方法,并不是一种方法的两个步骤!!!

我们可以看出来第一种方式写法固定,非常很适合通过写成过滤器的方式进行编码的统一转换。

publicclass EncodingFilter extends HttpFilter {

    publicvoid doFilter(HttpServletRequest request,  HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

       Stringcharset = this.getInitParameter("charset");

       if(charset == null ||charset.isEmpty()) {

           charset ="UTF-8";

       }

        request.setCharacterEncoding(charset);

       response.setContentType("text/html;charset=" + charset);

       chain.doFilter(request, response);

    }
}

2.Get方式请求乱码

   我们刚谈到Tomcat对Post请求的编码处理策略,并且从字里行间读出了Tomcat对Post和Get的编码策略有所不同,

那么Tomcat对Get请求的编码策略到底是如何不同的呢?答案就是Tomcat对于Get请求并不会考虑使用request.setCharacterEncoding方法设置的编码

言外之意就是我们无法通过request.setCharacterEncoding方式来改变编码,因为最终Tomcat会永远使用iso-8859-1进行编码(但是要注意一下,

respon还是可以通过调用response.setCharacterEncoding方式进行编码的设置的),既然是这样的话下面这个方法还是勉强可行的

a)

步骤一:response.setCharacterEncoding("UTF-8")

步骤二:String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");

通过这两步,可以看到我们的request的字符编码格式是默认的“iso-8859-1" 我们的response字符编码是自己设置的”utf-8"

显然两个是不相容的,因此我们在获取请求参数的时候才进行了一下字符集的转换即步骤二:

String name=new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");

     既然有a),那肯定还有b)咯?当然!而且方案b更加干净,利落,彻底。让我们一起看一下吧:

b)

修改Tomcat安装目录下conf子目录下的server.xml文件(解决get方式) 【注:记得先停掉服务器】

找到文件中类似这样的段落:
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

在里面加上这样一段:URIEncoding="UTF-8" 即变成下面这段
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8" />

最后重启Tomcat即可。


对于Get请求编码的统一处理也可以写成过滤器的形式,只不过稍微有些复杂。

EncodingRequest.java

public class EncodingRequest extends HttpServletRequestWrapper {
    private String charset;
    public EncodingRequest(HttpServletRequest request, String charset) {
        super(request);
        this.charset = charset;
    }

    public String getParameter(String name) {
        HttpServletRequest request = (HttpServletRequest) getRequest();
        
        String method = request.getMethod();
        if(method.equalsIgnoreCase("post")) {
            try {
                request.setCharacterEncoding(charset);
            } catch (UnsupportedEncodingException e) {}
        } else if(method.equalsIgnoreCase("get")) {
            String value = request.getParameter(name);
            try {
                value = new String(name.getBytes("ISO-8859-1"), charset);
            } catch (UnsupportedEncodingException e) {
            }
            return value;
        }
        return request.getParameter(name);
    }
}

EncodingFilter.java

public class EncodingFilter extends HttpFilter {
	public void doFilter(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		String charset = this.getInitParameter("charset");
		if(charset == null || charset.isEmpty()) {
			charset = "UTF-8";
		}
		response.setCharacterEncoding(charset);
		response.setContentType("text/html;charset=" + charset);
		EncodingRequest res = new EncodingRequest(request, charset);
		chain.doFilter(res, response);
	}
}

web.xml

  <filter>
  	<filter-name>EncodingFilter</filter-name>
  	<filter-class>cn.itcast.filter.EncodingFilter</filter-class>
  	<init-param>
  		<param-name>charset</param-name>
  		<param-value>UTF-8</param-value>
  	</init-param>
  </filter>
  <filter-mapping>
  	<filter-name>EncodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

【注】为了避免您的测试与我给的解决方案结果不符,请在项目编码格式为utf-8,jsp页面 pageEncoding="utf-8"的环境下测试。






  • 6
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值