对于GET方式,我们知道它的提交是将请求数据附加到URL后面作为参数,这样依赖乱码就会很容易出现,因为数据name和value很有可能就是传递的为非ASCII码。
当URL拼接后,浏览器对其进行encode,然后发送到服务器。具体规则见URL编码规则。
tomcat服务器在进行解码过程中URIEncoding就起到作用了。tomcat服务器会根据设置的URIEncoding来进行解码,如果没有设置则会使用默认的ISO-8859-1来解码。假如我们在页面将编码设置为UTF-8,而URIEncoding设置的不是或者没有设置,那么服务器进行解码时就会产生乱码。
这个时候我们一般可以通过new String(request.getParameter(“name”).getBytes(“iso-8859-1”),“utf-8”) 的形式来获取正确数据,或者通过更改服务器的编码方式: tomcat 设置中
服务器获取的数据都是ASCII范围内的请求头字符,其中请求URL里面带有参数数据,如果是中文或特殊字符,那么encode后的%XY(编码规则中的十六进制数)通过request.setCharacterEncoding()是不管用的。这时候我们就能发现出现乱码的根本原因就是客户端一般是通过用UTF-8或GBK等对数据进行encode的,到了服务器却用iso-8859-1方式decoder(解码)。
需要提前引入依赖
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>${servlet-api.version}version>
<scope>providedscope>
dependency>
"Tue Oct 01 2019 00:00:00 GMT+0800 (中国标准时间)"
然后使用方法,request.getParameter(“date”).getBytes(“iso-8859-1”),“utf-8”);
ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码
@RequestMapping(value = "/getMemberReportByDate",method = RequestMethod.GET)
public Result getMemberReportByDate(HttpServletRequest request) {
//因为需要处理中文((中国标准时间))的问题,可以使用request接收请求参数
String date = null;//request接收到的参数 先行定义
try {
//出现接收参数的异常情况 需要try/catch
date = new String(request.getParameter("date")//接收date参数
.getBytes("iso-8859-1")//设置接收到的浏览器参数的编码格式
,"utf-8");//设置接收完之后拿到的编码格式
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
<
Connector URIEncoding=“utf-8” connectionTimeout=“20000” port=“8080” protocol=“HTTP/1.1” redirectPort=“8443”/>
注: Connector 通常在%HOME_TOMCAT%/conf/servser.xml 文件内
需要修改的位置:
在每个页面的开头处,都会有一行:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
contentType="text/html;charset=UTF-8"的作用是指定对服务器响应进行重新编码的编码格式
pageEncoding="UTF-8" 是讲jsp编译成servlet时的编码 ;
对于POST方式,它采用的编码是由页面来决定的即ContentType(“text/html; charset=GBK”)。当通过点击页面的submit按钮来提交表单时,浏览器首先会根据ContentType的charset编码格式来对POST表单的参数进行编码然后提交给服务器,在服务器端同样也是用ContentType中设置的字符集来进行解码,这就是通过POST表单提交的参数一般而言都不会出现乱码问题。
当然这个字符集编码我们是可以自己设定的:request.setCharacterEncoding(charset)设置编码,然后通过request.getParameter获得正确的数据。
springMVC已经提供了轮子给我们使用,在web.xml添加post乱码filter
在web.xml中加入:
<filter>
<filter-name>CharacterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>CharacterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
以上可以解决post请求乱码问题。