JavaWeb筆記十三:JSTL、自定義標籤、MVC、Java三層框架

JSTL

Apache提供的標籤庫,
jar包:jstl-1.2.jar,如果傅MyEclipse,它會在我們導入jar包,無需自己導入,如果沒有使用MyEclipse那麼需要自行導入。

------------------

導入JSTL核心標籤庫
<%taglib prefix="c" uri="http://java.sun.com/jstl/core"%>


<c:set> 
* <c:set var="a" value="hello"/> 創建名爲a,值爲hello的域屬性,範圍:page
* <c:set var="a" value="hello" scope="session"/> 範圍爲session

<c:out>
* <c:out value="aaa"/> 輸出字符串aaa
* <c:out value="${aaa"/> 輸出域屬性aaa,其中與${aaa}相同
* <c:out value="${aaa}" default="xxx"/>如果${aaa}不存在,那麼輸出xxx字符串
* <c:out value="${aaa}" escapeXml="true"/>如果${aaa}中包含特殊字符,那麼轉義它。這可以防止javascript攻擊

<c:remove>
* <c:remove var="a"/> 刪除名爲a的域屬性
* <c:remove var="a" scope="page"/> 刪除page域中名爲a的域屬性

<c:url>
* <c:url value="/AServlet"/> 輸出URL:/項目名/AServlet
* <c:url value="/AServlet" var="url" scope="page"/> 把生成的url保存到page域中,而不會輸出
* <c:url value="/AServlet">:輸出URL:/項目名/AServlet?username=%xx%xx%xx%xx%xx%xx,其中張三會被URL編碼
   <c:param name="username" value="張三"/>
  </c:url/>

<c:if>
* <c:if test="${條件}"> 當條件爲true時執行標籤體內容
    hello
  </c:if>

<c:choose>
* <c:choose>
    <c:when test="${條件1}">a</c:when>
    <c:when test="${條件2}">b</c:when>
    <c:when test="${條件3}">c</c:when>
    <c:otherwise>d</c:otherwise>
  </c:choose>

  等同與:
  if() {
  } esle if() {
  } esle if() {
  } else if() {
  } else {
  }

-------------

<c:forEach>

可以用來遍歷數組、List、Map、

1. 計數循環

<c:forEach begin="1" end="10" var="i">
 ${i}
</c:forEach>
等同於
for(int i = 1; i <= 10; i++) {
  out.println(i);
}


<c:forEach begin="1" end="10" var="i" step="2">
 ${i}
</c:forEach>
等同於
for(int i = 1; i <= 10; i+=2) {
  out.println(i);
}

-------------

2. 遍歷數組

<%
String[] names = {"zhangSan", "liSi", "wangWu", "zhaoLiu"};
pageContext.setAttribute("ns", names);
%>
<c:forEach var="item " items="${ns } ">
	<c:out value="name: ${item } "/><br/>
</c:forEach>


-------------

3. 遍歷List

<%
	List<String> names = new ArrayList<String>();
	names.add("zhangSan");
	names.add("liSi");
	names.add("wangWu");
	names.add("zhaoLiu");
	pageContext.setAttribute("ns", names);
%>
<c:forEach var="item" items="${ns }"> 
	<c:out value="name: ${item }"/><br/>
</c:forEach>

-------------

4. 遍歷Map

<%
	Map<String,String> stu = new LinkedHashMap<String,String>();
	stu.put("number", "N_1001");
	stu.put("name", "zhangSan");
	stu.put("age", "23");
	stu.put("sex", "male");
	pageContext.setAttribute("stu", stu);
%>
<c:forEach var="item " items="${stu }">
	<c:out value="${item.key }: ${item.value } "/><br/>
</c:forEach>


-------------

5. 循環狀態對象

循環狀態對象是用來說明循環的狀態的,屬性如下:
count:int類型,當前以遍歷元素的個數;
index:int類型,當前元素的下標;
first:boolean類型,是否爲第一個元素;
last:boolean類型,是否爲最後一個元素;
current:Object類型,表示當前項目。

<c:forEach var="item" items="${ns }" varStatus="vs" >
	<c:if test="${vs.first } ">第一行:</c:if>
	<c:if test="${vs.last } ">最後一行:</c:if>
	<c:out value="第${vs.count } 行: "/>
	<c:out value="[${vs.index } ]: "/>
	<c:out value="name: ${vs.current } "/><br/>
</c:forEach>


------------------

導入JSTL格式化標籤庫

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

<%
	Date date = new Date();
	pageContext.setAttribute("d", date);
%>
<fmt:formatDate value="${d }" pattern="yyyy-MM-dd HH:mm:ss "/>

---------

<%
	double d1 = 3.5;
	double d2 = 4.4; 
	pageContext.setAttribute("d1", d1);
	pageContext.setAttribute("d2", d2);
%>
<fmt:formatNumber value="${d1 }" pattern="0.00 "/><br/>
<fmt:formatNumber value="${d2 }" pattern="#.## "/>

* pattern:0.00,表示小數不足兩位時,使用0補足兩位
* pattern:#.##,表示小數不足兩位時,有幾位顯示幾位,不會補足

自定義標籤

自定義標籤:

1. 實現Tag接口,即傳統標籤。不建議使用!
2. 實現SimpleTag接口,即簡單標籤。建議使用!

JavaWeb中還提供了SimpleTagSupport類,繼承它要比實現SimpleTag接口方便。

-----------------

步驟:
1. 標籤處理類:繼承SimpleTagSupport類
public class HelloTag extends SimpleTagSupport {
	public void doTag() throws JspException, IOException {
		// 獲取JspContext對象,再獲取out對象,再向頁面輸出
		// 獲取到的JspContext其實就是當前頁面的pageContext對象
		this.getJspContext().getOut().write("<p>Hello SimpleTag!</p>") ;
	}
}

2. 標籤描述符文件(tld)

/WEB-INF/tlds/itcast.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xml="http://www.w3.org/XML/1998/namespace" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
						http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd ">

	<tlib-version>1.0</tlib-version> 
	<short-name>itcast</short-name> 
	<uri>http://www.itcast.cn/tags</uri> 
	<tag> 
		<name>hello</name> <!--標籤名稱-->
		<tag-class>cn.itcast.tag.HelloTag</tag-class> <!--標籤處理類名稱-->
		<body-content>empty</body-content> <!--標籤體爲空,即空標籤-->
	</tag>
</taglib>

3. jsp頁面中使用自定義標籤

<%@ taglib prefix="it"  uri="/WEB-INF/hello.tld"  %>
......
<it:hello/>

----------------------

有標籤體的標籤

1. 標籤處理類
public class HelloTag extends SimpleTagSupport {
	public void doTag() throws JspException, IOException {
		PageContext pc = (PageContext) this.getJspContext();
		HttpServletRequest req = (HttpServletRequest) pc.getRequest();
		String s = req.getParameter("exec");
		if(s != null && s.endsWith("true")) {
			// 獲取標籤體對象
			JspFragment body = this.getJspBody() ;
			// 執行標籤體
			body.invoke (null);
		}

	}
}

2. tld

	<tag>
		<name>hello</name>
		<tag-class>cn.itcast.tags.HelloTag</tag-class>
		<body-content>scriptless</body-content> <!--標籤體內容不可以是java腳本,但可以是el、jstl等-->
	</tag>

----------------------

不執行標籤下面的頁面內容

	public void doTag() throws JspException, IOException {
		this.getJspContext().getOut().print("<h1>只能看到我!</h1>");
		throw new SkipPageException();
	}

----------------------

帶有屬性的標籤

public class IfTag extends SimpleTagSupport {
	private boolean test;//設置屬性,提供getter/setter方法
	public boolean isTest() {
		return test;
	}
	public void setTest (boolean test) {
		this.test = test;
	}
	@Override
	public void doTag() throws JspException, IOException {
		if(test) {//如果test爲true,執行標籤體內容
			this.getJspBody().invoke(null);
		} 
	}
}

	<tag> 
		<name>if</name> 
		<tag-class>cn.itcast.tag.IfTag</tag-class> 
		<body-content>scriptless</body-content>
		<!--部署屬性-->
		<attribute> 
			<name>test</name> <!--屬性名-->
			<required>true</required> <!--屬性是否爲必須的-->
			<rtexprvalue>true</rtexprvalue> <!--屬性值是否可以爲EL或JSTL等-->
		</attribute> 
	</tag>

MVC

1. 什麼是MVC
  MVC模式(Model-View-Controller)是軟件工程中的一種軟件架構模式,把軟件系統分爲三個基本部分:模型(Model)、視圖(View)和控制器(Controller)。

* 控制器Controller:對請求進行處理,負責請求轉發;
* 視圖View:界面設計人員進行圖形界面設計;
* 模型Model:程序編寫程序應用的功能(實現算法等等)、數據庫管理;

2. Java與MVC

JSP Model1第一代:JSP + DB
JSP Model1第二代:JSP + javabean + DB
JSP Model2:JSP + Servlet + JavaBean + DB

JavaWeb三層框架

* Web層(表述層):與Web相關的,例如jsp、servlet都是Web層
* Business層(業務邏輯層):封裝業務邏輯,通常對應一個業務功能,例如登錄、註冊都是一個業務功能。
* Data層(數據訪問層):封裝對數據庫的操作,通常對應一次對數據庫的訪問,例如添加、修改、刪除、查詢等。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章