麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

第14天(就業(yè)班) 自定義標(biāo)簽&mvc編碼實(shí)戰(zhàn)

2019-11-14 11:47:51
字體:
供稿:網(wǎng)友

一、  課程回顧

1. jsp加強(qiáng)

a)  jsp的9大內(nèi)置對象

request       HttpServletRequest

response      HttpServletResponse

config        ServletCongfig

application   ServletContext

exception     Throwable

page          Object

pageContext   PageContext

out           JspWriter

session       HttpSesstion

b)  Jsp的4個(gè)域?qū)ο?/p>

request

session

application

pageContext

作用范圍:

pageContext:處于當(dāng)前jsp頁面

request:處于同一個(gè)請求中

session:處于統(tǒng)一會(huì)話中

application:處于同一個(gè)web應(yīng)用中都是有效的

c)  el表達(dá)式

替代jsp表達(dá)式,用于向?yàn)g覽器輸出域?qū)ο笾械淖兞?#20540;和表達(dá)式計(jì)算的結(jié)果。

語法:${變量}

輸出普通字符串:${name}

輸出對象屬性:${student.name},注意.name相當(dāng)于.getName()方法

輸出List集合:${list[0].name},注意[0]相當(dāng)于get(下標(biāo))方法

輸出map集合:${map[key].name},注意:[key]相當(dāng)于get(key)方法

d)  jsp標(biāo)簽

替代jsp腳本,用于在jsp頁面中執(zhí)行java代碼

   1.內(nèi)置標(biāo)簽:

   <jsp:foward/>   request.getRequesetDipsacher("/路徑").foward(request,response);

<jsp:param/>   參數(shù)標(biāo)簽    ?name=eric

<jsp:include/>   包含其他頁面 ,動(dòng)態(tài)包含

靜態(tài)包含: 先合并再翻譯。不能傳遞參數(shù)

動(dòng)態(tài)包含: 先翻譯再合并。可以傳遞參數(shù)

2. jstl標(biāo)簽庫(Java標(biāo)準(zhǔn)標(biāo)簽庫)

使用步驟:

1) 確保jstl支持的jar包存在于項(xiàng)目中

2) 在jsp頁面中國導(dǎo)入標(biāo)簽庫

<%@tagliburi="標(biāo)簽庫聲明文件tld文件的標(biāo)記" PRefix="前綴"%>

3) 使用標(biāo)簽庫中的標(biāo)簽

核心標(biāo)簽庫:

<c:set />     保存數(shù)據(jù)到域?qū)ο笾?/p>

<c:out/>     從域中取出數(shù)據(jù)

<c:if/>       單條件判斷

<c:choose/> +<c:when/> + <c:otherwise/>  多條件判斷

<c:forEach />  遍歷數(shù)據(jù)

<c:forTokens/>  遍歷特殊字符串

<c:redirect/>   重定向

二、  自定義標(biāo)簽入門

1. 引入

向?yàn)g覽器輸出當(dāng)前客戶的ip地址(只能使用jsp標(biāo)簽)

2. 第一個(gè)自定義標(biāo)簽開發(fā)步驟

1)   編寫一個(gè)普通的java類,繼承SimpleTagSupport類,叫標(biāo)簽處理器類

package cn.xp.a_tag;import java.io.IOException;import javax.servlet.http.HttpServletRequest;import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.PageContext;import javax.servlet.jsp.tagext.SimpleTagSupport;/** * @author xiongpan *	1)繼承SimpleTagSupport類 */public class ShowIpTag extends SimpleTagSupport {	/**	 * 以下代碼在屏蔽的代碼在SimpleTagSupport中已經(jīng)做了不需要了	 private JspContext context;		 * 傳入pageContext		@Override		public void setJspContext(JspContext pc) {			this.context = pc;		}	 */	/**	 * 2)覆蓋doTag方法	 */	@Override	public void doTag() throws JspException, IOException {		PageContext pageContext = (PageContext)this.getJspContext();		HttpServletRequest request = (HttpServletRequest)pageContext.getRequest();		String ip = request.getRemoteHost();		JspWriter out = pageContext.getOut();		out.write("使用自定義標(biāo)簽輸出客戶的IP地址:"+ip);	}}

2)在web項(xiàng)目的WEB-INF目錄下建立xp.tld文件,這個(gè)tld叫標(biāo)簽庫的聲明文件。(參考核心標(biāo)簽庫的tld文件)

<?xml version="1.0" encoding="UTF-8"?><taglib version="2.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee web-jsptaglibrary_2_1.xsd"> <!-- 標(biāo)簽庫的版本 --> <tlib-version>1.1</tlib-version> <!-- 標(biāo)簽庫前綴 --> <short-name>xp</short-name> <!-- tld文件的唯一標(biāo)識  --> <uri>http://com.xp.cn</uri> <!-- 一個(gè)標(biāo)簽的聲明 --> <tag> <!-- 標(biāo)簽名稱 --> 	<name>showIp</name> 	<!-- 標(biāo)簽處理類的全名 --> 	<tag-class>cn.xp.a_tag.ShowIpTag</tag-class> 	<!-- 輸出標(biāo)簽體內(nèi)容格式 --> 	<body-content>scriptless</body-content> </tag></taglib>

3) 在jsp頁面的頭部導(dǎo)入自定義標(biāo)簽庫

<%@tagliburi="http://com.xp.cn" prefix="xp"%>

4) 在jsp中使用自定義標(biāo)簽

<xp:showIp></ xp:showIp>

1. 自定義標(biāo)簽的執(zhí)行過程

問題:http://localhost:8080/day14/01.hellotag.jsp 如何訪問到自定義標(biāo)簽?

