On Sat, 17 Aug 2002, tek1 wrote:
> Date: Sat, 17 Aug 2002 15:03:28 +0900
> From: tek1 <[EMAIL PROTECTED]>
> Reply-To: Tomcat Users List <[EMAIL PROTECTED]>
> To: [EMAIL PROTECTED]
> Subject: retrieving HttpSession in Filter?
>
> hello.
>
> in a filter, is it possible to cast the ServletRequest to a
> HttpServletRequest
Yes.
and retrieve the HttpSession object, *if* the session
> has never been created before?
The rules for a filter are the same as the rules for a servlet -- you have
to create a session if you want one, before the response is submitted.
>
> i tried the following:
>
> 1 public void doFilter(ServletRequest req, ServletResponse res,
> FilterChain chain) throws IOException, ServletException {
> 2
> 3 HttpServletRequest hreq = (HttpServletRequest)req;
> 4 chain.doFilter(hreq,res);
> 5
> 6 // if it's the client's first access, the below returns false
> 7 if( hreq.isRequestedSessionIdValid() ) {
This is not the right test for a newly created session, because there
*was* no requested session. Try something like this instead:
HttpSession session = request.getSession(false);
if (session == null) {
... no session exists ...
} else if (session.isNew()) {
... this is a newly created session ...
} else {
... this is an existing session ...
}
> 8 // ...not processed; go to else clause below...
> 9 } else {
> 10 String sid = hreq.getSession().getId();
> 11 }
> 12 }
>
> the request hangs on line 10 (which is when a client is accessing for the
> *first time*).
>
> however, if the servlet (that receives the request in "doFilter()") calls
> request.getSession(), then the above filter is able to retrieve the
> HttpSession without a problem.
>
> is a filter prevented from creating a *new* HttpSession object?
>
No, you can create one the same way a servlet can - by calling
request.getSession() or request.getSession(true). However, you must call
this before the response is committed, so calling it after
chain.doFilter() returns is not going to work.
> most likely, i'll be calling the request.getSession() in my servlet, so it
> shouldn't be a problem, but i discovered this before placing the
> request.getSession() code in my servlet.
>
> thank you.
>
Craig
>
> tomcat: 4.0.4
> os: windows2000
> jdk: 1.3.1_04
>
>
> --
> To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
> For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>
>
>
--
To unsubscribe, e-mail: <mailto:[EMAIL PROTECTED]>
For additional commands, e-mail: <mailto:[EMAIL PROTECTED]>