How to know when the request is forwarded in a RequestWrapper object

荒凉一梦 提交于 2019-11-28 08:59:55

问题


I am using a subclass of HttpServletRequestWrapper to do some translations on the request parameters, and I cache the translated values the first time they are requested. For example, the first time getQueryString() is called, I call super.getQueryString() and calculate the result that I want and keep it in a field, and then return it. Next times, I just use the cached result.

This method works like a charm unless there's some "forwarding". When a request is forwarded, Tomcat replaces the original request, so my cached query string is not changed, and the forwarded page gets the original query string, not the one that is forwarded to.

Overriding the setRequest() method to clear the cache doesn't help either, as if the request is wrapped twice, it calls the setRequest on the inner wrapper (which is not mine), and I have no way to know when it happens.

I'm looking for a way to be notified when there is a change in the wrapped request hierarchy, so that I can clear the cache, when there is a "forward".


回答1:


The original request URI is available as request attribute with the key RequestDispatcher.FORWARD_REQUEST_URI.

String originalRequestURI = request.getAttribute(RequestDispatcher.FORWARD_REQUEST_URI);

if (originalRequestURI != null) {
    // It was forwarded. Now get the query string as follows.
    String originalQueryString = request.getAttribute(RequestDispatcher.FORWARD_QUERY_STRING);
}

Note: in older Servlet API versions you need to hardcode the key instead.

String originalRequestURI = request.getAttribute("javax.servlet.forward.request_uri");
// ...


来源:https://stackoverflow.com/questions/5622461/how-to-know-when-the-request-is-forwarded-in-a-requestwrapper-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!