java數(shù)據(jù)庫開發(fā)第7章jdbc結(jié)合servlet與jsp的應(yīng)用_第1頁
java數(shù)據(jù)庫開發(fā)第7章jdbc結(jié)合servlet與jsp的應(yīng)用_第2頁
java數(shù)據(jù)庫開發(fā)第7章jdbc結(jié)合servlet與jsp的應(yīng)用_第3頁
java數(shù)據(jù)庫開發(fā)第7章jdbc結(jié)合servlet與jsp的應(yīng)用_第4頁
java數(shù)據(jù)庫開發(fā)第7章jdbc結(jié)合servlet與jsp的應(yīng)用_第5頁
已閱讀5頁,還剩48頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)

文檔簡介

第7 JDBC結(jié)合Servlet與JSP的應(yīng)MyEclipse5.5Tomcat6.0MySQL5.1。ServletServlet的程序來完成的。ServletJava應(yīng)用程序。Servlet由WebJava應(yīng)Web應(yīng)用的主要模式是客戶端-服務(wù)端模式。即客戶端發(fā)出某種請求,服務(wù)端接受請求,并針有的優(yōu)勢,和其他的站技術(shù)相比,Servlet的優(yōu)點主要有以下幾點:很大的開銷,于此同時,效率將受到很大的影響。ServletCGI的效率問題。ServletJava語言編寫ServletJava編寫的,ServletAPIServlet是在哪個系統(tǒng)平臺上編譯的,Java虛擬機(jī)。ServletServletjavax.servlet.Servlet接口的類。Servlet接口規(guī)定了特定的方法來處理特定的請ServletHTTP規(guī)范基礎(chǔ)上的。HTTP1.1OPTIONS,GET,POST,HEAD,PUT,DELETE以及TRACE等7種Web方式。各方式的意義為:GET表示查詢信息,URL中可以附帶少量的參數(shù)信息,但是URL總長度過255個字HTTPPOSTServlet中對HEAD表示查詢文檔頭信息,服務(wù)器會返回文件類型,長度,最后修改時間等信息。該方式很doXxx((HttpServletRequestrequest,HttpServletResponseresponse)doGet,doPost等。參數(shù)HttpServletRequestHttpServletResponse分別為客戶端請求與服務(wù)器端響應(yīng)。request)ServletServletjavax.servlet.http.HttpServlet類。HttpServlet importjava.io.*;importpublicclassUseServletextendsHttpServlet importjava.io.*;importpublicclassUseServletextendsHttpServlet//Servletpublicvoiddestroy(){}//以GET方 頁面時執(zhí)行該函數(shù)。/處理方法為HTTPGET的請publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{Stringusername=if(username==null||username==""){username="No} Servletout對象PrintWriteroutresponse.getWriter();.println("<!DOCTYPEHTMLPUBLIC\"-//W3C//DTDHTML4.01Transitional//EN\">");out.println("<HEAD><TITLE>AServlet</TITLE></HEAD>");out.println("<BODY>"); Servletout.println("doPost方法out.println("</BODY>"); 輸}//以POST方 頁面時執(zhí)行該函數(shù)。處理方法為HTTPPOST的請publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{ Servletout對象PrintWriteroutresponse.getWriter();.println("<!DOCTYPEHTMLPUBLIC\"-//W3C//DTDHTML4.01Transitional//EN\">");out.println("<HEAD><TITLE>aServlet</TITLE></HEAD>");out.println("<BODY>");out.println(" <h1>ThisismyfirstServlet</h1>"); Thisis");out.println(",out.println(",usingthePOSTmethod");out.println("</BODY>"); 輸}publicvoidinit()throwsServletException}}Servletweb.xmlServletTomcat瀏覽器該Servlet,效果如圖7.1所示7.1UseServletServletCGICGI程序,服務(wù)器就會開辟一個單獨的進(jìn)程來處理請求,處理完請求數(shù)(同一時刻請求的數(shù)目)很多,CGI程序往往顯得力不從心。Servlet解決了這個問題。服務(wù)器會在服務(wù)器啟動時(load-on-startup1)或第一次請求ServletServlet的開銷。當(dāng)然,這種機(jī)制也增加了服務(wù)器Servlet的復(fù)雜度(不過這是服務(wù)器的工作而不是你的工作)。ServletServlet的時候開始生命周期,在服務(wù)器結(jié)束的時候結(jié)束生Servletservice方法。ServletServlet的基本知識之后,JSPServlet5.4所示。而service在每次客戶端請求ServletServlet中有時會用到一些需要初始化與銷毀的資源,Servletinit(ServletConfigconf)方法,HttpServlet提供了一個更簡單的不帶參數(shù)的替代方法:init()。HttpServletinit()init()中就可以了。對ServletConfiggetServletConfig()方法獲取到。Servlet請求轉(zhuǎn)發(fā)(Forward)是通過RequestDispatcher對象的forward(HttpServletRequestrequest,HttpServletResponseresponse)方法來實現(xiàn)的。RequestDispatcher可以通過HttpServletRequest的getRequestDispatcher()Servlet: getRequestDispatcher()方法的參數(shù)必須為以“/”開始,“/Web應(yīng)用程序的根。如果要跳轉(zhuǎn)到的Servlet為,則參數(shù)應(yīng)為“/Method_Service”JSP頁面中顯示處理結(jié)果。forwardStruts、WebWorkMVCServlet來處理用戶請求,request.setAttribute()requestforwardJSP中顯示。ServletURL重定向也叫重定向,是利用服務(wù)器返回的狀態(tài)碼來實現(xiàn)的??蛻舳藶g覽器請求服務(wù)器的時候,HttpServletResponse的setStatus(intstatuss)方法設(shè)置狀態(tài)碼。如果服務(wù)器返回301或者302,則瀏覽器會到新的重新請求該資源。狀態(tài)碼代表的意義如下:3xx301,302表示該資源已經(jīng)不存在或者換了地址,客戶端需要重新定Servlet只接受GET,POST方式但是客戶端卻以DELETE方式)5xx500Servlet的請求重定向到另一個 response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);//設(shè)置狀態(tài)碼為302.response.setHeader("Location"," //新 SC_MOVED_TEMPORARILY302。HttpServletResponsesetStatussetHeader方法封裝sendRedirect(Stringlocation)sendRedirection就能實現(xiàn)重定向。下面通過例子來深入了解Servlet的重定向。例子中利用一個Servlet來統(tǒng)計文件的次數(shù)。要的文件以及次數(shù)都保持在一個Map中。當(dāng)單擊的時候,doGet獲取到文件名,更新的次數(shù),并重定向到要的文件,達(dá)到統(tǒng)計次數(shù)的目的JDBC在ServletServlet在實際應(yīng)用中,大多數(shù)情況下并不是直接實現(xiàn)javax.Servlet接口,而是擴(kuò)展了javax.Servlet.http.HttpServlet或者javax.Servlet.http.GenericServlet這兩個javax.Servlet.Servlet的標(biāo)準(zhǔn)實現(xiàn)。javax.Servlet.http.GenericServletinitdestoryservice方j(luò)avax.Servlet.http.HttpServletGenericServlet類,并HTTPjavax.Servlet.http.HttpServletweb請求會更加方便快捷。HttpServlet類提供了兩個重要的方法:doGet和doPostservice方法。JDBCServletSerrvletdoPostdoGet方法中應(yīng)用。7章\7-2jdbc_servlet在使用ServletHTML<!DOCTYPE<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<metahttp-equiv="content-type"content="text/html;<formaction="AddServlet"method=<inputtype="text"<inputtype="text"<inputtype="text"<inputtype="text"<inputtype="submit"value="提交7.17.1URLServlet文件“AddServlet”,當(dāng)表單提交后將執(zhí)行這個HTMLHEADERACTIONURL地址。用戶看不到這個過程。傳送的數(shù)getpost方法,HttpServlet類提供了兩種方法:doGet和doPostdoGetdoPostpostServletHttpServletRequestgetParameter(大小寫敏感id“nameGETPOST請求的處理方法完全相同。getParameter方法的返回值是一個字符串,它是參數(shù)中指定的變量名一次出現(xiàn)所對應(yīng)的值經(jīng)反編碼得到的字符串(可以直接使用)。例如,如果用戶輸入新部門名稱為“開發(fā)部”,那么調(diào)用方法返回空字符串;如果指定的表單變量不存在,則返回null。如果表單變量可能對應(yīng)多個值,可以用getParameterValuesgetParameter。getParameterValues能夠返回一個字符串?dāng)?shù)組。完整的表單變量名字列表往往是很有用的,利用getParamerterNames方法可以方便地實現(xiàn)這一點。EnumerationpublicclassAddServletextendsHttpServletpublicvoiddestroy()super.destroy();//Justputs"destroy"stringin//Putyourcode}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{PrintWriterout=response.getWriter();this.doPost(request,response);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriterStringid=request.getParameter("id"); Stringnamerequest.getParameter("name");//獲取部門名稱Stringaddress=request.getParameter("address");//獲取部門所在地址intnum=Integer.parseInt(request.getParameter("num"));//獲得部門人數(shù)Connectionconn= 一個Connection對象,原用來連接數(shù)據(jù)庫PreparedStatementpstmt PreparedStatement//MySQLbank數(shù)據(jù)庫模式//connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");//SQLStringsql="insertintodept(id,dname,address,empnumber)values(?,?,?,?)";pstmt=conn.prepareStatement(sql);pstmt.setString(2,name);pstmt.setString(3,address);pstmt.setInt(4,num);intresultpstmt.executeUpdate();//SQLif(result==1)}catch(Exception}}}publicvoidinit()throwsServletException//Putyourcode}}id是唯一這條數(shù)據(jù)的詳細(xì)信息。HTML頁面的代碼如下(7章\7-2)::<!DOCTYPE<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<head><metahttp-equiv="content-type"content="text/html;<formaction="SearchEmployee"<inputtype="text"<inputtype="submit"value="查找7.37.37章\7-2):publicclassQueryByidServletextendsHttpServlet{publicvoiddestroy(){super.destroy();//Justputs"destroy"stringin//Putyourcode}publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriterStringid //Connectionconn=null;// 一個Connection對象,原用來連接數(shù)據(jù)庫。PreparedStatementpstmt=null;// PreparedStatement對象ResultSetrs=null;// connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");Stringsql"select*fromdeptwhereid=?";//SQLpstmt=conn.prepareStatement(sql);pstmt.setString(1,id);rs=}catch(Exceptione){}try{out.print("部門編號out.print("out.print(""+rs.getString(2)+"\n");out.print("部門人數(shù):"+rs.getString(3)+"\n");out.print("部門名稱:"+rs.getString(4)+"\n");out.print("部門id:"+rs.getString(5)+"\n");}}catch(SQLExceptione)//TODOAuto-generatedcatchblock}}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriter();}publicvoidinit()throwsServletException//Putyourcode}}7.57.5publicclassDeptListextendsHttpServletpublicclassDeptListextendsHttpServletpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=gb2312")response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriter();Connectioncon=null;Statementstmt=null;ResultSetrs=null;{);//con=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");stmt=con.createStatement();rsstmt.executeQuery("SELECT*FROMdept");//"<html>""<head><title>部門表信息</title></headout.println("<h1>Employeeout.print("部門編號out.print("部門地址:");out.print("部門人數(shù):");out.print("部門名稱:");out.print("部門id:");}out.print("</body></html>");}catch(Exception}}Servlet7.57.5<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<metahttp-equiv="content-type"content="text/html;charset=UTF-<inputtype="text"<inputtype="submit"value="提交7.6

