我有一个带有名为 title 的属性的类,并且我有一个获取和设置该属性的 getter/setter。如果属性是PI需要在页面上打印“Peer”字样,如果是TI需要在页面上打印“Team”。我可以在不使用脚本的情况下在 JSP 中执行此操作吗?我尝试使用
<jsp:getProperty name="value" class"classname" />
但从那里我不知道如何在 JSP 中使用条件。请帮忙。
正如@CoolBeans 所说,使用 JSTL 。它看起来像这样:
在小服务程序中,
// where myBean is an instance of the class with [get|set]Title
request.setAttribute("myFoo", myBean);
然后,在 JSP 中,
<c:choose>
<c:when test="${myBean.title eq 'P'}">Peer</c:when>
<c:when test="${myBean.title eq 'T'}">Team</c:when>
</c:choose>
如果您不熟悉 JSTL,我建议您阅读Java EE 5 教程的 JSP 部分,或者选择一份Head First Servlets 和 JSP(非常好)。
您应该使用JSTL。这是一个例子:
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<c:if test="${yourClass.p eq 'P'}">PEER</c:if>
我使用属性来设置和从用户获取数据,通过创建一个java类处理程序并使用“useBean”......这是我生成的一些代码来解决我的问题......希望它有所帮助......
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login and Do Action</title>
</head>
<% // java code
%>
<body>
<jsp:useBean id="myBean" scope="session" class="org.mypackage.IFPWAFCAD.NameHandler" />
<jsp:setProperty name="myBean" property="name"/>
<jsp:setProperty name="myBean" property="screenName"/>
<jsp:setProperty name="myBean" property="username"/>
<jsp:setProperty name="myBean" property="password" />
<h1>Hello <jsp:getProperty name="myBean" property="screenName" />! Ready to Login and perform Action</h1>
<form method="post" action="DBConnection">
<table border="0">
<thead>
<tr>
<th>
</th>
<th>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>Table:</td>
<td><input type="radio" name="tableName" value="product"/>Produce
<<input type="radio" name="tableName" value="customer" />Customer
<input type="radio" name="tableName" value="actor" checked="checked" />Actor</td>
</tr>
<tr>
<td>Action:</td>
<td>
<select name="action" value="0">
<option value="0">Choose a Action...</option>
<option value="create">Create</option>
<option value="read">Read</option>
<option value="update">Update</option>
<option value="delete">Delete</option>
<option value="fancy">Fancy Display</option>
<option value="pass">Pass to JSP File</option>
</select>
</td>
</tr>
<tr>
<td>Record ID:</td>
<td><input type="text" name="tid" size="3"/></td>
</tr>
<tr>
<td>
First Name:
</td>
<td>
<input type="text" name="firstname" size="30"/>
</td>
</tr>
<tr>
<td>
Last Name:
</td>
<td>
<input type="text" name="lastname" size="30"/>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="hidden" name="name" value="<jsp:getProperty name="myBean" property="name" />" />
<input type="hidden" name="username" value="<jsp:getProperty name="myBean" property="username" />" />
<input type="hidden" name="screenName" value="<jsp:getProperty name="myBean" property="screenName" />" />
<input type="hidden" name="password" value="<jsp:getProperty name="myBean" property="password" />" />
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Login" />
<input type="reset" name="clear" value="Clear" />
</form>
</body>