2. jstl中choose,if,set,out,remove标签,以及进一步精简获取对象时的代码

1.choose标签

<c:choose>
    <c:when test="事件">
        代码块  
    </c:when>
    <c:when test="事件">
        代码块
    </c:when>
    <c:otherwise>
        代码块
    </c:otherwise>
</c:choose>

类似于java中的switch事件。when等同于case,otherwise等同于default。

2.if标签

<c:if test="">
</c:if>

需要注意的是,jstl中没有if-else语句。想要实现只能一遍一遍写if标签。

3.set标签

<c:set var="变量名" value="获取到的值">
</c:set>

value中长式子的值就可以用${变量名}来调用,可以大幅度精简jsp页面中的代码。例子见后

4.out标签

<c:out value="${key}"></c:out>

该标签用于显示数据

5.remove标签

<c:remove var="变量名"></c:remove>

通常和上面的set标签搭配使用。


【说明】(1)test属性用于存放判断的条件,一般为EL表达式。

    (2)var属性用于存放判断结果,类型为true或false。


6.现有三个学生对象,属性有 name,id,address,并均已赋值。

要求在页面上显示。

public class RoleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		List<User>list=new ArrayList<User>();
		list.add(new User("jim", "25", "无意义的词条1"));
		list.add(new User("sun", "21", "无意义的词条2"));
		list.add(new User("oracle", "21", "无意义的词条3"));
		
		request.setAttribute("lists", list);
		request.getRequestDispatcher("user.jsp").forward(request, response);
	}
}
<body>
<style>
	table{
	  border:black 1px solid;
	  border-spacing:0px;
	  border-collapse:collapse;
	}
	th{
		border:black 1px solid;
	}
	td{
		border:black 1px solid;
	}
</style>
	<table>
		<tr>
			<th>name</th><th>id</th><th>address</th>
		</tr>
		
		<c:forEach var="l" items="${lists}"> 
			<tr>
				<td>
					${l.name}
				</td>
				<td>
					${l.id}
				</td>
	 			<td>
					<c:set var="address" value="${l.address}"></c:set>
					<c:choose>
							<c:when test="${fn:length(address)>6}">
								${fn:substring(address,0,4)}... 
							</c:when>
							<c:otherwise>
								${address} 
							</c:otherwise>
					</c:choose>
					<c:remove var="address"/>
				</td>
			</tr>
		</c:forEach>
		
	</table>
</body>
发布了30 篇原创文章 · 获赞 1 · 访问量 746

猜你喜欢

转载自blog.csdn.net/nairuozi/article/details/103446379