Java 如何在 REST Jersey Web 应用程序中创建、管理、关联会话
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22377903/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create, manage, associate a session in REST Jersey Web Application
提问by Harish
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.
HTML5 UI 连接到后端(REST Jersey 到 Hibernate 和 DB 的业务逻辑)。我需要为每个用户登录创建和维护一个会话,直到用户注销。
Can you please guide me on what technologies/ APIs can be used. Does something need to be handled at the REST Client end also..
你能指导我使用哪些技术/API。是否还需要在 REST 客户端处理某些事情..
回答by xea
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:
将 JAX-RS 用于 RESTful Web 服务非常简单。以下是基础知识。您通常通过JAX-RS 注释定义一个或多个服务类/接口来定义您的 REST 操作,如下所示:
@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 Sessionsare accessible from the HTTP Requestobject via getSession()
and getSession(boolean)
as usual. Other useful annotations are @RequestParam
, @CookieParam
or even @MatrixParam
among many others.
HTTP会话是从可访问的HTTP请求经由对象getSession()
和getSession(boolean)
像往常一样。其他有用的注释是@RequestParam
,@CookieParam
甚至@MatrixParam
还有许多其他注释。
For further info you may want to read the RESTEasy User Guideor the Jersey User Guidesince both are excellent resources.
有关更多信息,您可能需要阅读RESTEasy 用户指南或Jersey 用户指南,因为两者都是极好的资源。