Jesse Barnum
Jesse Barnum

Reputation: 6856

How do I get the org.apache.catalina.connector.Request object in Tomcat?

I need to write a Servlet or Filter class that can get access to the org.apache.catalina.connector.Request object, which is wrapped in the RequestFacade object given to my servlet. Casting doesn't work, since RequestFacade is not a subclass of Request.

The reason I need this is because I am trying to call the setRequestedSessionId() method of Request, and this is apparently not part of the Http servlet spec. The reason I need to do this is because the session ID is being included in a URL under a different name than JSESSIONID. I can't change the URL or the name of the parameter, so I'm trying to associate the request with the correct session by extracting the session ID and call Request.setRequestedSessionId().

I have actually solved the problem using a Valve subclass, but I don't like using a Valve because as far as I can tell, I need to install my Valve subclass in the Tomcat/server/classes directory instead of packaging it with the rest of my webapp. If there was a portable way to do this across different Servlet containers, that would be great, but at the moment I'm resigned to making this Tomcat-specific.

Here is the working Valve code:

public class SessionSetter extends ValveBase {
public void invoke( Request request, Response response ) throws IOException, ServletException {
    String sessionId = request.getParameter( "whatever" );
    request.setRequestedSessionId( sessionId );
}

}

Is there some way to do the same thing in a Servlet or Filter? Or is there some way to package the Valve class in my application .war file?

Upvotes: 6

Views: 13414

Answers (2)

JRL
JRL

Reputation: 3401

Tomcat stores the real Request object in the protected variable request of RequestFacade, so you can get it (in a Servlet or JSP) with reflection:

import java.lang.reflect.Field;
import org.apache.catalina.connector.Request;

...

Field f = request.getClass().getDeclaredField("request");
f.setAccessible(true); // grant access to (protected) field
Request realRequest = (Request)f.get(request);

Upvotes: 6

matt
matt

Reputation: 79793

(this is my comment upgraded to an answer)

If you're using Tomcat 5.5 or 6 then this might be an alternative you could look at: http://tomcat.apache.org/tomcat-6.0-doc/config/systemprops.html#Sessions. You can change the names used for session id parameter using system properties. It's not available for Tomcat 7 though as far as I can tell (I think the servlet spec that tc7 implements is stricter about changing the name).

As for accessing the Tomcat internal request object from your webapp (servlet or filter), I don't think you'll be able to. I seem to recall reading somewhere that the RequestFacade class exists explicitly to prevent that, so that a webapp can't mess with the the Tomcat internals.

Upvotes: 5

Related Questions