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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 18:11:12  来源:igfitidea点击:

Session variables in ServletRequest

javaservletsservlet-filters

提问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 doFiltermethod type from javax.Servlet.Filterimplementation is ServletRequest, whilst HttpServlet inherited classes, doPost method parameter requestis HttpServletRequest.

我需要通过过滤器访问会话变量。我什至不知道这是否可能。在实践中,问题在于实现的doFilter方法类型javax.Servlet.FilterServletRequest,而 HttpServlet 继承的类,doPost 方法参数request是 HttpServletRequest。

  1. Can I access session in ServletRequest in a Filter?
  2. Should I do that?
  3. What could you recommend me?
  1. 我可以在过滤器中访问 ServletRequest 中的会话吗?
  2. 我应该这样做吗?
  3. 你能推荐我什么?

Thanks!

谢谢!

回答by BalusC

Just cast the obtained ServletRequestto HttpServletRequest.

只需将获得的转换ServletRequestHttpServletRequest.

@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. ServletRequestallows 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、会话侦听器中查看、添加、删除和修改属性。这种技术非常有用,尤其适用于同一会话中不同组件之间的通信。