欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JSTL的if标签和forEach标签(页码EL2)

程序员文章站 2022-06-13 12:51:51
...

JSTL的if标签和forEach标签(页码EL2)
导入jstl标签库

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

if标签

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<%
		request.setAttribute("test", 10);
	%>	
	<!-- jstl标签经常会和el配合使用 -->
	<!-- test代表的是返回Boolean的表达式 -->
	<c:if test="${test==10}">
		TTTT
	</c:if>
	<c:if test="${test!=10 }">
		FFFF
	</c:if>
</body>
</html>

for标签

<!-- forEach模拟 for(int i=0;i<-5;i++) -->
	<c:forEach begin="0" end="5" var="i">
		${i }<br>
	</c:forEach>

foreach标签使用

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page import="cn.aynortechnology.domain.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<%
		//模拟List<String> strList
		List<String> strList = new ArrayList<String>();
		strList.add("itcast");
		strList.add("aynor");
		strList.add("boxuegu");
		strList.add("shandingyu");
		request.setAttribute("strList", strList);
		
		//遍历List<User>内的值
		List<User> userlist = new ArrayList<User>();
		User user1 = new User();
		user1.setId(1);
		user1.setName("aynor");
		user1.setPassword("20190222**");
		userlist.add(user1);
		User user2 = new User();
		user2.setId(1);
		user2.setName("aynor");
		user2.setPassword("20190222**");
		userlist.add(user2);
		application.setAttribute("userlist", userlist);
		
		//遍历Map<String,String>的值
		Map<String,String> strMap = new HashMap<String,String>();
		strMap.put("name","ayonr");
		strMap.put("age","21");
		session.setAttribute("strMap", strMap);
		
		//遍历Map<String,User>的值
		Map<String,User> userMap = new HashMap<String,User>();
		userMap.put("user1",user1);
		userMap.put("user2",user2);
		session.setAttribute("userMap", userMap);
		
	%>
	<h1>取出strList的数据</h1>
	<c:forEach items="${strList }" var="str">
		${str }<br>
	</c:forEach>
	<h1>取出userList的数据</h1>
	<c:forEach items="${userlist }" var="user">
		user的name:${user.name }----user的password:${user.password }<br>
	</c:forEach>
	<h1>取出strMap的数据</h1>
	<c:forEach items="${strMap }" var="entry">
		${entry.key }:${entry.value }<br>
	</c:forEach>
	<h1>取出userMap的数据</h1>
	<c:forEach items="${userMap }" var="entry">
		${entry.key }:${enrty.value.name }<br>
	</c:forEach>
</body>
</html>