我想根据 JSP 文件中的某些条件输出一些 HTML 代码。
if (condition 1) {
Some HTML code specific for condition 1
}
else if (condition 2) {
Some HTML code specific for condition 2
}
我怎样才能做到这一点?我应该使用 JSTL 吗?
我应该使用 JSTL 吗?
是的。
您可以使用 <c:if>
和 <c:choose>
标签在使用 JSTL 的 jsp 中进行条件渲染。
要模拟 if ,您可以使用:
<c:if test="condition"></c:if>
要模拟 if...else,您可以使用:
<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
标记——这样更容易阅读。
如果要比较字符串,请编写以下 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="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>
简单的方法:
<c:if test="${condition}">
//if
</c:if>
<c:if test="${!condition}">
//else
</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
<%
}
%>
<%@ 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:if test="${any_cond}" var="condition">
//if part
</c:if>
<c:if test="${!condition}">
//else part
</c:if>
<c:if test="${condition1 && condition2 && condition3}" var="condition">
//if
</c:if>
<c:if test="${!condition}">
//else
</c:if>
这是在变量中采用 if 条件的另一种方法。
如果您想使用 JSTL Tag Libe 执行以下操作,请按照以下步骤操作:
【要求】如果一个数字大于等于40小于50则显示“以4开头的两位数”,否则显示“其他数字”。
[解决方案]
1. Please Add the JSTL tag lib on the top of the page.`
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>`
2. Please Write the following code
`
<c:choose>
<c:when test="${params.number >=40 && params.number <50}">
<p> Two digit number starting with 4. </p>
</c:when>
<c:otherwise>
<p> Other numbers. </p>
</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>
<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>
不定期副业成功案例分享