How to create, manage, associate a session in REST Jersey Web Application

34,201

Using JAX-RS for RESTful web services is fairly straightforward. Here are the basics. You usually define one or more service classes/interfaces that define your REST operations via JAX-RS annotations, like this one:

@Path("/user")
public class UserService {
    // ...
}

You can have your objects automagically injected in your methods via these annotations:

// Note: you could even inject this as a method parameter
@Context private HttpServletRequest request;

@POST
@Path("/authenticate")
public String authenticate(@FormParam("username") String username, 
        @FormParam("password") String password) {

    // Implementation of your authentication logic
    if (authenticate(username, password)) {
        request.getSession(true);
        // Set the session attributes as you wish
    }
}

HTTP Sessions are accessible from the HTTP Request object via getSession() and getSession(boolean) as usual. Other useful annotations are @RequestParam, @CookieParam or even @MatrixParam among many others.

For further info you may want to read the RESTEasy User Guide or the Jersey User Guide since both are excellent resources.

Share:
34,201
Harish
Author by

Harish

Updated on July 09, 2022

Comments

  • Harish
    Harish almost 2 years

    A HTML5 UI is connected to the backend (REST Jersey to business logic to Hibernate and DB). I need to create and maintain a session for each user login until the user logs out.

    Can you please guide me on what technologies/ APIs can be used. Does something need to be handled at the REST Client end also..

  • Harish
    Harish about 10 years
    Thanks for the answer. Suppose I have an user object mapping multiple modules. How do I bind the session to the User object.
  • xea
    xea about 10 years
    Can you explain how do you mean binding the session to an User object? What do you want to achieve?
  • Harish
    Harish about 10 years
    I mean to say that, I login from the HTML5 Web UI. Then I want to associate (bind) this User object to the session. This User object bound to the Session is to be used internally everywhere. That is to say, whenever I use an Uder object, the respective session id should be always tagged to it.
  • ihappyk
    ihappyk over 8 years
    is there any demo or tutorial for this? it would be more helpful if there is any tutorials