java ServletRequest 中的会话变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15009784/
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
Session variables in ServletRequest
提问by Alex
I need to access session variables through a filter. I don't even know if it is possible. In practice, the problem is that the doFilter
method type from javax.Servlet.Filter
implementation is ServletRequest
, whilst HttpServlet inherited classes, doPost method parameter request
is HttpServletRequest.
我需要通过过滤器访问会话变量。我什至不知道这是否可能。在实践中,问题在于实现的doFilter
方法类型javax.Servlet.Filter
是ServletRequest
,而 HttpServlet 继承的类,doPost 方法参数request
是 HttpServletRequest。
- Can I access session in ServletRequest in a Filter?
- Should I do that?
- What could you recommend me?
- 我可以在过滤器中访问 ServletRequest 中的会话吗?
- 我应该这样做吗?
- 你能推荐我什么?
Thanks!
谢谢!
回答by BalusC
Just cast the obtained ServletRequest
to HttpServletRequest
.
只需将获得的转换ServletRequest
为HttpServletRequest
.
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpSession session = request.getSession(false);
// ...
}
See also:
也可以看看:
回答by AlexR
Sure you can. ServletRequest
allows you access to session that contains attributes. You can review, add, remove and modify attributes whenever you want either in filter, servlet, jsp, session listener. This technique is very useful and especially attended for communication between different components within the same session.
你当然可以。ServletRequest
允许您访问包含属性的会话。您可以随时在过滤器、servlet、jsp、会话侦听器中查看、添加、删除和修改属性。这种技术非常有用,尤其适用于同一会话中不同组件之间的通信。