Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 370
Alex Avatar asked Feb 21 '13 18:02

Alex


People also ask

What are session variable in servlets?

A servlet can use the session of user to create some variables. These variables occupy server memory. Users cannot deny creation of session variables. One servlet can create session variables and other servlets can fetch or change the value of session variables.

How can you getSession information in a servlet?

The HttpServletRequest interface provides two methods to get the object of HttpSession: public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one.

How do you create a session using HttpSession object?

To create a new session or gain access to an existing session, use the HttpServletRequest method getSession(), as shown in the following example: HttpSession mySession = request. getSession();

What is the correct way to add attribute in the HTTP session?

Use the getAttribute(String name) or getAttributesNames() methods of the HttpSession object to retrieve attributes that are associated with it. If you want to set a new attribute, or remove an existing one, use setAttribute() and removeAttribute() , respectively.


1 Answers

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:

  • Our servlet-filters wiki page
like image 133
BalusC Avatar answered Sep 20 '22 18:09

BalusC