JDBC 其實有一點像是 EL
首先下載
JSTL.jar 放在 Project/WebContent/WEB-INF/lib 底下
接下來在新增一個繼承 HttpServlet 的 Class
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/HelloEveryone")
public class HelloEveryone extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 字串
String strData = "這是字串資料第一筆";
// List
List<String> listData = new ArrayList<String>();
listData.add("這是List第一筆數");
listData.add("這是List第二筆數");
listData.add("這是List第三筆數");
// Map
Map<String, String> mapData = new HashMap<String, String>();
mapData.put("First", "這是Map第一筆");
mapData.put("Second", "這是Map第二筆");
request.setAttribute("Date_1", strData);
request.setAttribute("Date_2", listData);
request.setAttribute("Date_3", mapData);
String uri = "/jsp/HelloEveryone.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(uri);
dispatcher.forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse respone)
throws ServletException, IOException {
super.doPost(request, respone);
}
}
在使用 JSTL 時候
一定要先宣告標籤
不然一定會出現錯誤訊息
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ 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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 字串資料 -->
<c:out value="${requestScope.Date_1}"></c:out>
<br>
<br>
<!-- List 資料 items是對應的資料來源,var是來源內的參數 -->
<c:forEach items="${requestScope.Date_2}" var="listData_2">
<c:out value="${listData_2}"></c:out><br>
</c:forEach>
<br>
<br>
<!-- Map 資料 -->
<c:forEach items="${requestScope.Date_3}" var="mapData_3">
<c:out value="${mapData_3.key}"></c:out> : <c:out value="${mapData_3.value}"></c:out><br>
</c:forEach>
</body>
</html>
參考資料 :
jsp与html的区别
參考資料 :
Attribute
歡迎轉載,請註明出處.