【问题标题】:define variables inside if condition in jsp在jsp中的if条件内定义变量
【发布时间】:2015-01-09 12:16:57
【问题描述】:

我使用follows将一个值从servlet传递给jsp,它返回整数值..

        HttpSession session = request.getSession();
        session.setAttribute(USER_OFFICE, user.getOffice().getId());

我可以在jsp中得到这个值

        <%=session.getAttribute("USER_OFFICE")%>

现在我需要根据 USER_OFFICE 值在 jsp 中显示一些文本

"Hello Police" 

如果 USER_OFFICE 值为 1

"Hello Doctor" 

如果 USER_OFFICE 值为 2

"Hello Engineer" 

如果 USER_OFFICE 值为 3

【问题讨论】:

  • 给出的答案显示了您如何可以做到这一点,但请不要这样做。这是应该存在于服务器端的确切逻辑类型,而前端应该只呈现它。为什么不让您的 servlet 计算问候语应该是什么,并在您的 JSP 中公开该值并显示它?

标签: java jsp el


【解决方案1】:

尝试 EL 和 taglib:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:choose>
    <c:when test="${1 eq USER_OFFICE}">
       Hello Police
    </c:when>
    <c:when test="${2 eq USER_OFFICE}">
        Hello Doctor
    </c:when>
    <c:otherwise>
        Hello Engineer
    </c:otherwise>
</c:choose>

或者没有标签库:

${1 eq USER_OFFICE ? "Hello Police" : (2 eq USER_OFFICE ? "Hello Doctor" : "Hello Engineer")}

【讨论】:

    【解决方案2】:
    <%
    
    String userOffice= session.getAttribute("USER_OFFICE")
    
    if(userOffice.equals("1")){
       out.print("Hello Police")
    }else if(userOffice.equals("2")){
      out.print("Hello Doctor")
    }else if(userOffice.equals("3")){
      out.print("Hello Engineer")
    }
    
    %>
    

    通过这种方式,您可以在 JSP 页面中编写 scriptlet。

    【讨论】:

      【解决方案3】:

      你可以使用scriptlet标签。

      <%
          String value = session.getAttribute("USER_OFFICE");
          if(value.equals(1)){
                 out.print("Hello Police");
          }else if(value.equals("2")){
                 out.print("Hello Police");
          }else if(value.equals("3")){
                 out.print("Hello Engineer");
          }
      
      %>
      

      附:您提到了 1、2 和 3,这是我之前没有看到的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-08-30
        • 2014-12-06
        • 1970-01-01
        • 2012-02-26
        • 2020-11-02
        • 2019-10-03
        • 2012-01-14
        相关资源
        最近更新 更多