Spring @RequestParam乱码问题
在网上找了很多资料才找到解决的方法,通过URL传递命名参数,后台接收的却是乱码解决方法如下:
方法一:将接收的参数重新编码
@RequestMapping(value="/handle") public String handle81(@RequestParam("userName") String userName){ userName=new String(userName.getBytes("ISO-8859-1"), "UTF-8") modelMap.put("userName", userName); return "/user/showUser"; }
方法二:在web.xml里面配置
<!-- 字符过滤器 --> <filter> <filter-name>encodingFilter</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>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
方法三:修改tomcat的server.xml(在conf文件下),找到下面代码添加URIEncoding编码。
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8"/>
最终我的解决方法时方法二和方法三同时用,没用方法一才解决@RequestParam乱码问题。
另外表单提交时出现乱码解决方法如下:
一、首先将Eclipse文件编码是UTF-8:Windows——Preference——General——Workspace——Text file encoding改为UTF-8.
二、设置页面编码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%> <% request.setCharacterEncoding("utf-8"); %>
三、将form表单提交方式变为post方式,即添加method="post"
四、在action类中,添加3句话
request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("UTF-8");
五、将接收到的数据转码
String name = new String(request.getParameter(“name”).getBytes("ISO-8859-1"),"utf-8");
六、post提交方式下可进行URL编码:
String info=java.net.URLEncoder.encode("你好吗.jpg","utf-8");
http://localhost:8080/webTest/index.jsp?name=<%=URLEncoder.encode("张三","UTF-8")%>
String myname=URLDecoder.decode(name,"UTF-8");
参考文献:
解决JSP中文乱码问题:http://www.cnblogs.com/chengkai/articles/2171848.html