RESTful风格的url包含中文的name,在用@PathVariable绑定参数时,发现乱码问题,打印name全是???
@RequestMapping(value = {"/category/id/{id}","/category/name/{name}"},method = RequestMethod.GET)
@ResponseBody
public Response<Category> findOne(@PathVariable(required = false) Integer id,@PathVariable(required = false) String name){
由于postman访问的url自动编码为
http://localhost:8080/MyPoetry/category/name/%E5%92%8F%E7%89%A9
因此可知是UTF-8编码后对每个字节前加入%形成url编码。
由于tomcat默认使用ISO-8859-1对接收的文本编码,因此要获得正确中文有两种解决方式:
- 自己转码
- 修改tomcat默认编码
自己转码
使用如下转码方式。先把name以ISO-8859-1再编码,还原成字节数组,再用UTF-8进行解码,即可获得正确中文。
String newName=new String(name.getBytes("ISO-8859-1"),"UTF-8");
修改tomcat | conf | server.xml
在server.xml的Connect中添加URIEncoding="utf-8",这样默认就是用utf-8解码了,参数绑定中文也可以正确显示:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
另,web.xml配置的filter只对post请求有效,因此对此问题不是解决之道:
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
参考:
https://blog.csdn.net/wangqing84411433/article/details/72814523