前提: tomcat服務(wù)器啟動(dòng)時(shí),加載到每個(gè)web應(yīng)用,加載每個(gè)web應(yīng)用的WEB-INF目錄下的所有文件!!!例如。web.xml, tld文件!!!

1)訪問01.hellotag.jsp資源

2)tomcat服務(wù)器把jsp文件翻譯成java源文件->編譯class->構(gòu)造類對象->調(diào)用_jspService()方法

3)檢查jsp文件的taglib指令,是否存在一個(gè)名為http://gz.itcast.cn的tld文件。如果沒有,則報(bào)錯(cuò)

4)上一步已經(jīng)讀到xp.tld文件

5)讀到<xp:showIp> 到xp.tld文件中查詢是否存在<name>為showIp的<tag>標(biāo)簽

6)找到對應(yīng)的<tag>標(biāo)簽,則讀到<tag-class>內(nèi)容

7)得到 com.xp.a_tag.ShowIpTag

構(gòu)造ShowIpTag對象,然后調(diào)用ShowIpTag里面的方法

一、  自定義標(biāo)簽作用

1.  自定義標(biāo)簽處理器類的生命周期

SimpleTag接口:

void setJspContext(JspContextpc)  --設(shè)置pageContext對象,傳入pageContext(一定調(diào)用)

通過getJspCotext()方法得到pageContext對象

void setParent(JspTagparent)  --設(shè)置父標(biāo)簽對象,傳入父標(biāo)簽對象,如果沒有父標(biāo)簽,則不 調(diào)用此方法。通過getParent()方法得到父標(biāo)簽對象。

void    setXXX(值) --設(shè)置屬性值。

void setJspBody(JspFragmentjspBody) --設(shè)置標(biāo)簽體內(nèi)容。標(biāo)簽體內(nèi)容封裝到JspFragment對象中,然后傳入JspFragment對象。通過getJspBody()方法得到標(biāo)簽體內(nèi)容。如果沒有標(biāo)簽體內(nèi)容,則不會(huì)調(diào)用此方法

void doTag()--執(zhí)行標(biāo)簽時(shí)調(diào)用的方法。(一定調(diào)用)

2.  自定義標(biāo)簽的作用

1)控制標(biāo)簽體內(nèi)容是否輸出

2)控制標(biāo)簽余下內(nèi)容是否輸出

3)控制重復(fù)輸出標(biāo)簽體內(nèi)容

4)改變標(biāo)簽體內(nèi)容

package cn.xp.a_tag;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.SkipPageException;import javax.servlet.jsp.tagext.JspFragment;import javax.servlet.jsp.tagext.SimpleTagSupport;public class TagHandlerClass extends SimpleTagSupport {	//1.聲明屬性的成員變量		private Integer num;		//2.關(guān)鍵點(diǎn): 必須提供公開的setter方法,用于給屬性賦值		public void setNum(Integer num) {			this.num = num;		}		@Override		public void doTag() throws JspException, IOException {			System.out.println("執(zhí)行了標(biāo)簽");						/**			 * 1)控制標(biāo)簽內(nèi)容是否輸出			 *    輸出: 調(diào)用jspFrament.invoke();			 *    不輸出: 不調(diào)用jspFrament.invoke();			 */			//1.1 得到標(biāo)簽體內(nèi)容			JspFragment jspBody = this.getJspBody();			/**			 * 執(zhí)行invoke方法: 把標(biāo)簽體內(nèi)容輸出到指定的Writer對象中			 */			//1.2 往瀏覽器輸出內(nèi)容,writer為null就是默認(rèn)往瀏覽器輸出			//JspWriter out = this.getJspContext().getOut();			//jspBody.invoke(out);			jspBody.invoke(null);//等價(jià)于上面的代碼			/**			 * 3)控制重復(fù)輸出標(biāo)簽體內(nèi)容			 *     方法: 執(zhí)行多次jspBody.invoke()方法			 */			/*for(int i=1;i<=num;i++){				jspBody.invoke(null);			}*/			/**			 * 4)改變標(biāo)簽體內(nèi)容			 */			//4.1 創(chuàng)建StringWriter臨時(shí)容器			/*StringWriter sw = new StringWriter();			//4.2 把標(biāo)簽體拷貝到臨時(shí)容器			jspBody.invoke(sw);			//4.3 從臨時(shí)容器中得到標(biāo)簽體內(nèi)容			String content = sw.toString();			//4.4 改變內(nèi)容			content = content.toLowerCase();			//System.out.println(content);			//4.5 把改變的內(nèi)容輸出到瀏覽器			//jspBody.invoke(null); 不能使用此方式輸出,因?yàn)閖sbBody沒有改變過			this.getJspContext().getOut().write(content);*/			/**			 * 2)控制標(biāo)簽余下內(nèi)容是否輸出			 *   輸出: 什么都不干!			 *   不輸出: 拋出SkipPageException異常			 */			throw new SkipPageException();		}	}

5)帶屬性的標(biāo)簽

在標(biāo)簽處理器中添加一個(gè)成語變量和setter方法      

   //1.聲明屬性的成員變量

   privateInteger num;

   //2.關(guān)鍵點(diǎn): 必須提供公開的setter方法,用于給屬性賦值

   publicvoid setNum(Integer num) {

      this.num= num;

   }

   6)輸出標(biāo)簽體內(nèi)容格式

JSP:   在傳統(tǒng)標(biāo)簽中使用的。可以寫和執(zhí)行jsp的java代碼。

scriptless:  標(biāo)簽體不可以寫jsp的java代碼

empty:    必須是空標(biāo)簽。

tagdependent : 標(biāo)簽體內(nèi)容可以寫jsp的java代碼,但不會(huì)執(zhí)行。

四、自定義標(biāo)簽案例

1.自定義登錄標(biāo)簽

package cn.xp.b_cases;import java.io.IOException;import javax.servlet.http.HttpServletResponse;import javax.servlet.jsp.JspException;import javax.servlet.jsp.JspWriter;import javax.servlet.jsp.PageContext;import javax.servlet.jsp.tagext.SimpleTagSupport;/** * 自定義登錄標(biāo)簽 * @author xiongpan */public class LoginTag extends SimpleTagSupport {	private String username;	private String passWord;	public void setUsername(String username) {		this.username = username;	}	public void setPassword(String password) {		this.password = password;	}	@Override	public void doTag() throws JspException, IOException {		 HttpServletResponse response = (HttpServletResponse)((PageContext)this.getJspContext()).getResponse();		 //設(shè)置輸出內(nèi)容類型和編碼		 response.setContentType("text/html;charset=utf-8");		 String html = "";		 html += "<center><h3>用戶登陸頁面</h3></center>";		 html += "<table border='1' align='center' width='400px'>";		 html += "	<tr>";		 html += "		<th>用戶名:</th>";		 html += "		<td><input type='text' name='"+username+"'/></td>";		 html += "	</tr>";		 html += "	<tr>";		 html += "		<th>密碼:</th>";		 html += "		<td><input type='password' name='"+password+"'/></td>";		 html += "	</tr>";		 html += "	<tr>";		 html += "		<td colspan='2' align='center'><input type='submit' value='登陸'/> <input type='reset' value='重置'/></td>";		 html += "	</tr>";		 html += "</table>";		JspWriter out = this.getJspContext().getOut();		out.write(html);	}}<tag>    <name>login</name>    <tag-class>cn.xp.b_cases.LoginTag</tag-class>    <body-content>scriptless</body-content>    <attribute>    	<name>username</name>    	<required>true</required>    	<rtexprvalue>false</rtexprvalue>    </attribute>    <attribute>    	<name>password</name>    	<required>true</required>    	<rtexprvalue>false</rtexprvalue>    </attribute>  </tag><%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@taglib uri="http://com.xp.cn" prefix="xp"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>     <title>登陸頁面</title>    </head>    <body>  <form action="" method="post">   <xp:login password="pwd" username="user"></xp:login>    </form>  </body></html>

2.核心標(biāo)簽庫案例

If標(biāo)簽庫

package cn.xp.b_cases;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.SimpleTagSupport;public class IfTag extends SimpleTagSupport {	private boolean test;	public void setTest(boolean test) {		this.test = test;	}	@Override	public void doTag() throws JspException, IOException {		//根據(jù)test的返回值決定是否輸出標(biāo)簽體內(nèi)容		if(test){			this.getJspBody().invoke(null);		}	}}<tag>    <name>if</name>    <tag-class>cn.xp.b_cases.IfTag</tag-class>    <body-content>scriptless</body-content>    <attribute>    	<name>test</name>    	<required>true</required>    	<rtexprvalue>true</rtexprvalue>    </attribute>  </tag>  <xp:if test="${10>5}">    	條件成立</xp:if>package cn.xp.b_cases;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.SimpleTagSupport;public class ChooseTag extends SimpleTagSupport {	//不是屬性,而是臨時(shí)變量	private boolean flag;	public boolean isFlag() {		return flag;	}	public void setFlag(boolean flag) {		this.flag = flag;	}	@Override	public void doTag() throws JspException, IOException {		//輸出標(biāo)簽體內(nèi)容		this.getJspBody().invoke(null);	}}  <tag>    <name>choose</name>    <tag-class>cn.xp.b_cases.ChooseTag</tag-class>    <body-content>scriptless</body-content>  </tag>WhenTagpackage cn.xp.b_cases;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.SimpleTagSupport;public class WhenTag extends SimpleTagSupport {	private boolean test;		public void setTest(boolean test) {		this.test = test;	}	@Override	public void doTag() throws JspException, IOException {		//根據(jù)test的返回值決定是否輸出標(biāo)簽體內(nèi)容		if(test){			this.getJspBody().invoke(null);		}		//獲取父標(biāo)簽		ChooseTag parent = (ChooseTag)this.getParent();		parent.setFlag(test);	}}  <tag>    <name>when</name>    <tag-class>cn.xp.b_cases.WhenTag</tag-class>    <body-content>scriptless</body-content>    <attribute>    	<name>test</name>    	<required>true</required>    	<rtexprvalue>true</rtexprvalue>    </attribute>  </tag>OtherwiseTagpackage cn.xp.b_cases;import java.io.IOException;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.SimpleTagSupport;public class OtherwiseTag extends SimpleTagSupport {	@Override	public void doTag() throws JspException, IOException {		//通過父標(biāo)簽傳遞,when標(biāo)簽中test的值		//獲取父標(biāo)簽		ChooseTag parent = (ChooseTag)this.getParent();		boolean test = parent.isFlag();				if(!test){			this.getJspBody().invoke(null);		}	}}<tag>    <name>otherwise</name>    <tag-class>cn.xp.b_cases.OtherwiseTag</tag-class>    <body-content>scriptless</body-content>  </tag><xp:otherwise>			條件不成立		</xp:otherwise>  package cn.xp.b_cases;import java.io.IOException;import java.util.Collection;import java.util.List;import java.util.Map;import javax.servlet.jsp.JspException;import javax.servlet.jsp.PageContext;import javax.servlet.jsp.tagext.SimpleTagSupport;public class ForEachTag extends SimpleTagSupport {	private Object items;//需要遍歷的數(shù)據(jù).List和map	private String var;//每個(gè)元素的名稱	public void setItems(Object items) {		this.items = items;	}	public void setVar(String var) {		this.var = var;	}	@Override	public void doTag() throws JspException, IOException {		//遍歷items數(shù)據(jù)		//List		/*PageContext pageContext = (PageContext)this.getJspContext();		if(items instanceof List){			List list = (List)items;			for (Object object : list) {				//把每個(gè)對象放入域?qū)ο笾?pageContext)				pageContext.setAttribute(var, object);				//顯示標(biāo)簽體內(nèi)容				this.getJspBody().invoke(null);			}		}		//Map		if(items instanceof Map){			Map map = (Map)items;			Set<Entry> entrySet = map.entrySet();			for(Entry entry :entrySet){				//把每個(gè)對象放入域?qū)ο笾?pageContext)				pageContext.setAttribute(var, entry);				//顯示標(biāo)簽體內(nèi)容				this.getJspBody().invoke(null);			}		}*/		//簡化代碼		//思路: 			//1)list         -> Collection			//2) map.entrySet -> Collection		PageContext pageContext = (PageContext)this.getJspContext();		Collection colls = null;		if(items instanceof List){			colls = (List)items;		}		if(items instanceof Map){			Map map = (Map)items;			colls = map.entrySet();		}		for(Object object:colls){			//把每個(gè)對象放入域?qū)ο笾?pageContext)			pageContext.setAttribute(var, object);			//顯示標(biāo)簽體內(nèi)容			this.getJspBody().invoke(null);		}	}}package cn.xp.b_cases;public class Student {	private String name1;	private int age;	public String getName() {		return name1;	}	public void setName(String name) {		this.name1 = name;	}	public int getAge() {		return age;	}	public void setAge(int age) {		this.age = age;	}	public Student(String name, int age) {		super();		this.name1 = name;		this.age = age;	}	public Student() {		super();		// TODO Auto-generated constructor stub	}		}<tag>    <name>forEach</name>    <tag-class>cn.xp.b_cases.ForEachTag</tag-class>    <body-content>scriptless</body-content>    <attribute>    	<name>items</name>    	<required>true</required>    	<rtexprvalue>true</rtexprvalue>    </attribute>    <attribute>    	<name>var</name>    	<required>true</required>    	<rtexprvalue>false</rtexprvalue>    </attribute>  </tag><%@ page language="java" import="java.util.*,com.xp.b_cases.*" pageEncoding="utf-8"%><%@taglib uri="http://com.xp.cn" prefix="xp" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>     <title>forEach標(biāo)簽</title>    </head>  <body>    <%       //保存數(shù)據(jù)       //List     	List<Student>  list = new ArrayList<Student>();     	list.add(new Student("rose",18));     	list.add(new Student("jack",28));     	list.add(new Student("lucy",38));     	//放入域中     	pageContext.setAttribute("list",list);     	     	//Map     	Map<String,Student> map = new HashMap<String,Student>();     	map.put("100",new Student("mark",20));     	map.put("101",new Student("maxwell",30));     	map.put("102",new Student("narci",40));     	//放入域中     	pageContext.setAttribute("map",map);     %>          <itcast:forEach items="${list}" var="student">     		姓名:${student.name } - 年齡:${student.age }<br/>     </itcast:forEach>          <hr/>          <itcast:forEach items="${map}" var="entry">     	  編號:${entry.key} - 姓名:${entry.value.name} - 年齡:${entry.value.age }<br/>     </itcast:forEach>  </body></html>

五、mvc開發(fā)模式

1.Javabean

JavaBean,是一種開發(fā)規(guī)范,可以說是一種技術(shù)。

JavaBean就是一個(gè)普通的java類。只有符合以下規(guī)定才能稱之為javabean:

1)必須提供無參數(shù)的構(gòu)造方法

2)類中屬性都必須私有化(private)

3)該類提供公開的getter 和setter方法

2.JavaBean的作用: 用于封裝數(shù)據(jù),保存數(shù)據(jù)。

訪問javabean只能使用getter和setter方法

JavaBean的使用場景:

1)項(xiàng)目中用到實(shí)體對象(entity)符合javabean規(guī)范

