gpt4 book ai didi

session - Grails Session Scoped bean 数据状态未正确更新

转载 作者:行者123 更新时间:2023-12-02 15:00:36 26 4
gpt4 key购买 nike

我有一个 Grails Web 应用程序,我需要在其中为每个用户 session 保留一些数据。我不想使用 HTTP session ,而是创建一个 session 范围的 bean。下面给出的是我的 Session Scoped bean 定义 -

class SessionContainer implements Serializable {

static scope = 'session' (if I am using resources.groovy)

Boolean abc
Boolean def
Boolean xyz
SomeOtherChildBean someBean
}

这就是我的 Controller 的样子:
class MyController {

def myService

def showMyProblem() {
myService.updateSession()
myService.printSessionData()
}
}

这就是我的服务类的样子:
class MyService {

SessionContainer sessionContainer

def updateSession() {
sessionContainer.abc = true
sessionContainer.def = true
sessionContainer.xyz = true
}

def printSessionData() {
def abc = sessionContainer.abc
def def = sessionContainer.def
def xyz = sessionContainer.xyz
println abc // This is always false (which is incorrect)
println def // This is true (which is correct)
println xyz // This is true (which is correct)
}
}

我使用 2 种方式注入(inject) session bean -
在 resources.groovy -

sessionContainerBean(SessionContainer) { bean ->
bean.scope = 'session'
}
sessionContainer(org.springframework.aop.scope.ScopedProxyFactoryBean) {
targetBeanName = 'sessionContainerBean'
proxyTargetClass = true
}

或在 resources.xml 中
<bean id="sessionContainer" name="sessionContainer" class="com.dataobjects.SessionContainer" scope="session">
<aop:scoped-proxy/>
</bean>

我尝试了 2 种不同的方法来注入(inject) session 作用域 bean 来解决我的问题,尽管上面提到的任何一种方式都导致了相同的 session 作用域 bean。

正如您从我的代码中看到的那样,我正在从我的 Session 范围 bean 中打印 bool 变量,并且 abc 值始终为 false(这是不正确的)。打印其他 bool 变量时,它会呈现正确的值。

我对 session bean 为何对少数变量有正确的状态,但没有更新某些变量的状态感到害怕。

我什至尝试通过使用 (static scope = 'true') 来使用 Session Scoped 服务,但出现以下错误 - 我最终创建了一个代理范围服务,如此处所述 Grails session-scoped service - not working ,但行为与 Session Scoped bean 相同。
Error creating bean with name 'myService': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread

最佳答案

如果 MyService是在 grails-app/services/ 下定义的真正 Grails 服务那么你不需要在 resources.groovy 中定义 bean或在 resources.xml .您可以将范围表示为静态属性:

// grails-app/services/demo/MyService.groovy
package demo

class MyService {
static scope = 'session'

// ...
}

这有帮助吗?

关于session - Grails Session Scoped bean 数据状态未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24788446/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com