Grails在Service类中获得Session和Management [英] Grails get Session and Management in Service class

查看:82
本文介绍了Grails在Service类中获得Session和Management的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Grails Session上遇到问题.我当时正在考虑为会话处理设置一个服务类.因此,我创建了一个名为"SessionService"的类(位于grails-app/services/grails/下).

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/).

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")
    }
}

现在的问题是,我得到一个Nullpointer-Exception:"方法抛出了'java.lang.NullPointerException'异常.无法评估org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession.ToString ()".

The Problem is now, that I get a Nullpointer-Exception: "Method threw 'java.lang.NullPointerException' exception. Cannot evaluate org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession.ToString()".

我的服务等级的使用,例如在控制器中:

Usage of my Service Class e.g. in a Controller:

class SampleController {

    SessionService sessionService

    def selectAnything = {

        sessionService.setTestvar("test-value")
        render(view: "testview")
    }
}

我在这里做错了什么?这是正确的方法吗?还是我必须在每种方法中都设置"session = request.session"?

What am I'm doing wrong here? Is it the right way? Or do I have to set "session = request.session" in every method?

希望从您那里获得帮助.

Hope to get help from you.

非常感谢您.

干杯

马可

推荐答案

RequestContextHolder来自何处?在grails 3.3.8中(至少在插件中)不可见

where does RequestContextHolder come from? Its not visible in grails 3.3.8 (in plugin at least)

这篇关于Grails在Service类中获得Session和Management的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