如果你的请求是post,中文应该不会有乱码。如果有,看看你的web.xml有没有配置
CharacterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
CharacterEncodingFilter
/*
如果你的请求是get,参数有中文的,比如 ?name=张上,按照如下处理
前端encodeURIComponent(encodeURIComponent(url)),对url进行二次编码。
后端:拿到参数值,使用URLDecoder.decode(s, "UTF-8")解码一下。这样方式确实可行的,答主在实际项目总使用过。
举个例子吧:
前端:
var url = "/xxx/param/test";
var name = "张上";
name = encodeURIComponent(name);
name = encodeURIComponent(name);//二次编码
alert(name);
url = url + "?name="+name;
window.location.href = url;
后端:
@Controller
@RequestMapping(value="/param")
public class ParamController extends BaseController {
/**
* @throws UnsupportedEncodingException
*
*/
@RequestMapping(value="/test",method=RequestMethod.GET)
public String test(@RequestParam("name") String name) throws UnsupportedEncodingException{
name = URLDecoder.decode(name, "UTF-8");//实测,可以正确的得到中文。
System.out.println(name);
return "index";
}
}
注意:get请求有中文参数,可以指定容器使用何种编码规则来解码提交的参数,但是这种做法不建议使用,推荐使用二次编码吧。
为什么需要二次编码?可以看如下博文:
地址