Domanda

I need to access the session cookie (JSESSIONID) from within a Grails Service. I know how to access it from a Servlet.

Edit: I use the Grails JAXRS plugin http://grails.org/plugin/jaxrs to access a Resource from a REST request.

How can I access the Session Cookie JSESSIONID in a Grails Service?

È stato utile?

Soluzione

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:

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

Altri suggerimenti

I know you can use SecurityRequestHolder.request.session in services and src files (if you are using 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. 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.

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top