Deny access to session attribute using EL

I understand how to access session attributes using EL in a JSP / Servlet application:

<p> Hello <c:out value="${sessionScope.userName}"/> </p> 

However, I was wondering if there is a way to hide the Session variable from accessing the JSP page? If I set a session variable in my servlet, for example:

  UserDAO user = new UserDAO(); user.setUserName("XYZ"); request.getSession().setAttribute("user", user); 

Is there a way to deny access to the UserDAO Java Object fields in the JSP using some code, for example:

  <p> Hello <c:out value="${user.userName}"/> </p> 

Thanks.

+4
source share
1 answer

No. At least not without writing a custom EL resolver that is not trivial.

It is best to wrap it in an object that does not expose the value with the Javabean getter method. For instance.

 public class UserWrapper implements Serializable { private User user; public UserWrapper(User user) { this.user = user; } public User get() { return user; } } 

Save it in the session as shown below.

 session.setAttribute("user", new UserWrapper(user)); 

Get it from the session as follows.

 User user = ((UserWrapper) session.getAttribute("user")).get(); 

This method is not available in EL. At least in EL versions prior to 2.2, where you could just do #{user.get()} .

Alternatives are to make the getter method of the wrapper class a protected package so that it is available only to classes in the same package and / or subclasses (EL specifically requires it to be publicly available).

  protected User get() { return user; } 

Or even make the entire wrapper class a closed or protected package inner class.

+4
source

All Articles