在 Grails 的命令对象中获取会话
如何从命令对象中获取会话?
我尝试过:
import org.springframework.security.context.SecurityContextHolder as SCH
class MyCommand {
def session = RCH.currentRequestAttributes().getSession()
}
这会抛出
java.lang.IllegalStateException:未找到线程绑定请求:您是指实际 Web 请求之外的请求属性,还是在原始接收线程之外处理请求?如果您实际上在 Web 请求中进行操作并且仍然收到此消息,则您的代码可能在 DispatcherServlet/DispatcherPortlet 之外运行:在这种情况下,请使用 RequestContextListener 或 RequestContextFilter 公开当前请求。
How can I get the session from within a command object?
I have tried:
import org.springframework.security.context.SecurityContextHolder as SCH
class MyCommand {
def session = RCH.currentRequestAttributes().getSession()
}
This throws
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? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您导入了 Spring Security 的 SecurityContextHolder,但您使用的是标准 Grails 请求持有者。如果您使用 Acegi 插件,那么有一个过滤器可以在 org.codehaus.groovy.grails.plugins.springsecurity.SecurityRequestHolder 管理的 ThreadLocal 中设置请求,因此这将起作用:
请注意,它必须位于方法中由于command类会在启动时实例化一次或多次进行初始化,所以只需要在HTTP请求执行过程中访问session和request
You have an import for Spring Security's SecurityContextHolder but you're using the standard Grails request holder. If you're using the Acegi plugin, then there's a filter that sets the request in a ThreadLocal managed by org.codehaus.groovy.grails.plugins.springsecurity.SecurityRequestHolder, so this will work:
Note that is has to be in a method since the command class will be instantiated one or more times at startup for initialization, so you need to access the session and request only during the execution of an HTTP request
还可以使用 RequestContextHolder 访问会话(以避免 Spring Security 依赖/导入):
It's also possible to access the session using RequestContextHolder (to avoid the Spring Security dependency/import):
另一种方式:
在我的应用程序中
SecurityRequestHolder.request
以某种方式返回 null,但上面的方式有效。Another way:
In my app
SecurityRequestHolder.request
returns null somehow, but the way above works.