Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...