java springMVC前台和后台间传数据乱码

来源:互联网 发布:文件定时拷贝软件 编辑:程序博客网 时间:2024/05/05 18:42

在java web项目中,我的前台用的是velocity,而不是jsp。发现前台和后台间传输数据(post和get)会出现中文乱码的情况。

解决方法如下:

如果后台要接收前台传送过来的数据(通过HttpServletRequest),则需接入以下代码,对接收的参数进行解码:

request.setCharacterEncoding("UTF-8");String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");String stuId = new String(request.getParameter("stuId").getBytes("ISO-8859-1"), "UTF-8"); 

其中name和stuId是后台要接收的数据。


同时如果后台要进行重定向,并且有参数传递;如果参数中有中文,则要对参数编码(假设name为参数):

name = new String(java.net.URLEncoder.encode(name,"UTF-8"));
同时接收方也要用刚才的方法对参数进行解码。

这样,综合起来的代码就是:

@RequestMapping("/login.html")public ModelAndView Login(ModelAndView modelAndView, HttpServletRequest request) throws UnsupportedEncodingException {request.setCharacterEncoding("UTF-8");String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");String stuId = new String(request.getParameter("stuId").getBytes("ISO-8859-1"), "UTF-8"); System.out.println("我的名字" + name);name = new String(java.net.URLEncoder.encode(name,"UTF-8"));modelAndView.setViewName("redirect:/student/success.html?name=" +name  +  "&stuId=" + stuId);return modelAndView;}

同时,如果用的服务器是tomcat,则必须在tomcat目录下的server.xml中的Connector中加入以下两个属性:

URIEncoding="UTF-8" useBodyEncodingForURI="true"


修改后为:

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8" useBodyEncodingForURI="true"/><Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8" useBodyEncodingForURI="true"/>



0 0
原创粉丝点击