使用动态代理解决get参数中文乱码

本文介绍了一种通过代理模式实现的请求参数解码方法。利用Java反射机制创建HttpServletRequest接口的代理对象,对getParameter方法进行增强,将获取到的参数从ISO-8859-1编码转换为UTF-8编码,确保了前端传来的参数能够被正确解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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方法获取参数时就可以得到正确的解码值

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值