A标签中传递的中文参数到Servlet 后台request.getParameter()接收时出现中文乱码

时间:2022-07-04 07:28:38

package util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyHttpServletRequest extends HttpServletRequestWrapper {

protected Log log = LogFactory.getLog(getClass());
private static final String ENCODED = "UTF-8",DECODE="ISO8859-1";

public MyHttpServletRequest(HttpServletRequest request) {
super(request);
}

@Override
public String getQueryString() {
String queryString = super.getQueryString();
if(queryString != null){
try {
return new String(queryString.getBytes(DECODE),ENCODED);
} catch (UnsupportedEncodingException e) {
log.info(e.getMessage(),e);
}
}
return queryString;
}

@Override
public String getParameter(String name) {
String value = super.getParameter(name);
if (value != null) {
try {
return new String(value.getBytes(DECODE), ENCODED);
} catch (UnsupportedEncodingException e) {
log.info(e.getMessage(),e);
}
}
return value;
}

@SuppressWarnings("unchecked")
@Override
public Map getParameterMap() {
Map<String, String[]> values = super.getParameterMap();
Map<String, String[]> valuesMap = new HashMap<String, String[]>();
Set<String> names = values.keySet();
for (Iterator<String> iter = names.iterator(); iter.hasNext();) {
String name= iter.next();
String[] v = values.get(name);
if(v != null) {
String[] valuesCopy = new String[v.length];
for(int i = 0; i < v.length; i++) {
try {
valuesCopy[i] = new String(v[i].getBytes(DECODE), ENCODED);
} catch (UnsupportedEncodingException e) {
log.info(e.getMessage(),e);
}
}
valuesMap.put(name, valuesCopy);// 向新Map放入转码过的值
}
}
return valuesMap;// 返回是副本
}

@Override
public String[] getParameterValues(String name) {
String[] values = super.getParameterValues(name);
if(values != null) {
String[] valuesCopy = new String[values.length];//原数组是只读的,不能修改
for(int i = 0; i < values.length; i++) {
try {
valuesCopy[i] = new String(values[i].getBytes(DECODE), ENCODED);
} catch (UnsupportedEncodingException e) {
log.info(e.getMessage(),e);
}
}
return valuesCopy;
}
return values;
}
}

后台调用

request = new MyHttpServletRequest(request);

来自:http://bbs.csdn.net/topics/320081498  回答的二楼作者