开发者

Prevent session attribute access by EL

开发者 https://www.devze.com 2023-03-12 10:35 出处:网络
I understand how to access Session attributes using EL in my JSP/Servlet application: <p> Hello <c:out value=\"${sessionScope.userName}\"/> </p>

I understand how to access Session attributes using EL in my JSP/Servlet application:

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

However, I was wondering if there was a way to hide a Session variable from JSP page EL access? If I set a session variable in my servlet, such as:

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

Is there a way to prevent that UserDAO Java Object's fields from being accessed on the JSP with some code such as:

    <p&开发者_如何学运维gt; Hello <c:out value="${user.userName}"/> </p>

Thank you.


There isn't. At least, not without writing a custom EL resolver which isn't exactly trivial.

Your best bet is to wrap it in an object which does not expose the value by a Javabean getter method. E.g.

public class UserWrapper implements Serializable {

    private User user;

    public UserWrapper(User user) {
        this.user = user;
    }

    public User get() {
        return user;
    }

}

Store it in the session as follows instead.

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

Get it from the session as follows instead.

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

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

Alternatives are to make the getter method of the wrapper class package-protected so that it's only accessible by classes in the same package and/or subclasses (EL namely requires it to be public).

    protected User get() {
        return user;
    }

Or even make the whole wrapper class a private or package-protected inner class.

0

精彩评论

暂无评论...
验证码 换一张
取 消