Is this an acceptable use case for a JSP script?

I know that using JSP scripts is generally frowned upon, so I wonder if there is a more elegant way to achieve what I'm trying to do. I mainly create a view, and depending on certain situations in the domain model, I process different HTML.

For example, consider a scenario in which a user may be in a role. And such a method is defined in the user model class:

public boolean isInRole(String roleName) {
    // Logic here to determine if the user is in a role
}

And then we have a JSP as shown below:

<%
    User user = (User)request.getAttribute("user");
%>

// Some HTML here...

<% if (user.isInRole("admin") { %>
    // Generate some admin menu here
<% } %>

As far as I know, this cannot be done using JSTL / EL. Does using scripts sound like a good idea here? Or is there another approach I have to take?

Thanks for any suggestions.

+3
source
3

. :

tld: WEB-INF/user.tld

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag 
Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.2</jsp-version>
  <short-name></short-name>
    <tag>
       <name>user</name>
       <tag-class>tags.UserRoleTag</tag-class>
       <body-content>JSP</body-content>
       <attribute>
          <name>roles</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
       </attribute>
    </tag>
</taglib>

: /UserRoleTag.java

package tags;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

@SuppressWarnings("serial")
public class UserRoleTag extends TagSupport {
  private String roles;

  public int doStartTag() throws JspException {
    String userRole = (String)pageContext.getAttribute("currentUserRole");

    return roles.contains(userRole) ? EVAL_BODY_AGAIN : SKIP_BODY;
  }

  public String getRoles() {
    return roles;
  }

  public void setRoles(String roles) {
    this.roles = roles;
  }
}

jsp: warfolder/home.jsp

<%@ taglib uri="/WEB-INF/user.tld" prefix="u" %>

<% pageContext.setAttribute("currentUserRole", "admin"); // this value would come from the controller... %>

<u:user roles="admin registered">
    welcome admin!
</u:user>

<u:user roles="guest">
    welcome guest!
</u:user>

, , .

+5

Servlet 3.0/JSP 2.2, EL

<c:if test="${user.isInRole('admin')}">

EL

<c:if test="${util:isUserInRole(user, 'admin')}">

, , JEE6. , ( web.xml Servlet 3.0).

+8

, ( JSP EL ) , , , .

, , , . , , , -. MVC, . JSP- EL, . , .

, ? , . , , , . ${user.isAdmin} . "" .

, , ? , , , , . , ​​, .

. , .

, . , .

+2

Source: https://habr.com/ru/post/1792133/


All Articles