Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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..

like image 618
Harish Avatar asked Mar 13 '14 11:03

Harish


1 Answers

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.

like image 51
xea Avatar answered Oct 20 '22 23:10

xea