我想根据JSP文件中的某些条件输出一些HTML代码。

if (condition 1) {
    Some HTML code specific for condition 1
}
else if (condition 2) {
    Some HTML code specific for condition 2
}

我该怎么做呢?我应该使用JSTL吗?


当前回答

<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<c:set var="val" value="5"/>
<c:choose> 
  <c:when test="${val == '5'}">
    Value is 5
  </c:when>
  <c:otherwise>
    Value is not 5
  </c:otherwise>
</c:choose>

其他回答

如果你想比较字符串,写下面的JSTL:

<c:choose>
    <c:when test="${myvar.equals('foo')}">
        ...
    </c:when>
    <c:when test="${myvar.equals('bar')}">
        ...
    </c:when>
    <c:otherwise>
        ...
    </c:otherwise>
</c:choose>
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<c:set var="isiPad" value="value"/>
<c:choose>
   <!-- if condition -->
   <c:when test="${...}">Html Code</c:when> 
   <!-- else condition -->
   <c:otherwise>Html code</c:otherwise>   
</c:choose>

它的结构是:

<c:choose>
   <c:when test="${..}">...</c:when> <!-- if condition -->
   <c:when test="${..}">...</c:when> <!-- else if condition -->
   <c:otherwise>...</c:otherwise>    <!-- else condition -->
</c:choose>

如果条件不是很昂贵,我有时更喜欢简单地使用两个不同的<c: If标记——这样更容易阅读。

如果你想比较字符串,写下面的JSTL:

<c:choose>
    <c:when test="${myvar.equals('foo')}">
        ...
    </c:when>
    <c:when test="${myvar.equals('bar')}">
        ...
    </c:when>
    <c:otherwise>
        ...
    </c:otherwise>
</c:choose>

简单方法:

<c:if test="${condition}">
    //if
</c:if>
<c:if test="${!condition}">
    //else
</c:if>