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.
Thanks!
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.
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.
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();
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.
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);
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With