7.6(import7章\7-2):publicclassQueryToUpdateServletextendsHttpServletpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriterStringid //Connectionconn=null;// 一個Connection對象,用來連接數(shù)據(jù)庫。PreparedStatementpstmt=null;// PreparedStatement對象ResultSetrs=null;// connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");Stringsql"select*fromdeptwhereid=?";//SQLpstmt=conn.prepareStatement(sql);pstmt.setString(1,id);rs=}catch(Exception//"<head><title>顯示單個部門信息+out.print("<formaction='UpdateDeptServlet'method='post'>");try{out.println("部門編號//在文本框中顯示部門編號,out.println("<inputtype='text'name='id'readonly='true'value=");//out.println("<inputtype='text'name='address'out.println("");//out.println("<inputtype='text'name='empnumber'value=");out.println("");//out.println("<inputtype='text'name='dname'value=");id部門id在數(shù)據(jù)庫中是自動生成的,并且是主鍵,所以設(shè)置成只讀out.println("<inputtype='text'name='did'readonly='true'value=");//out.print("<inputtype='submit'value='Submit'>");}}catch(SQLExceptione)//TODOAuto-generatedcatchblock}}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriter();}}7.7所示。

7.7publicclassUpdateDeptServletextendsHttpServletpublicpublicclassUpdateDeptServletextendsHttpServletpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{PrintWriterout=response.getWriter();this.doPost(request,response);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriterConnectionconn ConnectionPreparedStatementpstmt PreparedStatementResultSetrs Statementstmt=Stringid=Stringaddress=intempnumber=Integer.parseInt(request.getParameter("empnumber"));Stringd_name=request.getParameter("d_name");intdid=Integer.parseInt(request.getParameter("did")); MySQLbank//connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");//SQLStringsql="updatedeptsetid=?,address=?,empnumber=?,dname=?,did=?whereid=?";pstmt=conn.prepareStatement(sql);pstmt.setString(1,id);pstmt.setString(2,address);pstmt.setInt(3,empnumber);pstmt.setString(4,dname);pstmt.setInt(5,did);pstmt.setString(6,id);*stmt=conn.createStatement()rsstmt.executeQuery("SELECT*FROMdept");//"<html>""<head><title>部門表信息</title></headout.print("部門編號out.print("部門地址:");out.print("部門人數(shù):");out.print("部門名稱:");out.print("id:");}out.print("</body></html>");}catch(Exceptione){}}}}7.8所示。7.8要刪除的部門編號的頁面代碼如下(7章\7-2):<!DOCTYPE<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<metahttp-equiv="content-type"content="text/html;<formaction="DeleteByIdServlet"<inputtype="text"<inputtype="submit"value="刪除7.97.9publicclassDeleteByIdServletextendsHttpServletpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponsepublicclassDeleteByIdServletextendsHttpServletpublicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{PrintWriterout=response.getWriter();this.doPost(request,response);}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{response.setContentType("text/html;charset=gb2312");PrintWriterout=response.getWriter();Stringid=request.getParameter("id");//Connectionconn=null;ResultSetrs=null;PreparedStatementpstmt=null;try{//MySQLbank//connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");StringsqldeletefromdeptwhereidSQLpstmtconn.prepareStatement(sql);pstmt.setString(1,id);//刪除部門表數(shù)據(jù)</title></head>body>");out.print}catch(Exceptione){}}}JSPJSPHMTLJSPJSPServlt的所有優(yōu)點。JSPServletAIHTMLHTMLJSP成ServletJSP頁面上可以寫JavaJSP也是Servle。JSP做一個簡單的了解。JSPJSP3pageJSPincludeJSPtaglib指令:用于讓用戶自定義pageJSPpagepageJSP容器發(fā)送一些指令,JSP<%@page[language="java"][import="{package.class|package.*},..."]<%@page[language="java"][import="{package.class|package.*},..."]<%@pagelanguage="java"<%@pagelanguage="java"contentType="text/html;charset=UTF-includeJSPincludeJSP文件時,當(dāng)前的頁面include指令指定的頁面合并。在實際的開發(fā)中,會遇到許多頁面都有相同部分,這個時候就需要include指令,它的作用是:通過代碼的重用,達(dá)到減少工作量的目的。JSPinclude指令有兩種<%@<%@includefile=""<jsp:includeflush="true"在編譯階段,指令元素把被包含的文件插入到包含的地方,生成一個.java文件和一個.class文件;行為元素在編譯的時候,被包含的文件單獨生成一個.java和.class文件。指令元素用include的偽代碼實現(xiàn)頁面包含頁面,不會檢查包含文件的變化;行為元素用jsp:includetaglib<%@tagliburi="URIToTagLibrary"prefix="tagPrefix"taglib指令是用來指定一個庫以及自定義庫的前綴。一個JSP文件使用了taglib指令,就可以通過taglib指令來告訴容器:該JSP文件需要哪些庫,并可以指定的前綴。taglib<%@tagliburi="URIToTagLibrary"prefix="tagPrefix"其中uri是指庫的路徑,prefix是的前綴。taglib指令在JSP文件中的代碼如下<%@<%@taglib<c:if/jsp/jstl/core"JSPJSP的對象也叫內(nèi)置對象,也可以叫做JSP的內(nèi)置隱藏對象。它用在jsp表達(dá)式和中,不能直接用在jsp中。JSP的隱藏對象有:out,request,response,config,session,application,page,pageContext,exceptionJSPServlet更加簡單和方便。outjavax.servlet.jsp.JspWriterJSPresponsejavax.servlet.http.HttpServletResponse接口的實現(xiàn)。JSP容器會根據(jù)客戶端的請求信response對象。對象可以將服務(wù)端進(jìn)行的邏輯運作的結(jié)果信息返回給客戶端的瀏覽器。configjavax.servlet.ServletConfig類的實例。ServletConfigweb.xml中初始化始化參數(shù),JSPconfig對象就能滿足這種需求。session對象是javax.servlet.http.HttpSession類的實例。session與是記錄客戶信息的兩種機(jī)制,session用于在服務(wù)器端保存用戶信息,用于在客戶端保存用戶信息。Servlet中需要通過request.getSession()來獲取sessionJSPJSP中配置了<%@pagesession=”false%>session不可用。applicationjavax.servlet.ServletContext接口的實現(xiàn)。applicationJSPWeb應(yīng)用web.xmlapplicationWeb應(yīng)用范圍內(nèi)Web應(yīng)用程序運行期間持久地保持?jǐn)?shù)據(jù)。通過applicationWebWeb應(yīng)用。JSPJSP1.1中出現(xiàn)了自定義。在JSP應(yīng)用程序中添加添加自定義的功能可以是開發(fā)者將工作重JavaJSP頁面脫離,使得JSP頁面更加簡潔,便于。在JSP2.0中,把JSTL庫作為標(biāo)準(zhǔn)的庫。JSTL作為最基本的庫,JSTL庫中提供了一系列的JSP,實現(xiàn)了最基本的功能,例如集合的遍歷,數(shù)據(jù)的輸出,JSP庫是生成的一種機(jī)制。自定義庫可以根據(jù)自己需求來定制、組合一些已存的代碼,形成一個新的代碼。是可重用的代碼結(jié)構(gòu)。自定義庫是個Java類,它封裝了一些代碼,形成一個具有某個功能的新。封裝成一個Java類有兩個好處,一是增加了可擴(kuò)展性,不同之間可以建立起一個繼承關(guān)系,這樣構(gòu)建新的自定義時,可以對已存的進(jìn)行某種程度的升級或改進(jìn),而不需要重新開始創(chuàng)建,提高了開發(fā)效率;而是增加了可復(fù)用性,可以將自定義打包成一個Java文件,這樣可以在不同應(yīng)用之間自由移JSP模式,實現(xiàn)新的頁面效果時,需要重新寫底層實現(xiàn)代碼。這樣費時費力,而且新寫出的代碼沒有經(jīng)過大量的測試,它需要付出很多的調(diào)試成本。ELEL表達(dá)式用${}EL表達(dá)式有標(biāo)識符、存取器、文字和運算符組成。標(biāo)識符是用來存EL表達(dá)式可以通過使用標(biāo)識符和存取器,遍歷包含應(yīng)用程序數(shù)據(jù)或者關(guān)于環(huán)境信息的對象層次結(jié)構(gòu)。EL表達(dá)式還包括了用來操作比較EL表達(dá)式所數(shù)據(jù)的運算符,這些運算符如下:EL ELemptyemptyboolean值。boolean值表示對表達(dá)式的結(jié)果是不是“null”值。JDBCJSPJSPJSP頁面中實現(xiàn)數(shù)據(jù)的增刪改查操作。JSPJDBCJSPJDBC技術(shù)操作數(shù)據(jù)庫MVC分層方式編寫。JSP文件中只編寫頁面顯示內(nèi)容,各種各業(yè)務(wù)邏輯放到Servlet中,操作數(shù)據(jù)庫由JDBC完成。在頁面取值使用JSTL和EL表達(dá)式。7章\7-4jdbc_jsp<%@pagelanguage="java"<%@pageimport="java.sql.*"<!DOCTYPE<%@pagelanguage="java"<%@pageimport="java.sql.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<head><title>MyJSP'add.jsp'starting<formaction=""method=<inputtype="text"<inputtype="text"<inputtype="text"<inputtype="text"<inputtype="submit"value="提交Connectionconn PreparedStatementpstmt connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");Stringsql="insertintodept(id,dname,address,empnumber)values(?,?,?,?)";pstmt=conn.prepareStatement(sql);Stringid Stringnamerequest.getParameter("name");//Stringaddress=request.getParameter("address");//獲取部門所在地址intnum=Integer.parseInt(request.getParameter("num"));//獲得部門人數(shù)pstmt.setString(2,name);pstmt.setString(3address);pstmt.setInt(4,num);=if(result==1)}catch(Exception}catch7.10所示。7.10publicclassDeptVopublicclassDeptVoprivateStringid;//部門編號privateStringaddress;//部門地址privateintempnumber;//部門人數(shù)privateStringd_name;//privateintd_id;//idpublicStringgetAddress(){return}publicvoidsetAddress(Stringaddress){this.address=address;}publicStringgetDname(){returndname;}publicvoidsetDname(Stringdname){this.dname=dname;}publicintgetEmpnumber(){returnempnumber;}7章\7-<%@pagelanguage="java"import="java.util.*"<%@taglib /jsp/jstl/core"prefix="c"<%@page .vo.*"<%@pageimport="java.sql.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<title>MyJSP'showAll.jsp'startingList<DeptVo>list=newArrayList<DeptVo>();{Class.forName("com.mysql.jdbc.Driver"http://Connectionconn=DriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");Statementstmt=conn.createStatement();ResultSetrs=stmt.executeQuery("SELECT*FROMdept");//DeptVodeptVo=newDeptVo();// DeptVo對象,把數(shù)據(jù)放入該對象中deptVo.setDname(rs.getString("dname"));deptVo.setDid(rs.getInt("did"));list.add(deptVo);//DeptVoList集合中}}catch(Exception}publicvoidsetEmpnumber(intempnumber){this.empnumber=empnumber;}publicStringgetId(){returnid;}publicvoidsetId(Stringid){this.id=id;}publicintgetDid(){returndid;}publicvoidsetDid(intdid){this.did=did;}}<tableborder="1"align="center"<c:forEachitems="${list}"<td>${list.id<td>${list.address<td>${list.dname<td>${list.didJSPJavaJDBC部分,把查詢出來的數(shù)據(jù)放入集合中,在頁面使用便簽取值。7.11所示。7.11ididJSP文件代碼如下(源代碼見7章\7-4):<%@<%@pagelanguage="java"import="java.util.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<head><title>MyJSP'item.jsp'starting<formaction="ShowById.jsp"<inputtype="text"<inputtype="submit"value="查找ShowById.jsp頁面,ShowById.jsp是接下來要編寫的文件,JSP文件中,獲得傳遞過來的查詢條件,然后跟查詢條件把數(shù)據(jù)詳細(xì)信息查詢出來。并把查詢出來的數(shù)據(jù)信息顯示在頁面中。ShowById.jsp文件代碼如下(7章\7-4):<%@<%@pagelanguage="java"import="java.util.*"<%@page .vo.*"<%@pageimport="java.sql.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<head><title>MyJSP'ShowById.jsp'startingintd_id=Integer.parseInt(request.getParameter("id")); //獲取部門編號Connectionconn=null;// 一個Connection對象,原用來連接數(shù)據(jù)庫。PreparedStatementpstmt=null;// PreparedStatement對象ResultSetrs=null;// connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");Stringsql"select*fromdeptwhered_id=?";//SQLpstmt=conn.prepareStatement(sql);pstmt.setInt(1,did);rs=pstmt.executeQuery();DeptVodeptVonew deptVo.setDname(rs.getString("dname"));deptVo.setDid(rs.getInt("did"));System.out.println(deptVo.getDid());}}catch(Exception}<jsp:include<jsp:includeflush="true"<tableborder="1"align="center"<td>${deptVo.id<td>${deptVo.dname<td>${deptVo.didJSPDeptVoDeptVorequest對象中,在頁面中使用EL表達(dá)式來取值,ShowById.jsp頁面,頁面效果如圖7.12所示。7.12在這一節(jié)的例子中,先編寫輸入修改數(shù)據(jù)條件的頁面,代碼如下(7章\7-<%@pagelanguage="java"import="java.util.*" <!DOCTYPE<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<head><title>MyJSP'updateItem.jsp'starting<formaction="queryToUupdate.jsp"<inputtype="text"<inputtype="submit"value="查找上述代碼中,form表單的action值是queryToUupdate.jsp,當(dāng)提交查詢時,頁面會進(jìn)入queryToUupdate.jspqueryToUupdate.jspd_idqueryToUupdate.jsp頁面的代碼如下(7章\7-4):<%@<%@pagelanguage="java"import="java.util.*"<%@page .vo.*"<%@pageimport="java.sql.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<head><title>MyJSP'queryToUupdate.jsp'startingresponse.setCharacterEncoding("gb2312");//設(shè)置response的編碼方式request.setCharacterEncoding("gb2312");//設(shè)置request的編碼方式Connectionconn=null;// 一個Connection對象,原用來連接數(shù)據(jù)庫。PreparedStatementpstmt PreparedStatementResultSetrs=null;//intd_id=// connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");Stringsql"select*fromdeptwhered_id=?";//SQLpstmt=conn.prepareStatement(sql);pstmt.setInt(1,did);rs=pstmt.executeQuery();DeptVodeptVonew deptVo.setDname(rs.getString("dname"));deptVo.setDid(rs.getInt("did"));System.out.println(deptVo.getDid());}}catch(Exception}catch(Exception}<formaction="update.jsp"method=<inputtype="text"name="id"value="${<inputtype="text"name="name"value="${deptVo.d<inputtype="text"name="num"value="${<inputtype="text"name="address"value="${<inputtype="text"name="did"value="${deptVo.d<inputtype="submit"value="修改7.13所示。7.13<%@pagelanguage="java"import="java.util.*"<%@pageimport="java.sql.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTD<%@pagelanguage="java"import="java.util.*"<%@pageimport="java.sql.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<head><title>MyJSP'update.jsp'startingConnectionconn PreparedStatementpstmt Stringid=Stringaddress=intempnumber=Integer.parseInt(request.getParameter("num"));Stringdname=request.getParameter("name");intdid=Integer.parseInt(request.getParameter("d 連接到MySQL數(shù)據(jù)庫中的bank數(shù)據(jù)庫模式connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");Stringsql="updatedeptsetid=?,address=?,empnumber=?,dname=?,did=?whereid=?";pstmt=conn.prepareStatement(sql);pstmt.setString(1,id);pstmt.setString(2,address);pstmt.setInt(3,empnumber);pstmt.setString(4,dname);pstmt.setInt(5,did);pstmt.setString(6,id);}catch(Exception}<jsp:includeflush='true'page=7.14所示。7.14<%@pagelanguage="java"import="java.util.*"<%@pageimport="java.sql.*"<!DOCTYPE<%@pagelanguage="java"import="java.util.*"<%@pageimport="java.sql.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<head><title>MyJSP'delete.jsp'starting<formaction=""<inputtype="text"<inputtype="submit"value="刪除//連接數(shù)據(jù)庫Connectionconnnull;ResultSetrs=null;PreparedStatementpstmt=null;try{Stringid=//MySQLbank數(shù)據(jù)庫模式//connDriverManager.getConnection("jdbc:mysql://localhost:3306/bank","root","root");StringsqldeletefromdeptwhereidSQLpstmt=conn.prepareStatement(sql);pstmt.setString(1,id);}catch(Exception}JSP頁面中,JDBCJSPid來作為刪除條件。JDBC獲idid7.15所示。7.15的頁是第一頁的時候,上一頁超就不能再點擊,當(dāng)前頁是最后一頁的時候,下一頁則不能再點擊。JSP文件中,代碼如下(7章\7-4):<%@<%@pagelanguage="java"import="java.util.*"<%@taglib /jsp/jstl/core"prefix="c"<%@page .vo.*"<%@pageimport="java.sql.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<head><title>MyJSP'showAllByPage.jsp'startingResultSetrs=null;PreparedStatementpstmt=null;Connectionconn=null;List<DeptVo>list=newArrayList<DeptVo>();try{=intpage2=1;if(page1!=null){page2=}request.setAttribute("page2",page2);Class.forName("com.mysql.jdbc.Driver"創(chuàng)建數(shù)據(jù)庫驅(qū)動conn=Stringsql="select*fromdeptorderbyiddesclimit?,5";pstmt=conn.prepareStatement(sql);pstmt.setInt(1,rs=pstmt.executeQuery();DeptVodeptVo=new CarsVo對象中deptVo.setDname(rs.getString("dname"));deptVo.setDid(rs.getInt("did"));}intcount 一個count變量,用 記錄intmaxpage maxpageStatementstmt=Stringsql1="selectcount(*)fromdept";//查 錄數(shù)的SQL語rs=while(rs.next())countrs.getInt(1);//}maxpage=(count+4)/5;//最大頁數(shù)等于 request.setAttribute("maxpage",maxpage);}catch(SQLExceptione){}<tableborder="1"align="center"<c:forEachitems="${list}"

<td>${list.id<td>${list.address<td>${list.dname<td>${list.did<div<a<ahref="?page=1">首頁<c:iftest="${page21}">上一頁<c:iftest="${page21}"><ahref="?page=${page21上一頁<c:iftest="${page2maxpage}">下一頁<c:iftest="${page2maxpage}"><ahref="?page=${page2+1下一頁<ahref="?page=${maxpage末頁上述代碼中,分頁顯示設(shè)置成每頁顯示5條記錄,默認(rèn)的頁數(shù)為第一頁,也就是說第一次時,7.16所示。7.16JDBCServletJSP動包和JSTL庫的jar包拷貝到WebRoot/WEB-INF/lib中。本節(jié)中的例子所有文件都在該工程7章\7-3jsp_jdbc。CREATETABLEusers(idint(11)NOTNULL,nameCREATETABLEusers(idint(11)NOTNULL,namevarchar(20)DEFAULTNULL,ageint(11)DEFAULTNULL,varchar(20)DEFAULTNULL,addressvarchar(50)DEFAULTNULL,PRIMARYKEY(id))ENGINE=InnoDBDEFAULTJDBCMySQL數(shù)據(jù)庫,JDBC連接MySQL數(shù)據(jù)的代碼如下(import的內(nèi)容): publicclassJDBCConnectionstaticStringdrivername="com.mysql.jdbc.Driver";//mysql數(shù)據(jù)庫驅(qū)動staticStringurl="jdbc:mysql://localhost:3306/bank";//連接的數(shù)據(jù)庫地址staticStringusername="root";//連接數(shù)據(jù)庫用戶名staticStringpassword="root";//try}catch(ClassNotFoundExceptione){}}publicstaticConnectiongetConnection(){Connectionconn=null;tryconn(ConnectionDriverManager.getConnection(urlusername,password);//創(chuàng)建連接}catch(SQLExceptione)System.out.println("url、usernamepassword");}

returnStatement@param@param@parampublicstatic (ResultSetrs,Connectionconn,Statementtryif(rs}catch(SQLExceptione)System.out.println("ResultSet失敗!");}finallytryif(conn!=}}catch(SQLExceptione)tryif(stmt!=}catch(SQLExceptione)}}}}publicstaticvoidmain(String[]args)JDBC}}JSPJSPaddUsers.jsp,在這個頁面中,數(shù)據(jù)庫存在的字段,form對應(yīng)的文本框。addUsers.jsp文件代碼如下(替、<%@pagelanguage="java"import="java.util.*"<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01<formaction="AddUsersServlet" <tr><td>編號:<td><inputtype="text" :<td><inputtype="text" :<td><inputtype="text" :<td><inputtype="text"name="<tr><td>地址:<td><inputtype="text"<inputtype="submit"value="提交<inputtype="reset"value="重置users5Java變量來操作數(shù)據(jù)庫的字段。這過程中需要數(shù)據(jù)類型的轉(zhuǎn)換。實體類的類名為publicclassUserVo{privateintid;privatepublicclassUserVo{privateintid;privateStringname;privateintage;privateString privateString}ServletpublicclassAddUserpublicvoidadd(UserVouserVo){Connectionconn=null;PreparedStatementpstm=publicclassAddUserpublicvoidadd(UserVouserVo){Connectionconn=null;PreparedStatementpstm=null;ResultSetrs=null;tryconn=JDBC//sqlStringsql="insertintousers(id,name,age,,address)values(?,?,?,?,?)";pstm=conn.prepareStatement(sql);pstm.setInt(1userVo.getId());//idpstm對象中,intsetInt()//把添加的name值存入pstm對象中String類型的值用setString方法pstm.setInt(3,userVo.getAge());//把添加的age值存入pstm對象中pstm.setString(4,userVo.get 值存入pstm對象中System.out.println("id:"+userVo.getId()+"\tname:"+userVo.getName()+"\tage:"+userVo.getAge()+"\t "\taddress:"+userVo.getAddress());}catch(Exceptione){}finallyJDBC (rs,conn,}}}publicclassAddUsersServletextendsHttpServletpublicpublicclassAddUsersServletextendsHttpServletpublicvoiddestroy()super.destroy();//Justputs"destroy"stringin//Putyourcode}publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)throwsServletException,IOException{request.setCharacterEncoding("gb2312");//request的編碼方式response.setCharacterEncoding("gb2312");//response的編碼方式PrintWriterout=response.getWriter();intid=Integer.parseInt(request.getParameter("id"));//idStringname=request.getParameter("name");//nameintage=Integer.parseInt(request.getParameter("age"));//獲得頁面?zhèn)鬟f過來的age =request.getParameter("");//獲得頁面?zhèn)鬟f過來的Stringaddressrequest.getParameter("address");// UserVoUserVouserVo=newUserVo(); ();AddUseraddUsernew AddUseraddUser.add(userVo);//AddUseradd()方法response.sendRedirect("addUsers.jsp");}publicvoidinit()throwsServletException//Putyourcode}}Servletweb.xml中配置Servlet信息,AddUsersServletweb.xml中的配置信息如下(AddUsersServlet類的配置 publicclassZhFilterpublicclassZhFilterimplementspublicvoiddestroy()//TODOAuto-generatedmethod}publicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{//request//responsegb2312//chaindoFilter}publicvoidinit(FilterConfigarg0)throwsServletException//TODOAuto-generatedmethod}}WebRoot/WEN-INF/web.xmlweb.xml中配置這里需這里需 的是:過濾器必須要配置在所有Servlet的配置之前,這樣才能保證過濾器對每 .filter.ZhFilter</filter- ,在MyEclipse中,把工程jsp_jdbc發(fā)布到Tomcat服務(wù)器添加數(shù)據(jù)的JSP頁面,頁面效果如,7.177.17users中了。MySQL中的分頁查詢。個方法來實現(xiàn),這個方法里根據(jù)分頁查詢的SQL語句來實現(xiàn)分頁查詢。分頁顯示的實現(xiàn)類類名ShowByPage,ShowByPage類的代碼如下(import的內(nèi)容):publicclassShowByPagepublicList<UserVo>showByPage(intpage){//分頁查詢方法ResultSetresultSet=null;PreparedStatementpstmt=null;Connectionconn=null;List<UserVo>list=newArrayList<UserVo>();try{conn=Stringsql="select*fromusersorderbyiddesclimit?,5";//SQL5pstmt=conn.prepareStatement(sql);pstmt.setInt(1,page);resultSet=pstmt.executeQuery();UserVouserVo=new (resultSet.getString(""));}}catch(SQLExceptione)//TODOAuto-generatedcatc

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論