如何在REST Jersey Web Application中创建,管理和关联会话

Har*_*ish 12 java rest session html5 web-applications

HTML5 UI连接到后端(REST Jersey到业务逻辑到Hibernate和DB).我需要为每个用户登录创建和维护一个会话,直到用户注销.

您能否指导我使用哪些技术/ API?是否需要在REST客户端处理某些事情..

xea*_*xea 21

将JAX-RS用于RESTful Web服务非常简单.以下是基础知识.您通常通过JAX-RS注释定义一个或多个定义REST操作的服务类/接口,如下所示:

@Path("/user")
public class UserService {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

您可以通过以下注释在方法中自动注入对象:

// 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
    }
}
Run Code Online (Sandbox Code Playgroud)

HTTP会话是从可访问的HTTP请求经由对象getSession()和getSession(boolean)像往常一样.其他有用的注释是@RequestParam,@CookieParam甚至@MatrixParam是许多其他注释.

有关详细信息,您可能需要阅读RESTEasy用户指南或Jersey用户指南,因为这两者都是极好的资源.