1

I found this answer very usefull but I can't figure out why it works.
In accordance with API pageContext getRequest() method returns ServletRequest and it doesn't contain getUserPrincipal() method. So why do things like this work

<c:if test="${not empty pageContext.request.userPrincipal}">

    <c:if test="${pageContext.request.isUserInRole('ADMIN')}">

        User ${pageContext.request.userPrincipal.name} in ADMIN Group

    </c:if>

</c:if>

Is there implicit type conversion or what?

Community
  • 1
  • 1
Vitalii Vitrenko
  • 9,763
  • 4
  • 43
  • 62

1 Answers1

3

The servlet API has been designed, a long time ago, in order to be usable in a context that is different from a web, HTTP context (I think supporting WAP using this API was a goal, at that time).

In reality, I don't know of any context other that the traditional Java EE webapp context where the servlet API is used. And in that context, all requests are instances of HttpServletRequest (which is a sub-interface of ServletRequest). And this method exists in HttpServletRequest.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • But why does it work? If pageContext.request returns ServletRequest in java you cannot use method of its subclass if you don't cast it to HttpServletRequest excplicity. – Vitalii Vitrenko Mar 06 '16 at 13:06
  • 1
    That would be true in Java. But the code you posted is not Java. It's the JSP expression language, which is a much more dynamic language. If a `getFoo()` getter method is available on an object `bar`, the `bar.foo` EL expression calls that getter, using reflection, without caring of the type of the object. – JB Nizet Mar 06 '16 at 13:08
  • Oh now I get it. I didn't know that EL uses reflection. Thanks :) – Vitalii Vitrenko Mar 06 '16 at 13:12