我想根据JSP文件中的某些条件输出一些HTML代码。
if (condition 1) {
Some HTML code specific for condition 1
}
else if (condition 2) {
Some HTML code specific for condition 2
}
我该怎么做呢?我应该使用JSTL吗?
我想根据JSP文件中的某些条件输出一些HTML代码。
if (condition 1) {
Some HTML code specific for condition 1
}
else if (condition 2) {
Some HTML code specific for condition 2
}
我该怎么做呢?我应该使用JSTL吗?
当前回答
如果您只想输出不同的文本,一个更简洁的示例是
${condition ? 'some text when true' : 'some text when false'}
它比c:choose短多了。
其他回答
我应该使用JSTL吗?
Yes.
您可以使用<c:if>和<c:choose>标记在jsp中使用JSTL进行条件呈现。
要模拟if,你可以使用:
<c:if test="condition"></c:if>
为了模拟如果…否则,您可以使用:
<c:choose>
<c:when test="${param.enter=='1'}">
pizza.
<br />
</c:when>
<c:otherwise>
pizzas.
<br />
</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标记——这样更容易阅读。
<c:if test="${any_cond}" var="condition">
//if part
</c:if>
<c:if test="${!condition}">
//else part
</c:if>
您可以在jsp页面的<% %>内编写if-else条件,在<% %>外编写html代码
例如:
<%
String username = (String)session.getAttribute("username");
if(username==null) {
%>
<p> username is null</p> //html code
<%
} else {
%>
<p> username is not null</p> //html code
<%
}
%>
如果您只想输出不同的文本,一个更简洁的示例是
${condition ? 'some text when true' : 'some text when false'}
它比c:choose短多了。