Scriptlets in a JSP Page to Access an Authorizatio

2019-08-21 23:44发布

So I'm basically looking for advise on how I could improve on a solution.

Some Background First,

I developed an simple in-house authorization framework to control access and behavior in a Java/J2EE based application where the framwork could my used in any the Model, View or Controller layers.

When the user logs in they are passed a User Permission object based on their assigned role. (Default is always deny). The permissions consist of a Subject (enum) as well as a list of optional permissions (Create, Read, Update, Delete...).

In some places this is used to control the display of screen elements, in others it's combined with Strategy patterns to control system behavior based on the User's role.

In the JSP layer I access it via Scriptlets because the Code Complete option makes sure that a user doesn't enter a value that's not defined in the framework.

Code Example:

<% if (user.can(Permission.somePermission, Subject.subjectOfPermission)) {  %>
    <td >
            ...display something if the User can Access the Subject
    </td>
<% } %>
<% if (user.cannot(Permission.somePermission, Subject.subjectOfPermission)) {  %>
        ...display something if the User cannot Access the Subject
<% } %>

What I'm curious to find is if there is a better way to do this? I've heard the mantra, "You shouldn't use scriptlets. Everything should be done with JSTL and Custom Tags".

However, it seems to me that by using Custom Tags I loose the advantage of using Code Complete as well as enforcing the framework's contract. To me, passing Strings to a Custom Tag only adds an extra layer of abstraction (to an abstract framework) and increases the chance of a mistake since we're now working with simple Strings.

Is there a way to create custom tag that would take Enum's as parameters or an alternate solution avoiding this altogether?

1条回答
Explosion°爆炸
2楼-- · 2019-08-22 00:09

You could use EL for this. The way to do this is by first importing the core tag library, by putting this in the head of your jsp view.

<%@ taglib prefix="c" 
       uri="http://java.sun.com/jsp/jstl/core" %>

Put your subject + permission(s) for that user in a hashmap, and make a function hasPermission, that returns whether or not the user has the permission.

class User {
    private HashMap<String, List<String>> permissionMap;

    public boolean hasPermission(String subject, String action) {
        return permissionMap.getValue(subject).contains(action);
    }
}

In your servlet, you have to put the user object in an attribute of the request by using

request.setAttribute("user", userObject);

Afterwards, you can access them like this in your view.

<c:choose>
    <c:when test="${user.hasPermission('Record', 'create')}">
    // Code when access granted
    </c:when>
    <c:otherwise>
    // Code when access denied
    </c:otherwise>
</c:choose>
查看更多
登录 后发表回答