今天在写练习的时候,传值乱码让我很头疼。今天就做个笔记,记录乱码的解决办法。
1.在jsp的头部配置
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="UTF-8"%>
2.在action层
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");3.jqueryeasyui传值时出现乱码,就要解碼
如我傳的值是userName
$("#loains").datagrid( {
width :myWidth, height : myHeight, 'login.do?action=UserList&userName='+encodeURIComponent(userName)';action取值:
String userName= urlDecoder.decode(request.getParameter("userName"), "UTF-8");
或者:String userName= new String(request.getParameter("userName").getBytes("ISO8859-1"), "UTF-8");
4.配置过滤器
web.xml里面
<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><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() {
}}