Alex
Alex

Reputation: 3413

Session variables in ServletRequest

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.

  1. Can I access session in ServletRequest in a Filter?
  2. Should I do that?
  3. What could you recommend me?

Thanks!

Upvotes: 16

Views: 21853

Answers (2)

BalusC
BalusC

Reputation: 1108722

Just cast the obtained ServletRequest to 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:

Upvotes: 29

AlexR
AlexR

Reputation: 115328

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.

Upvotes: 0

Related Questions