java – I want to access a session from a non-Bean class on a web application using JAX-RS

Question: Question:

I am making a web application using JAX-RS.
I want to be able to access a session from a class that meets all of the following conditions, but I don't know how.

  1. Any self-made class that is not a bean
  2. Unable to get object to access session by argument (eg HttpServletRequest)

For ASP.NET, you can always access your session (and other HTTP-related objects) via a static property called HttpContext.Current .
Is there a similar method in Java (JAX-RS)?

There are many things I'm trying to do, such as "logging the logged-in user's ID at the entrance to the data access layer (inside the common infrastructure hidden from each programmer)".
The information of the logged-in user is retained in the session, but what is called this "common infrastructure" is not connected to the JAX-RS Web service as a relationship between classes at all .
In other words, although the classes exist on the same application, there is no connection between classes in that sense.
So it would be nice to have an API like a global variable, like HttpContext.Current .

It is possible to use DI with @SessionScoped , but I don't think it can be incorporated into a hidden common infrastructure.

Alternatively, the idea of ​​extracting information from a session (is there a better one?) With the Web service RequestFilter and copying it to a static field of a common class somewhere came to my mind for a moment, but it is not thread-safe at all, so it is NG. did.
It may be good to use ThreadLocal, but I'm worried whether it can be implemented safely with a little lack of knowledge and experience.
If there is no other means, it is necessary to investigate and verify various things before introducing it …

Is there any good way?

The environment is as follows, but if, for example, "Spring Framework is acceptable", we will consider introducing it.
Application server: WildFly
Framework used: JavaEE7, Jersey (JAX-RS)

Answer: Answer:

It is possible to inject an HttpServletRequest object using the @Context annotation.

You can pass an HttpServletRequest object as a resource method parameter as follows:

public class ContactService {
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public Contact find(@Context HttpServletRequest request, @PathParam("id") Long id) {
        return repository.find(id);

All you have to do now is call the HttpServletRequest # getSession () method inside this method to get the HttpSession object.

Scroll to Top