简体   繁体   English

如何在Grails服务中访问会话Cookie?

[英]How can I access the Session Cookie in a Grails Service?

I need to access the session cookie (JSESSIONID) from within a Grails Service. 我需要从Grails服务中访问会话cookie(JSESSIONID)。 I know how to access it from a Servlet. 我知道如何从Servlet访问它。

Edit: I use the Grails JAXRS plugin http://grails.org/plugin/jaxrs to access a Resource from a REST request. 编辑:我使用Grails JAXRS插件http://grails.org/plugin/jaxrs从REST请求访问资源。

How can I access the Session Cookie JSESSIONID in a Grails Service? 如何在Grails服务中访问会话Cookie JSESSIONID?

If you need to have an access to the session in your Jersey REST Resource, you need to add a Request parameter to the Resource method, like: 如果需要访问Jersey REST资源中的会话,则需要在Resource方法中添加一个Request参数,例如:

@POST
public createData(@Context HttpServletRequest request) {
    def session = request.session
} 

I know you can use SecurityRequestHolder.request.session in services and src files (if you are using SpringSecurity). 我知道您可以在服务和src文件中使用SecurityRequestHolder.request.session (如果使用的是SpringSecurity)。 I'm not sure how well it works in a class. 我不确定它在课堂上的表现如何。 Honestly I would find another way. 老实说,我会找到另一种方式。

I've learned that when I think I need to access the session anywhere else but from a controller I have an architectural problem. 我了解到,当我认为需要从控制器以外的其他任何地方访问会话时,我会遇到体系结构问题。 At that point I stop and rethink what I'm doing and why I'm doing it. 到那时,我停下来思考一下自己在做什么,为什么要这么做。 Often Grails provides a better way to accomplish what I think I need to do with the session. 通常,Grails提供了一种更好的方式来完成我认为需要在会议上做的事情。 As @JoshuaMoore has pointed out, the best approach to using sessions is to pass the session values to a class instance or service within a controller. 正如@JoshuaMoore指出的那样,使用会话的最佳方法是将会话值传递给控制器​​内的类实例或服务。

This may not be the answer you want, but in the long run debugging, testing, and maintenance will be be easier. 这可能不是您想要的答案,但是从长远来看,调试,测试和维护将更加容易。 You will be glad you redesigned it. 您将很高兴重新设计它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM