今天在寫練習的時候,傳值亂碼讓我很頭疼。今天就作個筆記,記錄亂碼的解決辦法。html
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%>java
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");jquery
如我傳的值是userNameweb
$("#loains").datagrid( {
width :myWidth,
height : myHeight,
'login.do?action=UserList&userName='+encodeURIComponent(userName)';apache
action取值:app
String userName= urlDecoder.decode(request.getParameter("userName"), "UTF-8");jsp
或者:String userName= new String(request.getParameter("userName").getBytes("ISO8859-1"), "UTF-8");ui
web.xml裏面this
<filter>
<filter-name>encodeFilter</filter-name>
<filter-class>com.wow.util.EncodeFilter</filter-class>
<init-param>
<param-name>encode</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>url
<filter-mapping>
<filter-name>encodeFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
在com.wow.util.EncodeFilter類裏面
package com.wow.util;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
public class EncodeFilter implements Filter {
private String encode = "UTF-8";
public void init(FilterConfig config) {
this.encode = config.getInitParameter("encode");
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) {
try {
request.setCharacterEncoding(this.encode);
response.setCharacterEncoding(this.encode);
chain.doFilter(request, response);
} catch (Exception e) {
if (!(e instanceof java.net.SocketException)) {
if (request instanceof HttpServletRequest) {
Logger.getLogger(this.getClass()).error(
"error request uri:"
+ ((HttpServletRequest) request)
.getRequestURI());
}
Logger.getLogger(this.getClass()).error(e);
}
e.printStackTrace();
}
}
public void destroy() {
}
}