title: Grails get Session and Management in Service class
body: <p>I have a problem with Grails Session. I was thinking about having a Service Class for my session handling. So I created a class called "SessionService" (under grails-app/services/grails/). </p>
  
  <pre><code>class SessionService {
      static transactional = true
      GrailsWebRequest request = RequestContextHolder.currentRequestAttributes()
      GrailsHttpSession session = request.session
  
      def setTestvar(String value) {
          if (session != null)
              session.setAttribute("sTeststring", value)
      }
  
      def getTestvar() {
          if (session != null)
              session.getAttribute("sTeststring")
      }
  }
  </code></pre>
  
  <p>The Problem is now, that I get a Nullpointer-Exception: "<em>Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession.ToString()</em>".</p>
  
  <p>Usage of my Service Class e.g. in a Controller:</p>
  
  <pre><code>class SampleController {
  
      SessionService sessionService
  
      def selectAnything = {
  
          sessionService.setTestvar("test-value")
          render(view: "testview")
      }
  }
  </code></pre>
  
  <p>What am I'm doing wrong here? Is it the right way? Or do I have to set "session = request.session" in every method?</p>
  
  <p>Hope to get help from you. </p>
  
  <p>Thank you very much in advance.</p>
  
  <p>Cheers,</p>
  
  <p>Marco</p>