在網上找了很多資料才找到解決的方法,通過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