java修改请求参数的值

异常

java.lang.IllegalStateException: No modifications are allowed to a locked ParameterMap。网上查了一些资料,解决方案是使用Wrapper,重写HttpServletRequestWrapper,如下:

package com.gdcn.bpaf.security.yale;

import java.util.Enumeration;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

@SuppressWarnings("unchecked")
public class ParameterRequestWrapper extends HttpServletRequestWrapper {

	private Map params;

	public ParameterRequestWrapper(HttpServletRequest request, Map newParams) {
		super(request);
		this.params = newParams;
	}

	public Map getParameterMap() {
		return params;
	}

	public Enumeration getParameterNames() {
		Vector l = new Vector(params.keySet());
		return l.elements();
	}

	public String[] getParameterValues(String name) {
		Object v = params.get(name);
		if (v == null) {
			return null;
		} else if (v instanceof String[]) {
			return (String[]) v;
		} else if (v instanceof String) {
			return new String[] { (String) v };
		} else {
			return new String[] { v.toString() };
		}
	}

	public String getParameter(String name) {
		Object v = params.get(name);
		if (v == null) {
			return null;
		} else if (v instanceof String[]) {
			String[] strArr = (String[]) v;
			if (strArr.length > 0) {
				return strArr[0];
			} else {
				return null;
			}
		} else if (v instanceof String) {
			return (String) v;
		} else {
			return v.toString();
		}
	}
}

 2.使用

//然后在另一个地方使用时,按下面这样用,假如我要修改username的值

HashMap m=new HashMap(request.getParameterMap());  
/*
关键部分,如果不转换成String数组,如果在下面这样是有时:
eg:
HttpSession session = request.getSession();
Map map = request.getParameterMap();
Set keySet = map.keySet();
for (Iterator iterator = keySet.iterator(); iterator.hasNext();)
{
String key = (String)iterator.next();
String values[] = (String[])map.get(key);  //这个地方就会报错,因为username一个String不能转换成String数组
if (values.length == 1)
	session.setAttribute(key, values[0]);
else
	session.setAttribute(key, values);
}
异常
就会出现java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.String;
*/
//m.put("username", newusername);  //这样会报错
m.put("username", new String[]{newusername});  //这就是对的
HttpServletRequest req = (HttpServletRequest) request; 
com.gdcn.bpaf.security.yale.ParameterRequestWrapper wrapRequest=new com.gdcn.bpaf.security.yale.ParameterRequestWrapper(req,m);   
request=wrapRequest; //这是rquest就和本身的request一样了

 

你可能感兴趣的:(java修改请求参数的值)