0

I have a web application written in JSF2 that uses Spring. I need to create a bean that is a wrapper of JSF HTTP session and use it internally. It seems logical to me to inject the HttpSession object into that bean's definition and to scope the bean to the session. However I could not find a way to define the injection in the context.xml file. Is it possible to do this, could it backfire and is there a better way? All I want is to have the current session inside that bean. If there is a static method to get the session (similar to HttpContext.Current.Session in ASP.NET), it will also be of good use. Thanks in advance.

Ivaylo Slavov
  • 8,839
  • 12
  • 65
  • 108

2 Answers2

1

I'm not sure about the Spring part (I don't use it, I use just the standard Java EE 6 API), but you can get the HttpSession statically in JSF context by ExternalContext#getSession() as follows:

HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);

You could do that in the bean's (post)constructor.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks, I guess this is the JSF alternative for the ASP.NET's HttpContext.Current.Session. It will work fine for me, even better - I will not need to scope my bean to the session, since it will always get it statically, so that I will have a single instance of my bean. Of course, I must not keep any state outside the session that is related to the current session's content, so that the bean remains somewhat stateless. – Ivaylo Slavov Oct 10 '11 at 15:11
  • You're welcome. I must admit that this requirement doesn't make much sense to me. I think a simple session scoped managed bean is more than sufficient. Store the session data in there instead of trying to wrap the `HttpSession`. – BalusC Oct 10 '11 at 15:14
  • I know, but my idea is to compel to a certain interface; in other words the bean implements an interface and will be exposed by this interface, which does not know and must not depend on web technologies and HTTP session. – Ivaylo Slavov Oct 10 '11 at 15:34
1

If you are in a Spring-managed handler method, you can simply add the HttpSession object to your handler's method signature and Spring will automatically inject it, as follows:

@RequestMapping("/myhandler.do")
public String myHandler(HttpSession session) {
    ...foo...
}
atrain
  • 9,139
  • 1
  • 36
  • 40
  • Thanks, but my purpose is to wrap certain functionality with the session without explicitly working with it - in my case I am writing an authentication bean that will take username and password to load a user and put it in the session, and to expose that use if it is logged in, without exposing the actual session object. I think the static access that is proposed below will be more applicable in my case. Still, it was useful to learn that I can pass the session with '@RequestMapping' annotation. – Ivaylo Slavov Oct 10 '11 at 14:44