java 在控制器中获取 Spring 启动/安全性的会话令牌
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34072443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get session token for Spring boot/security in controller
提问by Carlos Bribiescas
We are using spring boot with spring security to implement a querying interface. What I want to do is to only allow a fixed number of queries per user to run at a time. Queries may take a long time and users may send repeated requests faster than we can respond. I want the controller to only ever be calculating a subset request at a time and I'll have to implement some logic as to which requests to respond to.
我们使用 spring boot 和 spring security 来实现查询接口。我想要做的是只允许每个用户一次运行固定数量的查询。查询可能需要很长时间,并且用户发送重复请求的速度可能比我们的响应速度更快。我希望控制器一次只计算一个子集请求,并且我必须实现一些关于响应哪些请求的逻辑。
To do this, I need to know the session token for the given user. Is there an easy way to get this in the controller's methods?
为此,我需要知道给定用户的会话令牌。有没有一种简单的方法可以在控制器的方法中获得它?
回答by Sainik Kumar Singhal
If you want to get sessionId in controllers you can use
RequestContextHolder.currentRequestAttributes().getSessionId();
如果你想在控制器中获取 sessionId,你可以使用
RequestContextHolder.currentRequestAttributes().getSessionId();
回答by Borgy Manotoy
I find it easier to add the parameter 'HttpSession session' in your request mapping:
我发现在请求映射中添加参数“HttpSession session”更容易:
@GetMapping(value = "/hello")
public String home(HttpSession session) {
String sessionId = session.getId();
System.out.println("[session-id]: " + sessionId);
...
return "anyPage";
}