简体   繁体   中英

How can I get HttpServletRequest when in an HttpSessionListener?

How can I access request headers from a SessionListener?

I need to set a timeout on the current session when it is created. The timeout needs to vary based on a header in the HttpServletRequest. I already have a SessionListener (implements HttpSessionListener) that logs the creation and destruction of new sessions, and it seems to be the most logical place to set the timeout.

I've tried the following, but it always sets ctx to null.

FacesContext ctx = FacesContext.getCurrentInstance();

The HttpSessionListener does not have access to the request because it is invoked when no request has been made—to notify of session destruction.

So, a Filter or Servlet would be better places to examine the request and specify the session timeout.

FacesContext ctx = FacesContext.getCurrentInstance();

JSF contexts are per-request and thread-local. So, this method call will probably return null outside the JSF controller invocations (eg FacesServlet.service ) - so, other threads and any requests that don't pass through the Faces servlet mapping.

It is technically possible to set this time-out using a JSF mechanism - you could use a phase listener to check for a session after RENDER RESPONSE , though you would still have to cast to the servlet API to set the time-out. The advantage of phase listeners is that they can be registered either globally in faces-config ( see spec ) or for specific views . A global phase listener defined in a JAR with a META-INF/faces-config.xml can be dropped into multiple WARs, allowing you to easily reuse the functionality.

(You could also override how the session is provisioned to JSF , but the amount of work is excessive.)

For a one-off, erickson's suggestion of a Filter is really straightforward.

You can't ( see the API ). The request allows you to access the session, but not the other way around.

You might even have concurrent requests for the same session, so this is not feasible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM