JSP
JSP是一種Web服務(wù)設(shè)計標(biāo)準(zhǔn)茬祷,以Java技術(shù)為基礎(chǔ)清焕,實現(xiàn)頁面的動態(tài)輸出。
Serlvet 提供了用于服務(wù)器編程的API,但是不能有效地管理頁面的邏輯部分和頁面輸出部分秸妥,導(dǎo)致Servlet類的代碼非彻鐾#混亂,為了克服這個缺點粥惧,Sun公司用Servlet為基礎(chǔ)键畴,推出了JSP。
JSP頁面組成
1.普通的HTML標(biāo)記符突雪。
2.JSP標(biāo)記起惕,如指令標(biāo)記,動作標(biāo)記咏删。
3.變量和方法的聲明惹想。
4.Java程序片。
5.Java表達(dá)式督函。
<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%--JSP 指令標(biāo)記--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%!
String mCurTime;
public String showTime() {
return new SimpleDateFormat("yyyy年MM月dd日").format(new Date());
}
%>
<html>
<head>
<title>JSPDemo</title>
</head>
<body>
<%
//Java程序片
mCurTime = showTime();
%>
當(dāng)前時間:<%= mCurTime%> //Java表達(dá)式
</body>
</html>
JSP語法
1.聲明變量嘀粱,方法
在<%! %> 標(biāo)記符號之間放置Java的變量聲明和方法。
聲明的變量為JSP頁面的 全局變量辰狡,在整個JSP頁面都有效锋叨。
方法在程序片中調(diào)用<% %>
習(xí)慣將<%! %> 放在JSP頁面的前面。
注意:全局變量為所有線程共享宛篇,操作數(shù)據(jù)要注意加鎖等待娃磺。
<%!
int mCount = 0;
public synchronized int getCount() {
return mCount++;
}
%>
2.Java程序片,表達(dá)式
1.Java程序片
在<% %>之間插入Java程序片些己,JSP頁面的程序片會被JSP引擎按順序執(zhí)行豌鸡。
2.Java表達(dá)式
在<%= %>間插入表達(dá)式嘿般,%=間不能有空格
這個表達(dá)式 必須能求值段标,表達(dá)式的值由服務(wù)器負(fù)責(zé)計算,并將結(jié)果以 字符串的形式發(fā)送到客戶端顯示炉奴。
在程序片中聲明的變量都是 局部變量逼庞。
<body>
<% int curCount;
curCount = getCount(); %>
第<%=curCount %>個訪問本網(wǎng)站
</body>
JSP指令標(biāo)記
1.page 指令標(biāo)記
page指令用來定義整個JSP頁面的一些屬性,page指令對整個頁面都有效瞻赶,與書寫位置無關(guān)赛糟,但是一般習(xí)慣放在JSP頁面最前端。
<%@ page contentType="text/html;charset=UTF-8" language="java"
import="java.util.Date"
session="true"
buffer="8kb"
autoFlush="true"
isThreadSafe="true"
%>
contentType:定義JSP頁面響應(yīng)的MIME類型和字符編碼砸逊。
language:定義JSP頁面使用的腳本語言璧南。
session:用于設(shè)置是否需要使用內(nèi)置的session對象,默認(rèn)true
buffer:內(nèi)置out對象緩沖區(qū)的大小师逸,或不用緩沖區(qū)none
autoFlush:緩沖區(qū)填滿時司倚,是否自動刷新,默認(rèn)true
isThreadSafe:是否可以多線程訪問,默認(rèn)true
2.include 指令標(biāo)記
可以在JSP頁面出現(xiàn)該指令的位置處动知,靜態(tài)插入一個文件皿伺。
使用include可以使代碼復(fù)用,比如每個頁面都需要導(dǎo)航條時盒粮。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>nav</title>
</head>
<body>
假裝這是個導(dǎo)航欄鸵鸥,和兩千行相同的代碼
</body>
</html>
<%@include file="nav.jsp"%>
<html>
<head>
<title>JSPDemo</title>
</head>
<body>
<br/>
假裝這是不同的主題內(nèi)容
</body>
</html>
JSP動作標(biāo)記
動作標(biāo)記是一種特殊的標(biāo)記,它影響JSP 運行時 的功能丹皱。
public class User {
private String name;
private int age;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
<body>
<%--生成User對象妒穴,id=bean的對象名,class=bean所在的包 scope=作用范圍--%>
<jsp:useBean id="user" class="com.bean.User" scope="session"/>
<%--設(shè)置值--%>
<jsp:setProperty name="user" property="name" value="張三" param="name"/>
<%--獲取值--%>
<jsp:setProperty name="user" property="age" value="18"/>
<jsp:getProperty name="user" property="name"/>
<%="年齡:"+user.getAge()%>
</body>
JSP內(nèi)置對象
有些對象不用聲明就可以在JSP頁面的Java程序片和表達(dá)式中部分使用摊崭,這些就是JSP內(nèi)置對象宰翅。
常用的內(nèi)置對象
request
response
session
application
out
1.request 對象
request封裝了用戶提交的信息,使用request對象可以獲取表單提交的信息爽室。
常常使用HTML中的表單向服務(wù)器的某個JSP頁面提交信息
<body>
<form action="#" method="get">
<input type="text" placeholder="用戶名" name="name">
<input type="submit" value="提交">
</form>
<%String userName;
userName = request.getParameter("name");
if (userName!=null)
out.println("提交的用戶名為:"+userName);
%>
</body>
Request 對象常用API
<%
request.getParameterMap();
request.getMethod();
request.getServerName();//獲取服務(wù)器名稱
request.getServerPort();//獲取服務(wù)器的端口
request.getRemoteAddr();//獲取用戶IP地址
request.getServletPath();//獲取獲取用戶請求的Web服務(wù)目錄
%>
2.response對象
response對象汁讼,用于對用戶的請求作出動態(tài)響應(yīng),向客戶端發(fā)送數(shù)據(jù)阔墩。
response狀態(tài)行
1xx:(1開頭的3位數(shù))主要是實驗性質(zhì)嘿架。
2xx:表明請求成功
3xx:在請求滿足前應(yīng)采取進(jìn)一步行動
4xx:瀏覽器無法滿足請求
5xx:服務(wù)器出問題
當(dāng)將網(wǎng)頁保存在word 文檔時需要修改MIME類型,這時用響應(yīng)修改
<body>
<P>是否確認(rèn)將當(dāng)前頁面保存為Word文檔</p>
<form action="#" method="get">
<input type="submit" name="submit" value="提交">
</form>
<%
if ("提交".equals(request.getParameter("submit")))
response.setContentType("application/msword;charset=gb2312");
%>
</body>
response重定向
<body>
<P>是否確認(rèn)跳轉(zhuǎn)</p>
<form action="#" method="get">
<input type="submit" name="submit" value="提交">
</form>
<%
if ("提交".equals(request.getParameter("submit")))
response.sendRedirect("nav.jsp");
%>
</body>
3.session對象
當(dāng)用戶第一次訪問Web服務(wù)目錄上的一個JSP頁面時啸箫,JSP引擎會創(chuàng)建一個和該用戶對應(yīng)的Session對象耸彪,當(dāng)用戶在所訪問的Web服務(wù)目錄的各個頁面之間瀏覽時,這個Session對象都是同一個忘苛。
session 重寫URL
用戶從一個頁面重新連接到另一個頁面時蝉娜,通過新的URL添加參數(shù),把session對象的id傳過去扎唾,從而保證了各頁面中session對象是同一個召川。
<%
response.encodeRedirectURL("demo.jsp");
%>
session 存儲數(shù)據(jù)
<body>
<P>是否確認(rèn)跳轉(zhuǎn)</p>
<form action="#" method="get">
<input type="text" placeholder="用戶名" name="name">
<input type="submit" name="submit" value="提交">
</form>
<%
String name = request.getParameter("name");
session.setAttribute("username",name);
session.getAttribute("username");
session.removeAttribute("username");
session.invalidate();
%>
</body>
4.application對象
application對象由服務(wù)器負(fù)責(zé)創(chuàng)建,每個Web服務(wù)目錄下的application對象被訪問該服務(wù)目錄所有的用戶共享胸遇。
<%
application.setAttribute("username",name);
application.getAttribute("username");
application.removeAttribute("username");
%>
4.out對象
用來向客戶端輸出數(shù)據(jù)
<%
out.print("");
out.println("");
out.newLine();
out.flush();
out.clear();
%>
EL(Expression Language)
EL為 JSP 提供了簡化表達(dá)式的方法荧呐,讓JSP的代碼更加簡化。
基本語法:${express}
從作用域中獲取共享數(shù)據(jù)
EL表達(dá)式在獲取某個對象的屬性值時纸镊,先將某個屬性值的首字母變成大寫倍阐,然后加上 get 前綴,拼接成get方法逗威,再通過反射將該對象構(gòu)建出來峰搪,然后再對該對象執(zhí)行g(shù)etter方法,這與私有屬性并沒有關(guān)系凯旭,所以要注意概耻,JavaBean的屬性名要小寫楣颠,且要有g(shù)etter方法,不然會報錯咐蚯。
使用EL表達(dá)式童漩,獲取數(shù)據(jù)時,會在四大作用域中順序查找春锋,直到找到為止矫膨。
若找不到鍵值對應(yīng)的屬性值,不會顯示Null期奔,會顯示空字符串侧馅。
作用域的查找順序
page
request
session
application
1.直接從JavaBean中獲取數(shù)據(jù)
@WebServlet(value = "/a")
public class AServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserBean userBean = new UserBean();
userBean.setName(req.getParameter("name"));
req.getSession().setAttribute("user",userBean);
resp.sendRedirect("show_user_info.jsp");
}
}
<%-- 獲得所創(chuàng)建Bean的引用 --%>
<%--<jsp:useBean id="user" type="com.bean.UserBean" scope="session"/>--%>
<html>
<head>
<title>JSPDemo</title>
</head>
<body>
<p>
提交的用戶名為:<%--<jsp:getProperty name="user" property="name" />--%>
${user.name}
</p>
</body>
</html>
2.從List集合中獲取數(shù)據(jù)
@WebServlet(value = "/a")
public class AServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
List<UserBean> userBeanList = new ArrayList<>();
UserBean userBean = new UserBean();
userBean.setName(req.getParameter("name"));
userBeanList.add(userBean);
req.getSession().setAttribute("userList",userBeanList);
resp.sendRedirect("show_user_info.jsp");
}
}
<body>
<p>
提交的用戶名為:
${userList[0].name}
</p>
</body>
3.從Map集合中獲取數(shù)據(jù)
@WebServlet(value = "/a")
public class AServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String,UserBean> userBeanMap = new HashMap<>();
UserBean userBean = new UserBean();
userBean.setName(req.getParameter("name"));
userBeanMap.put("user1",userBean);
req.getSession().setAttribute("userMap",userBeanMap);
resp.sendRedirect("show_user_info.jsp");
}
}
<body>
<p>
提交的用戶名為:
${userMap['user1'].name}
</p>
</body>
JSTL(JavaServer Pages Standard Tag Library)
JSTL主要提供給Java Web開發(fā)人員一個標(biāo)準(zhǔn)通用的標(biāo)簽函數(shù)庫,解決JSP中寫Java代碼麻煩的問題呐萌。
使用步驟
1.導(dǎo)入JSTL的Jar
2.在jsp文件頂部加入taglib指令引入jar
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3.導(dǎo)入c.tld文件解決報錯問題
添加http://java.sun.com/jsp/jstl/core
File:填寫解壓后tld文件夾下的 /jakarta-taglibs-standard-1.1.2/tld/c.tld
4.在Web.XML中將Jar導(dǎo)入
JSTL的使用
c:if (單條件判斷)
test:條件表達(dá)式
var:返回結(jié)果馁痴,true,false
scope:指定從哪個作用域獲取數(shù)據(jù)
<body>
<%
int limit = 18;
request.setAttribute("age",limit);
%>
<c:if test="${age>18}">
可瀏覽
</c:if>
<c:if test="${age>=18}" var="res" scope="request">
${requestScope.res}
</c:if>
</body>
c:choose肺孤,c:when罗晕,c:otherwise(多條件判斷標(biāo)簽使用)
<body>
<%
Integer score = 90;
request.setAttribute("score", score);
%>
<c:choose>
<c:when test="${score >= 90}">優(yōu)秀</c:when>
<c:when test="${score >= 60 && score<90}">及格</c:when>
<c:otherwise>不及格</c:otherwise>
</c:choose>
</body>
c:forEach(循環(huán)標(biāo)簽)
items:要遍歷的集合,一定要寫EL表達(dá)式
var:返回的集合item值
varStatus:一個輔助類赠堵,標(biāo)記行數(shù)
<body>
<%
List list = new ArrayList();
list.add("Data1");
list.add("Data2");
list.add("Data3");
request.setAttribute("lists", list);
%>
<c:forEach items="${lists}" var="item" varStatus="vs">
${vs.count}:
${item}<br />
</c:forEach>
<!-- 輸出數(shù)字1-10 -->
<c:forEach begin="1" end="10" step="1" var="num">
${num}
</c:forEach>
</body>
XML(可擴(kuò)展置標(biāo)語言)
1.XML聲明
<?xml version="1.0" encoding="UTF-8" ?>
聲明位于XML文件的第一行小渊,以<?xml標(biāo)記開始,以?>標(biāo)記結(jié)束茫叭。
2.XML標(biāo)記
XML是由標(biāo)記構(gòu)成的文件
標(biāo)記名稱可以由字母酬屉、數(shù)字、下劃線"_"揍愁、點符號"."或連字符號"-"組成呐萨,但必須以字母或下劃線開頭。
如果是UTF-8編碼莽囤,字母包括漢字谬擦。
標(biāo)記名稱區(qū)分大小寫