适用场景:
需要同时从request对象的getParameter(),getCookies(),getHeader()中取值:
方法一:装饰模式:
方法二:代理模式:
如果不需要所有参数都在多个范围取值: 可以通过参数名判断怎样取。
需要同时从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);
}
如果不需要所有参数都在多个范围取值: 可以通过参数名判断怎样取。