强化Servlet Request 对象方法

适用场景:
需要同时从request对象的getParameter(),getCookies(),getHeader()中取值:

方法一:装饰模式:

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

/**
* description
*
* @author qiaoyao
* @version 1.0,2010-5-27
*/
public class ApiRequestWrapper extends HttpServletRequestWrapper {

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

public String getParameter(String parameter) {
String getValue = null;
getValue = super.getParameter(parameter);
if (StringUtils.isNullOrEmpty(getValue)) {
getValue = super.getHeader(parameter);
if (StringUtils.isNullOrEmpty(getValue)) {
return null;
}
}
return getValue;
}
}

spring过滤器调用如下:

protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

super.doFilterInternal(new ApiRequestWrapper ( request), response, filterChain);
}


方法二:代理模式:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.servlet.http.HttpServletRequest;

/**
* description
*
* @author qiaoyao
* @version 1.0,2010-5-27
*/
public class RequestHandler implements InvocationHandler {
private HttpServletRequest realRequest;
private HttpServletRequest wrappedHttpServletRequest;

@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if ("getPrameter".equals(method.getName())) {
// doSomeThing
return "result";
}
return method.invoke(realRequest, args);
}

public HttpServletRequest bind() {
this.wrappedHttpServletRequest = (HttpServletRequest) Proxy
.newProxyInstance(this.getClass().getClassLoader(),
new Class[] { HttpServletRequest.class }, this);
return this.wrappedHttpServletRequest;
}

}

spring过滤器调用如下:

protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
RequestHandler requestHandler = new RequestHandler(request);
request = requestHandler.bind();
super.doFilterInternal(request, response, filterChain);
}



如果不需要所有参数都在多个范围取值: 可以通过参数名判断怎样取。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值