1、代理:MyHttpServletRequest 代理 HttpServletRequest
import org.springframework.beans.factory.annotation.Value;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyHttpServletRequest implements InvocationHandler {
HttpServletRequest req;
String contextPath;
private MyHttpServletRequest(HttpServletRequest req, String contextPath) {
this.req = req;
this.contextPath = contextPath;
}
public static HttpServletRequest proxy(HttpServletRequest req, String contextPath){
return (HttpServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), new Class[]{HttpServletRequest.class},
new MyHttpServletRequest(req, contextPath));
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 代理了原始类中的 getContextPath 方法,一旦调用这个方法,直接返回预先设置好的值
if (method.getName().equals("getContextPath")) {
return contextPath;
}
return method.invoke(req, args);
}
}
2、 使用
// 省略
public class MyUReportServlet extends UReportServlet {
public static final String URL = "/ureport";
private Map<String, ServletAction> actionMap = new HashMap<String, ServletAction>();
// 获取yml 配置文件中的值
@Value("${ureport.contextPath}")
private String path;
// ...省略
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// ...省略
// 代理使用
req = MyHttpServletRequest.proxy(req, path);
RequestHolder.setRequest(req);
try{
targetHandler.execute(req, resp);
}catch(Exception ex){
//省略
}finally{
RequestHolder.clean();
}
}
}