public class RequestHandler implements InvocationHandler {
HttpServletRequest request;
public RequestHandler(HttpServletRequest request){
this.request=request;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
Object result=method.invoke(request, args);
if(method.getName().equals("getParameter")){
//根据项目的统一编码类型调整红色部分
if(result != null){
result =new String(((String)result).getBytes("ISO-8859-1"),"UTF-8");
}
}
return result;
}
}
在web.xml配置一个过滤器,关键代码如下
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
InvocationHandler handler = new RequestHandler((HttpServletRequest)arg0);
HttpServletRequest request=(HttpServletRequest)Proxy.newProxyInstance(arg0.getClass().getClassLoader(), arg0.getClass().getInterfaces(), handler);
arg2.doFilter(request, arg1);
}
通过以上程序的拦截处理,你在action中使用request.getParameter方法获取参数时就可以得到正确的解码值
本文介绍了一种通过代理模式实现的请求参数解码方法。利用Java反射机制创建HttpServletRequest接口的代理对象,对getParameter方法进行增强,将获取到的参数从ISO-8859-1编码转换为UTF-8编码,确保了前端传来的参数能够被正确解析。
2155

被折叠的 条评论
为什么被折叠?



