Servlet和Jsp模式
Servlet技術:開發動態資源,是一個Java類,最擅長寫Java代碼。Jsp技術:也是開發動態資源,通過Java代碼最擅長輸出html代碼。
Servlet負責的內容:
- 接收參數處
- 理業務邏輯
- 把結果保存到域對象中
- 跳轉到jsp頁面
JSP負責的任務:
- 從域對象取出數據
- 把數據顯示到瀏覽器
總結:我們在開發中,Jsp頁面儘量少寫甚至不寫Java代碼,所以我們使用EL表達式替換掉jsp表達式。EL表達式的主要作用是向瀏覽器輸出域對象的變量值或表達式計算的結果。
EL語法
- 輸出基本數據類型變量:${name}(從四個域中獲取)
- 指定域獲取${pageScope.name} pageScoep,requestScope,sessionScope,applicationScope
Jsp標籤
Jsp標籤的作用
替換jsp腳本
JSTL標籤
JSTL (全名:java standard tag libarary - java標準標籤庫 )
- 核心標籤庫 (c標籤庫) 天天用
- 國際化標籤(fmt標籤庫)
- EL函數庫(fn函數庫)
- xml標籤庫(x標籤庫)
- sql標籤庫(sql標籤庫)
核心標籤庫的重點標籤
<%@ page language="java" import="java.util.*,com.lyjs.bean.*" pageEncoding="UTF-8"%>
<%-- 導入標籤庫 --%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>核心標籤庫</title>
</head>
<body>
<%
Map map=new HashMap<String,Student>();
ArrayList list=new ArrayList<Student>();
Student student1=new Student("Tom","123456");
Student student2=new Student("Tom","123456");
Student student3=new Student("Tom","123456");
Student student4=new Student("Tom","123456");
map.put("001", student1);
map.put("002", student2);
map.put("003", student3);
map.put("004", student4);
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
//域對象中存取數據
pageContext.setAttribute("listStudents", list);
pageContext.setAttribute("mapStudents", map);
%>
<%--set標籤:保存數據(保存到域中)默認保存到page域 --%>
<c:set var="score" value="55"></c:set><br/>
<%--out標籤:獲取數據(從域中),當value值爲null,使用默認值
escapeXml:是否對value值進行轉義,false不轉義,true,轉義(默認)
--%>
<c:out value="成績爲:${score }" default="默認值" escapeXml="true"></c:out><br/>
<%--if標籤,但條件判斷 --%>
<c:if test="${score>60 }">
成績大於60
</c:if><br/>
<%--choose標籤+when 標籤+otherwrise標籤 --%>
<c:choose>
<c:when test="${score>=90 && score<100 }">
優秀
</c:when>
<c:when test="${score>=80 && score<90 }">
良好
</c:when>
<c:when test="${score>=60 && score<80 }">
良好
</c:when>
<c:otherwise>
不及格
</c:otherwise>
<%--forEarch:循環遍歷
begin="" :從哪個元素開始,默認從0開始
end="" :到哪個元素結束,默認到最後一個元素
step="1" :步長(每次加幾個):默認爲1
items="" :需要遍歷的數據集合
var="" :每個元素名稱
varStatus="" :當前正在遍歷元素的狀態對象(count屬性:當前位置,從1開始)
--%>
<br>
<c:forEach step="1" items="${listStudents}" var="student" varStatus="varSta">
序號:${varSta.count } -姓名: ${student.username } - 密碼:${student.password }<br/>
</c:forEach>
<%-- 遍歷map集合 --%>
<c:forEach var="entry" items="${ mapStudents}">
序號:${entry.key } 姓名:${entry.value.username } 密碼:${entry.value.password }<br/>
</c:forEach>
<%--forToken標籤:循環特殊字符串 --%>
<%
String str="php-java-net";
pageContext.setAttribute("str", str);
%>
<c:forTokens items="${str }" delims="-" var="s">
${s }<br/>
</c:forTokens>
<%--redirect:重定向 --%>
<c:redirect url="http://www.baidu.com"></c:redirect>
</body>
</html>