2)EL表達(dá)式訪問對象屬性。${student.name}  調(diào)用getName()方法,符合javabean規(guī)范。

3)jsp標(biāo)簽中的屬性賦值。 setNum(Integer num)。符合javabean規(guī)范。

4)jsp頁面中使用javabean。符合javabean規(guī)范

問題:

以下方法哪些屬于javabean的規(guī)范的方法? 答案 :( 1,3,5,6  )

注意: boolean類型的get方法名稱叫 isXXX()方法

1)getName()   2)getName(String name)

3)setName(String name)   4)setName()

5) setFlag(boolean flag)   6)isFlag()

3.Javabean的屬性

l  JavaBean的屬性可以是任意類型,并且一個(gè)JavaBean可以有多個(gè)屬性。每個(gè)屬性通常都需要具有相應(yīng)的setter、 getter方法,setter方法稱為屬性修改器,getter方法稱為屬性訪問器。

l  屬性修改器必須以小寫的set前綴開始,后跟屬性名,且屬性名的第一個(gè)字母要改為大寫,例如,name屬性的修改器名稱為setName,password屬性的修改器名稱為setPassword。

l  屬性訪問器通常以小寫的get前綴開始,后跟屬性名,且屬性名的第一個(gè)字母也要改為大寫,例如,name屬性的訪問器名稱為getName,password屬性的訪問器名稱為getPassword。

l  一個(gè)JavaBean的某個(gè)屬性也可以只有set方法或get方法,這樣的屬性通常也稱之為只寫、只讀屬性。

4.在jsp中使用javabean

JSP技術(shù)提供了三個(gè)關(guān)于JavaBean組件的動(dòng)作元素,即JSP標(biāo)簽,它們分別為:

<jsp:useBean>標(biāo)簽:用于在JSP頁面中查找或?qū)嵗粋€(gè)JavaBean組件。

<jsp:setProperty>標(biāo)簽:用于在JSP頁面中設(shè)置一個(gè)JavaBean組件的屬性。

