【问题标题】:Restful : How to get access to Httpsession inside the Service class?Restful:如何访问 Service 类中的 Httpsession?
【发布时间】:2012-08-03 14:05:22
【问题描述】:

我正在使用 Jersey restful web services 。 这是我下面的代码

@Path(/test)
public class testService  {
    @POST
    public String getData(Postdata postdata) {

    }

}

我的问题是,在这个类中是否可以访问 httpSession 对象??

【问题讨论】:

    标签: java rest jersey


    【解决方案1】:

    试试:

    @POST
    public String getData(Postdata postdata, @Context HttpServletRequest request) {
      HttpSession session = request.getSession();
    }
    

    【讨论】:

    【解决方案2】:

    如果你的服务不是单例的,你可以使用:

    @Path("/test")
    public class TestResource  {
    
        @Context
        private HttpServletRequest request;
    
        @POST
        public String getData(Postdata postdata) {
            HttpSession session = request.getSession();
        }
    
    }
    

    【讨论】:

    • 是否也可以在运行时检索 HttpServletRequest?通过 ServiceLocator 还是其他方式?
    • 嗨,@zwanz0r 在运行时?我不懂你说什么。你想说用 JAX-RS 吗?
    • @U2Answer 你可以试试ThreadLocal,见stackoverflow.com/a/5473312/870248
    • @U2Answer 嗯……不。见https://github.com/jersey/jersey/search?utf8=✓&q=ThreadLocal&type=Code
    • 设计,是的!它必须是无状态的。 但是,由于 JAX-RS 是基于 servlet 的,因此您可以使用 request 对象访问会话对象,就像普通的 servlet 一样。您可以执行this 之类的操作。太棒了!
    猜你喜欢
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多