我想根据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吗?
当前回答
<c:if test="${any_cond}" var="condition">
//if part
</c:if>
<c:if test="${!condition}">
//else part
</c:if>
其他回答
<%@ 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>
您可以在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
<%
}
%>
<c:choose>
<c:when test="${not empty userid and userid ne null}">
<sql:query dataSource="${dbsource}" var="usersql">
SELECT * FROM newuser WHERE ID = ?;
<sql:param value="${param.userid}" />
</sql:query>
</c:when>
<c:otherwise >
<sql:query dataSource="${dbsource}" var="usersql">
SELECT * FROM newuser WHERE username = ?;
<sql:param value="${param.username}" />
</sql:query>
</c:otherwise>
<%@ 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>