Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

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

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
// ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...