<jsp:getProperty>標(biāo)簽:用于在JSP頁面中獲取一個(gè)JavaBean組件的屬性。

<%@ page language="java" import="java.util.*,com.xp.b_cases.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>     <title>jsp頁面中使用javabean</title>    </head>  <body>    <%    	//Student stu = new Student();    	//stu.setName("rose");    	//stu.setAge(20);    	//stu.getName();     %>     <%---創(chuàng)建對象 --%>     <jsp:useBean id="stu" class="com.xp.b_cases.Student"></jsp:useBean>     <%--賦值 --%>     <jsp:setProperty property="name" name="stu" value="jacky"/>       <%--獲取--%>    <jsp:getProperty property="name" name="stu"/>  </body></html>6.web開發(fā)模式

MVC開發(fā)模式:

Model - JavaBean實(shí)現(xiàn)。用于封裝業(yè)務(wù)數(shù)據(jù)

View - Jsp實(shí)現(xiàn)。用于顯示數(shù)據(jù)

Controller-  servlet實(shí)現(xiàn)。用于控制model和view

三層結(jié)構(gòu):

dao層: 和數(shù)據(jù)訪問相關(guān)的操作

service層: 和業(yè)務(wù)邏輯相關(guān)的操作

web層: 和用戶直接交互相關(guān)的操作(傳接參數(shù),跳轉(zhuǎn)頁面)

六、mvc編碼實(shí)戰(zhàn)

第一步:導(dǎo)入必備的jar包

dom4j-1.6.1.jar    jaxen-1.1-beta-6.jar

第二步:根據(jù)需求創(chuàng)建實(shí)體類

