为了账号安全,请及时绑定邮箱和手机立即绑定

Spring MVC如何处理从前端传过来的参数变成乱码?

Spring MVC如何处理从前端传过来的参数变成乱码?

摇曳的蔷薇 2019-03-01 10:30:41
前端请求如果是中文的话,会变成乱码。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请求有中文参数,可以指定容器使用何种编码规则来解码提交的参数,但是这种做法不建议使用,推荐使用二次编码吧。

查看完整回答
反对 回复 2019-03-01
?
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");   转码后的值

}

查看完整回答
反对 回复 2019-03-01
  • 3 回答
  • 0 关注
  • 993 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号