前端请求如果是中文的话,会变成乱码。Spring MVC怎么处理这种情况?或者spring 能在xml怎么配置然后解决这个乱码问题?
3 回答

饮歌长啸
TA贡献1951条经验 获得超3个赞
如果你的请求是post,中文应该不会有乱码。如果有,看看你的web.xml有没有配置
<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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
如果你的请求是get,参数有中文的,比如 ?name=张上,按照如下处理
前端encodeURIComponent(encodeURIComponent(url)),对url进行二次编码。
后端:拿到参数值,使用URLDecoder.decode(s, "UTF-8")解码一下。这样方式确实可行的,答主在实际项目总使用过。
举个例子吧:
前端:
<script type="text/javascript"> var url = "/xxx/param/test"; var name = "张上"; name = encodeURIComponent(name); name = encodeURIComponent(name);//二次编码 alert(name); url = url + "?name="+name; window.location.href = url; </script>
后端:
@Controller @RequestMapping(value="/param") public class ParamController extends BaseController<ParamEntity> { /** * @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请求有中文参数,可以指定容器使用何种编码规则来解码提交的参数,但是这种做法不建议使用,推荐使用二次编码吧。

aluckdog
TA贡献1847条经验 获得超7个赞
String name = request.equest.getParameter("name"); 获取到有可能乱码的值
if (name.equals(new String(name.getBytes("iso8859-1"),"iso8859-1"))) {
name = new String(name.getBytes("iso8859-1"), "utf-8"); 转码后的值
}
添加回答
举报
0/150
提交
取消