package com.xp.contactSys_web.entity;/** * Contact實(shí)體 * @author xiongpan */public class Contact {	private String id;	private String name;	private String gender;	private int age;	private String phone;	private String email;	private String QQ;	public String getId() {		return id;	}	public void setId(String id) {		this.id = id;	}	public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public String getGender() {		return gender;	}	public void setGender(String gender) {		this.gender = gender;	}	public int getAge() {		return age;	}	public void setAge(int age) {		this.age = age;	}	public String getPhone() {		return phone;	}	public void setPhone(String phone) {		this.phone = phone;	}	public String getEmail() {		return email;	}	public void setEmail(String email) {		this.email = email;	}	public String getQq() {		return qq;	}	public void setQq(String qq) {		this.qq = qq;	}	@Override	public String toString() {		return "Contact [age=" + age + ", email=" + email + ", gender="				+ gender + ", id=" + id + ", name=" + name + ", phone=" + phone				+ ", qq=" + qq + "]";	}}第三步:編寫聯(lián)系人接口ContactDaopackage com.xp.contactSys_web.dao;import java.util.List;import com.xp.contactSys_web.entity.Contact;/** * 聯(lián)系人的接口 */public interface ContactDao {	public void addContact(Contact contact);//添加聯(lián)系人	public void updateContact(Contact contact);//修改聯(lián)系人	public void deleteContact(String id);//刪除聯(lián)系人	public List<Contact> findAll();  //查詢所有聯(lián)系人	public Contact findById(String id);//根據(jù)編號查詢聯(lián)系人	public boolean checkContact(String name);//根據(jù)姓名查詢是否重復(fù)}第四步:導(dǎo)入封裝好的xml工具庫package com.xp.contactSys_web.util;import java.io.File;import java.io.FileOutputStream;import org.dom4j.Document;import org.dom4j.DocumentException;import org.dom4j.io.OutputFormat;import org.dom4j.io.SAXReader;import org.dom4j.io.XMLWriter;/** * xml的工具類 */public class XMLUtil {	/**	 * 讀取xml文檔方法	 * @return	 */	public static Document getDocument(){		try {			Document doc = new SAXReader().read(new File("e:/contact.xml"));			return doc;		} catch (DocumentException e) {			e.printStackTrace();			throw new RuntimeException(e);		}	}		/**	 * 寫出到xml文檔中	 */	public static void write2xml(Document doc){		try {			FileOutputStream out = new FileOutputStream("e:/contact.xml");			OutputFormat format = OutputFormat.createPrettyPrint();			format.setEncoding("utf-8");			XMLWriter writer = new XMLWriter(out,format);			writer.write(doc);			writer.close();		} catch (Exception e) {			e.printStackTrace();			throw new RuntimeException(e);		}	}}第五步:編寫聯(lián)系人接口實(shí)現(xiàn)類package com.xp.contactSys_web.dao.impl;import java.io.File;import java.util.ArrayList;import java.util.List;import java.util.UUID;import org.dom4j.Document;import org.dom4j.DocumentHelper;import org.dom4j.Element;import com.xp.contactSys_web.dao.ContactDao;import com.xp.contactSys_web.entity.Contact;import com.xp.contactSys_web.util.XMLUtil;public class ContactDaoImpl implements ContactDao {	/**	 * 添加聯(lián)系人	 */	public void addContact(Contact contact) {		try {			File file = new File("e:/contact.xml");			Document doc = null;			Element rootElem = null;			if (!file.exists()) {				/**				 * 需求: 把contact對象保存到xml文件中				 */				// 如果沒有xml文件,則創(chuàng)建xml文件				doc = DocumentHelper.createDocument();				// 創(chuàng)建根標(biāo)簽				rootElem = doc.addElement("contactList");			} else {				// 如果有xml文件,則讀取xml文件				doc = XMLUtil.getDocument();				// 如果有xml文件,讀取根標(biāo)簽				rootElem = doc.getRootElement();			}			// 添加contact標(biāo)簽			/**			 * <contact id="1"> <name>eric</name> <gender>男</gender>			 * <age>20</age> <phone>1343333</phone> <email>[email protected]</email>			 * <qq>554444</qq> </contact>			 */			Element contactElem = rootElem.addElement("contact");			/**			 * 由系統(tǒng)自動(dòng)生成隨機(jī)且唯一的ID值,賦值給聯(lián)系人			 */			String uuid = UUID.randomUUID().toString().replace("-", "");			contactElem.addAttribute("id", uuid);			contactElem.addElement("name").setText(contact.getName());			contactElem.addElement("gender").setText(contact.getGender());			contactElem.addElement("age").setText(contact.getAge() + "");			contactElem.addElement("phone").setText(contact.getPhone());			contactElem.addElement("email").setText(contact.getEmail());			contactElem.addElement("qq").setText(contact.getQq());			// 把Document寫出到xml文件			XMLUtil.write2xml(doc);		} catch (Exception e) {			e.printStackTrace();			throw new RuntimeException(e);		}	}	/**	 * 刪除聯(lián)系人	 */	public void deleteContact(String id) {		try {			// 1.讀取xml文件			Document doc = XMLUtil.getDocument();			// 2.查詢需要?jiǎng)h除id的contact			Element contactElem = (Element) doc					.selectSingleNode("//contact[@id='" + id + "']");			// 刪除標(biāo)簽			if (contactElem != null) {				contactElem.detach();			}			// 3.把Document寫出到xml文件			XMLUtil.write2xml(doc);		} catch (Exception e) {			e.printStackTrace();			throw new RuntimeException(e);		}	}	/**	 * 查詢所有聯(lián)系人	 */	public List<Contact> findAll() {		// 1.讀取xml文件		Document doc = XMLUtil.getDocument();		// 2.創(chuàng)建List對象		List<Contact> list = new ArrayList<Contact>();		// 3.讀取contact標(biāo)簽		List<Element> conList = (List<Element>) doc.selectNodes("//contact");		for (Element e : conList) {			// 創(chuàng)建COntact對象			Contact c = new Contact();			c.setId(e.attributeValue("id"));			c.setName(e.elementText("name"));			c.setGender(e.elementText("gender"));			c.setAge(Integer.parseInt(e.elementText("age")));			c.setPhone(e.elementText("phone"));			c.setEmail(e.elementText("email"));			c.setQq(e.elementText("qq"));			// 把Contact放入list中			list.add(c);		}		return list;	}	/**	 * 根據(jù)編號查詢聯(lián)系人	 */	public Contact findById(String id) {		Document doc = XMLUtil.getDocument();		Element e = (Element) doc.selectSingleNode("//contact[@id='" + id				+ "']");		Contact c = null;		if (e != null) {			// 創(chuàng)建COntact對象			c = new Contact();			c.setId(e.attributeValue("id"));			c.setName(e.elementText("name"));			c.setGender(e.elementText("gender"));			c.setAge(Integer.parseInt(e.elementText("age")));			c.setPhone(e.elementText("phone"));			c.setEmail(e.elementText("email"));			c.setQq(e.elementText("qq"));		}		return c;	}	/**	 * 修改聯(lián)系人	 */	public void updateContact(Contact contact) {		/**		 * 需求: 修改id值為2的聯(lián)系人 1)查詢id值為2的contact標(biāo)簽 2)修改contact標(biāo)簽的內(nèi)容		 */		try {			// 1.讀取xml文件			Document doc = XMLUtil.getDocument();			Element contactElem = (Element) doc					.selectSingleNode("//contact[@id='" + contact.getId()							+ "']");			// 2.修改contact標(biāo)簽內(nèi)容			contactElem.element("name").setText(contact.getName());			contactElem.element("gender").setText(contact.getGender());			contactElem.element("age").setText(contact.getAge() + "");			contactElem.element("phone").setText(contact.getPhone());			contactElem.element("email").setText(contact.getEmail());			contactElem.element("qq").setText(contact.getQq());			// 3.把Document寫出到xml文件			XMLUtil.write2xml(doc);		} catch (Exception e) {			e.printStackTrace();			throw new RuntimeException(e);		}	}	public static void main(String[] args) {		// 測試UUID		String uuid = UUID.randomUUID().toString().replace("-", "");		System.out.println(uuid);	}	/**	 * true:重復(fù) false:不重復(fù)	 */	public boolean checkContact(String name) {		// 查詢name標(biāo)簽的內(nèi)容和傳入的name值是否一致?		Document doc = XMLUtil.getDocument();		Element nameElem = (Element) doc.selectSingleNode("//name[text()='"				+ name + "']");		if (nameElem != null) {			return true;		} else {			return false;		}	}}第六步:編寫業(yè)務(wù)實(shí)現(xiàn)類接口package com.xp.contactSys_web.service;import java.util.List;import com.xp.contactSys_web.entity.Contact;import com.xp.contactSys_web.exception.NameRepeatException;public interface ContactService {	public void addContact(Contact contact)throws NameRepeatException;//添加聯(lián)系人	public void updateContact(Contact contact);//修改聯(lián)系人	public void deleteContact(String id);//刪除聯(lián)系人	public List<Contact> findAll();  //查詢所有聯(lián)系人	public Contact findById(String id);//根據(jù)編號查詢聯(lián)系人}第七步:編寫業(yè)務(wù)接口實(shí)現(xiàn)類package com.xp.contactSys_web.service.impl;import java.util.List;import com.xp.contactSys_web.dao.ContactDao;import com.xp.contactSys_web.dao.impl.ContactDaoImpl;import com.xp.contactSys_web.entity.Contact;import com.xp.contactSys_web.exception.NameRepeatException;public class ContactServiceImpl {ContactDao dao = new ContactDaoImpl();	public void addContact(Contact contact) throws NameRepeatException {		//執(zhí)行業(yè)務(wù)邏輯判斷		if(dao.checkContact(contact.getName())){			//重復(fù)			/**			 * 注意: 如果業(yè)務(wù)層方法出現(xiàn)任何業(yè)務(wù)異常,則返回標(biāo)記(自定義異常)到servlet			 */			throw new NameRepeatException("姓名重復(fù),不可使用");		}		//如果不重復(fù),才執(zhí)行添加方法		dao.addContact(contact);	}	public void deleteContact(String id) {		dao.deleteContact(id);	}	public List<Contact> findAll() {		return dao.findAll();	}	public Contact findById(String id) {		return dao.findById(id);	}	public void updateContact(Contact contact) {		dao.updateContact(contact);	}}package com.xp.contactSys_web.exception;/** * 姓名重復(fù)自定義異常類 */public class NameRepeatException extends Exception {	private static final long serialVersionUID = 1L;	public NameRepeatException(String msg){		super(msg);	}}第八步:分別編寫聯(lián)系人增、刪、改、查得Servletpackage com.xp.contactSys_web.servlet;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.xp.contactSys_web.entity.Contact;import com.xp.contactSys_web.service.ContactService;import com.xp.contactSys_web.service.impl.ContactServiceImpl;public class ListContactServlet extends HttpServlet {	private static final long serialVersionUID = 1L;	public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		//1.從xml中讀取出聯(lián)系人數(shù)據(jù)		ContactService service = new ContactServiceImpl();		List<Contact> list = service.findAll();		//2.把結(jié)果保存到域?qū)ο笾?	request.setAttribute("contacts", list);		//3.跳轉(zhuǎn)到j(luò)sp頁面		request.getRequestDispatcher("/listContact.jsp").forward(request, response);			}	public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		doGet(request, response);	}}package com.xp.contactSys_web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.xp.contactSys_web.entity.Contact;import com.xp.contactSys_web.service.ContactService;import com.xp.contactSys_web.service.impl.ContactServiceImpl;public class QueryContactServlet extends HttpServlet {	private static final long serialVersionUID = 1L;	public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		//1.接收id		String id = request.getParameter("id");				//2.調(diào)用service根據(jù)id查詢聯(lián)系人的方法		ContactService service = new ContactServiceImpl();		Contact contact = service.findById(id);				//3.把查詢的結(jié)果保存到request域中		request.setAttribute("contact", contact);				//4.跳轉(zhuǎn)到修改聯(lián)系人的頁面		request.getRequestDispatcher("/updateContact.jsp").forward(request, response);	}	public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		doGet(request, response);	}}package com.xp.contactSys_web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.xp.contactSys_web.entity.Contact;import com.xp.contactSys_web.exception.NameRepeatException;import com.xp.contactSys_web.service.ContactService;import com.xp.contactSys_web.service.impl.ContactServiceImpl;public class AddContactServlet extends HttpServlet {	public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		request.setCharacterEncoding("utf-8");		//1.接收參數(shù)		String name = request.getParameter("name");		String gender = request.getParameter("gender");		String age = request.getParameter("age");		String phone = request.getParameter("phone");		String email = request.getParameter("email");		String qq = request.getParameter("qq");				//封裝成Contact對象		Contact contact = new Contact();		contact.setName(name);		contact.setGender(gender);		contact.setAge(Integer.parseInt(age));		contact.setPhone(phone);		contact.setEmail(email);		contact.setQq(qq);				ContactService service = new ContactServiceImpl();		//2.調(diào)用dao類的添加聯(lián)系人的方法		try {			service.addContact(contact);		} catch (NameRepeatException e) {			//處理自定義業(yè)務(wù)異常			request.setAttribute("msg", e.getMessage());			request.getRequestDispatcher("/addContact.jsp").forward(request, response);			return;		} 						//3.跳轉(zhuǎn)到查詢聯(lián)系人的頁面		response.sendRedirect(request.getContextPath()+"/ListContactServlet");	}	public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		doGet(request, response);	}}package com.xp.contactSys_web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.xp.contactSys_web.service.ContactService;import com.xp.contactSys_web.service.impl.ContactServiceImpl;/** * 刪除聯(lián)系人的邏輯 * */public class DeleteContactServlet extends HttpServlet {	public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		//在火狐瀏覽器中以Get方式提交帶參數(shù)的數(shù)據(jù),會(huì)重復(fù)提交兩次。		System.out.println("刪除聯(lián)系人");		//1.接收id		String id = request.getParameter("id");				//2.調(diào)用service刪除聯(lián)系人的方法		ContactService service = new ContactServiceImpl();		service.deleteContact(id);				//3.跳轉(zhuǎn)到查詢聯(lián)系人的頁面		response.sendRedirect(request.getContextPath()+"/ListContactServlet");	}	public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		doGet(request, response);	}}package com.xp.contactSys_web.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.xp.contactSys_web.entity.Contact;import com.xp.contactSys_web.service.ContactService;import com.xp.contactSys_web.service.impl.ContactServiceImpl;/** * 修改聯(lián)系人的邏輯 */public class UpdateContactServlet extends HttpServlet {	private static final long serialVersionUID = 1L;	public void doGet(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		request.setCharacterEncoding("utf-8");		//1.接收參數(shù)		String id = request.getParameter("id");		String name = request.getParameter("name");		String gender = request.getParameter("gender");		String age = request.getParameter("age");		String phone = request.getParameter("phone");		String email = request.getParameter("email");		String qq = request.getParameter("qq");				//封裝成Contact對象		Contact contact = new Contact();		contact.setId(id);		contact.setName(name);		contact.setGender(gender);		contact.setAge(Integer.parseInt(age));		contact.setPhone(phone);		contact.setEmail(email);		contact.setQq(qq);				//2.調(diào)用service修改聯(lián)系人的方法		ContactService service = new ContactServiceImpl();		service.updateContact(contact);				//3.跳轉(zhuǎn)到查詢聯(lián)系人的頁面		response.sendRedirect(request.getContextPath()+"/ListContactServlet");			}	public void doPost(HttpServletRequest request, HttpServletResponse response)			throws ServletException, IOException {		doGet(request, response);	}}<%@ page language="java" import="java.util.*,com.xp.contactSys_web.entity.*" pageEncoding="utf-8"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>查詢所有聯(lián)系人</title><style type="text/CSS">	table td{		/*文字居中*/		text-align:center;	}	/*合并表格的邊框*/	table{		border-collapse:collapse;	}</style></head><body><center><h3>查詢所有聯(lián)系人(jsp版本)</h3></center><table align="center" border="1" width="700px">	<tr>    	<th>編號</th>        <th>姓名</th>        <th>性別</th>        <th>年齡</th>        <th>電話</th>        <th>郵箱</th>        <th>QQ</th>        <th>操作</th>    </tr>    <c:forEach items="${contacts}" var="con" varStatus="varSta">    <tr>    	<td>${varSta.count }</td>        <td>${con.name }</td>        <td>${con.gender }</td>        <td>${con.age }</td>        <td>${con.phone }</td>        <td>${con.email }</td>        <td>${con.qq }</td>        <td><a href="${pageContext.request.contextPath }/QueryContactServlet?id=${con.id}">修改</a> <a href="${pageContext.request.contextPath }/DeleteContactServlet?id=${con.id}">刪除</a></td>    </tr>    </c:forEach>    <tr>    	<td colspan="8" align="center"><a href="${pageContext.request.contextPath }/addContact.jsp">[添加聯(lián)系人]</a></td>    </tr></table></body></html><%@ page language="java" import="java.util.*,com.xp.contactSys_web.entity.*" pageEncoding="utf-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>添加聯(lián)系人</title></head><body><center><h3>添加聯(lián)系人</h3></center><form action="${pageContext.request.contextPath }/AddContactServlet" method="post"><table align="center" border="1" width="400px">    <tr>    	<th>姓名</th>        <td><input type="text" name="name"/><font color="red">${msg }</font></td>    </tr>    <tr>    	<th>性別</th>        <td>        <input type="radio" name="gender" value="男"/>男        <input type="radio" name="gender" value="女"/>女        </td>    </tr>    <tr>    	<th>年齡</th>        <td><input type="text" name="age"/></td>    </tr>    <tr>    	<th>電話</th>        <td><input type="text" name="phone"/></td>    </tr>    <tr>    	<th>郵箱</th>        <td><input type="text" name="email"/></td>    </tr>    <tr>    	<th>QQ</th>        <td><input type="text" name="qq"/></td>    </tr>    <tr>        <td colspan="2" align="center">        <input type="submit" value="保存"/>         <input type="reset" value="重置"/></td>    </tr></table></form></body></html><%@ page language="java" import="java.util.*,com.xp.contactSys_web.entity.*" pageEncoding="utf-8"%><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>修改聯(lián)系人</title></head><body><center><h3>修改聯(lián)系人</h3></center><form action="${pageContext.request.contextPath }/UpdateContactServlet" method="post"><input type="hidden" name="id" value="${contact.id }"/><table align="center" border="1" width="300px">    <tr>    	<th>姓名</th>        <td><input type="text" name="name" value="${contact.name }"/></td>    </tr>    <tr>    	<th>性別</th>        <td>        <input type="radio" name="gender" value="男"  <c:if test="${contact.gender=='男' }">checked="checked"</c:if> />男        <input type="radio" name="gender" value="女"  <c:if test="${contact.gender=='女' }">checked="checked"</c:if> />女        </td>    </tr>    <tr>    	<th>年齡</th>        <td><input type="text" name="age" value="${contact.age }"/></td>    </tr>    <tr>    	<th>電話</th>        <td><input type="text" name="phone" value="${contact.phone }"/></td>    </tr>    <tr>    	<th>郵箱</th>        <td><input type="text" name="email" value="${contact.email }"/></td>    </tr>    <tr>    	<th>QQ</th>        <td><input type="text" name="qq" value="${contact.qq }"/></td>    </tr>    <tr>        <td colspan="2" align="center">        <input type="submit" value="保存"/>         <input type="reset" value="重置"/></td>    </tr></table></form></body></html>
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 久久久青| 99精品视频久久精品视频 | 国产成人在线视频 | 欧美三日本三级少妇三级99观看视频 | 成人福利在线免费观看 | 99ri在线| 国产99久久精品一区二区 | 亚洲日韩精品欧美一区二区 | 高潮激情aaaaa免费看 | 欧美成人影院 | 中文字幕 亚洲一区 | 午夜看毛片| 国产女同玩人妖 | 在线小视频国产 | 精品一区二区三区在线观看国产 | 欧美中文字幕一区二区三区亚洲 | h色网站免费观看 | 国产亚洲精品综合一区91 | 成人男女啪啪免费观看网站四虎 | 男女做性免费网站 | 亚洲成人精品久久 | 色无极影院亚洲 | 欧美日韩亚洲另类 | 久久亚洲精品视频 | 斗破苍穹在线免费 | 一级视频在线播放 | 免费播放欧美毛片 | 日本黄色免费片 | 中文字幕免费播放 | 国产乱色精品成人免费视频 | 黄色片免费在线 | 亚洲国产精品高潮呻吟久久 | 叉逼视频 | 国产精品欧美久久久久一区二区 | 4480午夜 | 91午夜少妇三级全黄 | 国产91久久久久久 | 制服丝袜成人动漫 | 欧美一级高潮 | 深夜免费观看视频 | 日本爽快片100色毛片视频 |