1

In doFilter method, we use the code below to access to session :

HttpServletRequest request = (HttpServletRequest) servletRequest;

But, "HttpServletRequest" extends "servletRequest", so theoretically we should not be able to put father in son.

  • except when you know that this `ServletRequest` is actually a `HttpServletRequest` – jmj Feb 17 '15 at 19:30
  • You can't extend an object (or a variable).. look at the *compile-time static type* of the expression (of "servletRequest") and you'll see that it does *not* extend HttpServletRequest. This is why Java needs the explicit cast: it could be [based on the static types] another non-HTTP ServletRequest. – user2864740 Feb 17 '15 at 19:31
  • Consider this: `Animal animal = NewDogOrCat(); Dog dog = (Dog)animal` - the cast to Dog is not guaranteed. Likewise, same for this: `ServletRequest servletRequest = NewHttpRequestOrNotHttpRequest(); HttpServletRequest request = (HttpServletRequest)serveltRequest` (Just because it's "always" a HttpServletRequest does *not* affect the static type system or request type validation.) – user2864740 Feb 17 '15 at 19:35
  • sorry, your answer is not clear, could you please break it down for me? –  Feb 17 '15 at 19:37
  • The cast is required because Java only has static type information available during the compilation phase. See the linked question - "downcasting" is about *getting a more specific*-typed expression, as a HttpServletRequest (or a Dog) is *more specific* than a ServletRequest (or an Animal). – user2864740 Feb 17 '15 at 19:37

0 Answers0