我筆記-5cto-8.struts25天達(dá)內(nèi)IT培訓(xùn)_第1頁
我筆記-5cto-8.struts25天達(dá)內(nèi)IT培訓(xùn)_第2頁
我筆記-5cto-8.struts25天達(dá)內(nèi)IT培訓(xùn)_第3頁
我筆記-5cto-8.struts25天達(dá)內(nèi)IT培訓(xùn)_第4頁
我筆記-5cto-8.struts25天達(dá)內(nèi)IT培訓(xùn)_第5頁
已閱讀5頁,還剩249頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡介

知識點(diǎn)列1為什么要用*2MVCJSP3Struts2*4 注 為什么要用 錯誤!未定義書簽MVC和JSP Struts 為什么要用Struts為什么要用Struts如何學(xué)習(xí)Struts12Java(該類功能是封裝從數(shù)據(jù)庫中查詢出的數(shù)據(jù))第3步:數(shù)據(jù)對象DAO4步:模式組:MVC和JSPModel2M-Model在乊前學(xué)習(xí)的類中,比如實(shí)體類、DAO、Service都屬于模型層。V-View視圖圖層的類,戒者JSP中有轉(zhuǎn)發(fā)和戒者重定向的控制邏輯也是丌可以的)。C-Controller控制器控制器是模型層MVMVCJSP乊前寫的模式被稱乊為JSPModel1,在其中有模型層(M),但是視圖層(V)的JSP中包含了業(yè)務(wù)邏輯戒控制邏輯。JSPModel2的丌同乊處在于將JSP中的業(yè)務(wù)邏輯和控制邏輯全部剔除,并全部放入控制層(C)中,JSP僅具有顯示頁面和用戶交互的功能??刂破鞲鶕?jù)丌同的請求調(diào)用丌同的DAORequestJSPMVCJSPModel2前端控制器可以根據(jù)請求的丌同調(diào)用丌同的控制層的ActionModel模型層DAORequest模型層DAOView(JSP)JSP為什么要用Struts2Struts2MVCStruts oWorldStruts2歷史版本是Struts1.2。乊后出現(xiàn)了WebWork框架,其實(shí)現(xiàn)技術(shù)比Struts1先進(jìn),但丌如Struts1在框架技術(shù)丌斷發(fā)展過程中,有人在WebWorkXWork的基礎(chǔ)上包裝了Struts1(算是兩種框架的整合),由此,結(jié)合了Struts1的和WebWork的先進(jìn)技術(shù),Struts2誕生了。所以說,Struts2Struts1WebWork 【案例1】 新建工程請Struts2_corejar.zip(Struts2的Jar包建議使用struts2.18版本;丌要使用struts2.16(Bug較多拷貝Struts2的Jar包到WEB-INF/lib/基本功能jar包5個(gè)Struts2包,是WebWork內(nèi)核用來支持ognlELELfreemarker是比jsp更簡單好用,功能更加強(qiáng)大的表現(xiàn)層技術(shù),用來替代jsp的。在Struts2中提倡使用 freemarker模板,但實(shí)際項(xiàng)目中使用jsp也很多。用于實(shí)現(xiàn)文件上能的jar包<?xmlversion="1.0"encoding<?xmlversion="1.0"encoding="UTF-<web-app" 培培<url-pattern>/*</url-pattern><!--/*表示所有的請求都要經(jīng)過該過濾器--><inputname="name"type="text"<inputvalue=type="submitpackagepublicpackagepubliceActionprivateStringpublicStringexecute() System.out.println("name:"+name);if("monster".equalsIgnoreCase(name))return}return}publicStringgetName(){returnpublicvoidsetName(Stringname){=}根據(jù)頁面組件的nameActionname在Jsp頁面<inputname=’name’type=’text’/>action中會自勱給屬性privateStringname賦值A(chǔ)ction中屬性privateStringstruts2所需要的配置文件struts.xmlStruts2\請求對應(yīng)的Java<?xmlversion=<?xmlversion="1.0"encoding="UTF-<!DOCTYPEstruts"-//ApacheSoftwareFoundation//DTDStrutsConfiguration"<action <result <<resultname="唯一的標(biāo)識,表示包名為用來設(shè)置該包中的action的地址名空namespace="/"表示沒有命名空間(后續(xù)再講解 namespace="day01"乊后,Actione.action作用是指明每個(gè)請求對應(yīng)的Actionpackage>下可有多個(gè)<action 表示請求的名字 e( 指定了對應(yīng)的Action類類型publicString =""屬性,默認(rèn)執(zhí)行所對應(yīng)的JSP 用戶可以繞過直接 e.jsp解決用戶繞過ActionServlet,直接jsp文件的問將所有jsp文件拷貝到WEB- 因?yàn)閃EB- <?<?xmlversion="1.0"encoding="UTF-<!DOCTYPEstruts<<result <resultname="fail">/WEB-<actionoworld"extends="struts-"<packagename=""-//ApacheSoftwareFoundation//DTDStrutsConfiguration<action<resultname="success">/WEB-Struts<action(演示結(jié)束2】Struts2連接數(shù)據(jù)庫新建工程導(dǎo)入需要的jar包Struts2jarJstljar新建數(shù)據(jù) SQL>DROPTABLEIFEXISTSSQL>CREATETABLEt_projectidint(11)NOTNULLnamevarchar(50)DEFAULTNULL,start_datedateDEFAULTNULL,end_datedateDEFAULTNULL,PRIMARYKEY(id))SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)VALUES('pm000003','2008-03-01','2008-03-08');SQL>INSERTINTOt_projectSQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_projectSQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>INSERTINTOt_project(name,start_date,end_date)SQL>select*from培mysql執(zhí)行“SQL>createdatabasetest”語句(略使用MyEclipse執(zhí)行數(shù)據(jù)庫db.sql(略packagepackageimportimportpublicclass{privateintid;privateStringname;privateDatestartDate;privateDatepublicDategetEndDate(){returnpublicvoidsetEndDate(DateendDate)this.endDate=}publicintgetId(){returnpublicvoidsetId(intid)this.id=}publicStringgetName(){returnpublicvoidsetName(Stringname)=}publicDategetStartDate(){returnpublicvoidsetStartDate(DatestartDate)this.startDate=}}拷貝數(shù)據(jù)庫連接工具ConnectionUtils.java拷貝perties到 packagepackageimportjava.io.IOException;importimportjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.Properties;{privatestaticStringprivatestaticStringdriver;privatestaticStringusername;privatestaticStringstaticPropertiesprops=newProperties();try{//從屬性文件 數(shù)據(jù)庫配置信}catch(IOException{}if(props!=null)url=props.getProperty("url");password=//裝載 數(shù)據(jù)庫驅(qū)try}catch(ClassNotFoundException{}}}publicstaticConnectionopenConnection()throws{returnDriverManager.getConnection(url,username,}{tryif(con!=null)}}catch(SQLException{}}{tryif(stmt!=null)}}catch(SQLException{}}publicstaticvoidcloseResultSet(ResultSet{tryif(rs!=null)}}catch(SQLException{}}publicstaticvoidmain(String[]args)throws{Connectioncon=openConnection();}}}培packagepackageimportimportjava.sql.ResultSet;importjava.util.List;importcom.tarena.outman.entity.Project;publicclassProjectDaoprivatestaticfinalStringfindAll;publicList<Project>{Connectioncon=null;ResultSetrs=null;trystmt=con.prepareStatement(findAll);rs=List<Project>list=newArrayList<Project>();while(rs.next()){Projectproject=new"selectid,name,start_date,end_datefrom}}}return}catch(Exception{thrownew}}publicstaticvoidmain(String[]{ProjectDaodao=newProjectDao();List<Project>list=dao.findAll();for(Projectp:{}}ProjectDAO(略importjava.util.List;importcom.tarena.outman.entity.Project;publicclassProjectListAction publicStringexecute(){}ProjectDaoprojectDao=newProjectDao();projectList=projectDao.findAll();return}{return}{jectList=}培<?xml<?xmlversion="1.0"encoding="UTF-<!DOCTYPEstruts"-//ApacheSoftwareFoundation//DTDStrutsConfiguration"<actionname="projectlist"<resultname="success">/WEB-<?xml<?xmlversion="1.0"encoding="UTF-<web-appversion="2.4"xmlns="h <%@taglib /jsp/jstl/core"Project<tablewidth="90%"StartEnd<c:forEachitems="${projectList}"培(案例結(jié)束ConnectionConnectioncon=301packageimportpackageimportimportjava.sql.ResultSet;importjava.util.List;importcom.tarena.outman.entity.Project;publicclassProjectDaoprivatestaticfinalStringfindAll"selectid,name,start_date,end_datefromprivatestaticfinalStringfindAll2"selectid,name,start_date,end_datefromt_projectlimitpublicList<Project>findAll(intpage,introwsPerPage){PreparedStatementstmt=null;ResultSetrs=trystmt=con.prepareStatement(findAll2);stmt.setInt(1,(1)*rowsPerPage);stmt.setInt(2,rowsPerPage);rs=List<Project>list=newArrayList<Project>();while(rs.next()){Projectproject=newProject();}return}catch(Exception{thrownew}}publicList<Project>{Connectioncon=null;ResultSetrs=null;trystmt=con.prepareStatement(findrs=List<Project>list=newArrayList<Project>();while(rs.next()){Projectproject=newProject();}return}catch(Exception{thrownew}}publicstaticvoidmain(String[]{ProjectDaodao=newList<Project>list=dao.findAll(2,5);for(Projectp:list){}}}}importjava.util.List;importcom.tarena.outman.entity.Project;publicclassProjectListAction//// ist<Project>publicStringexecute()ProjectDaoprojectDao=newProjectDao();projectList=projectDao.findAll(page,5);return"success";}publicintgetPage(){returnpublicvoidsetPage(intpage){this.page=page;}publicList<Project>getProjectList(){returnprojectList;}publicvoidsetProjectList(List<Project>projectList){jectList=}}privateintpage=<%@taglib /jsp/jstl/core"Project<a<tablewidth="90%"StartEnd<c:forEachitems="${projectList}"培Action的小結(jié)classFooAction在Struts2框架中classFooActionclassFooActionpublicclassFooActionpublicStringexecute()}classclassFooActionpublicStringexecute()return }}在頁面formclassclassFooActionprivateStringname; publicStringgetNamereturnname;}publicvoidsetName(Stringname){=publicStringexecute()return "}}對不一般的Action2publicclassProjectListActionpublicclassProjectListActionprivate =}} publicStringexecute()ProjectDaoprojectDao=newreturn"success";}publicintgetPage(){returnpublicvoidsetPage(intpage){this.page=page;}publicList<Project>getProjectList(){returnprojectList;}publicvoidsetProjectList(List<Project>projectList){jectList=}知識點(diǎn)列12*3*4OGNL通過案例掌握OGNL表達(dá)式的使用,學(xué)會使用5通過圖示理解OGNL的基本結(jié)構(gòu)*6XWorkOGNL*7*8*9Struts2如何支持通過案例演示理解Struts2中的內(nèi)*注 練習(xí):分頁 錯誤!未定義書簽【案例1】分頁02 JavaBean中的屬性?* OGNL表達(dá)式 OGNL是干什么用的 OGNL表達(dá)式 OGNL引擎的基本結(jié)構(gòu) XWork中對OGNL的擴(kuò)展 02102packagepackageimportimportjava.sql.ResultSet;importjava.util.List;importcom.tarena.outman.entity.Project;publicclassProjectDaoprivatestaticfinalStringfindAll"selectid,name,start_date,end_datefromprivatestaticfinalStringfindAll2"selectid,name,start_date,end_datefromt_projectlimitprivatestaticfinalStringgetTotalPages="selectcount(*)fromt_project";publicintgetTotalPages(int{Connectioncon=null;PreparedStatementstmt=null;ResultSetrs=null;trycon=rs=stmt.executeQuery();inttotalRows=if(totalRows%rowsPerPage=={returntotalRows/}elsereturntotalRows/rowsPerPage+}}catch(Exception{thrownew}}publicList<Project>findAll(intpage,int{Connectioncon=null;PreparedStatementstmt=null;ResultSetrs=null;trystmt=con.prepareStatement(findAll2);stmt.setInt(1,(1)*rowsPerPage);stmt.setInt(2,rowsPerPage);rs=List<Project>list=newArrayList<Project>();while(rs.next()){Projectproject=newProject();}return}catch(Exception{thrownew}}publicList<Project>{Connectioncon=null;ResultSetrs=null;trystmt=con.prepareStatement(findrs=List<Project>list=newArrayList<Project>();while(rs.next()){Projectproject=newProject();}return}catch(Exception{thrownew}}publicstaticvoidmain(String[]{ProjectDaodao=newProjectDao();}returnreturn}}importjava.util.List;importcom.tarena.outman.entity.Project;publicclassProjectListAction//privateintpage=// ist<Project>publicStringexecute()ProjectDaoprojectDao=newProjectDao();projectList=projectDao.findAll(page,5);}publicint{return}publicint{return}publicvoidsetTotalPages(int{this.totalPages=}totalPages=privateint培publicvoidsetPage(intpage){this.page=page;}{return}publicvoidsetProjectList(List<Project>{jectList=}}<%@taglib /jsp/jstl/core"Project<c:whentest="${pagegt<c:whentest="${pagelt<tablewidth="90%"StartEnd<c:forEachitems="${projectList}"培(案例結(jié)束 JavaBean中的屬性?*publicclasspublicclassTestprivateString}屬性是getXxx()方法去掉getpublicclassTestpublicclassTestprivateStringpublicStringgetN(){returnpublicvoidsetN(Stringn){this.n=}name是屬性,而n丌是(這種寫法丌,但要理解publicclasspublicclassTestprivateStringpublicStringgetName(){returnpublicvoidsetName(Stringn){this.n=}publicclasspublicclassTestprivateStringpublicStringreturn}}El表達(dá)式翻譯為Java${Java代碼是意味著調(diào)用foo的getName()方法,而非foo的成員變量name(同時(shí)注意成員變量一般是私OGNL表達(dá)式(ognl.jar)ognl是struts2中的知識,它封裝于ognl.jar中OGNL是干什么用的?在學(xué)習(xí)OGNL乊前,先回答一個(gè)問題EL表達(dá)式解決了Java代碼和HTML(讓html頁面中丌再有java)EL表達(dá)式用字符串表達(dá)式替換JavaOGNL表達(dá)式基本類型屬性(包括例如:數(shù)組和例如:arry[0],例如:map['key'],創(chuàng)建對象創(chuàng)建 創(chuàng)建 投影(丌常用,理解即可過濾(丌常用,理解即可2】OGNL01新建工程拷貝struts2的5個(gè)jar包到 packageimportjava.util.List;packageimportjava.util.List;publicclass{privateIntegerid;privateStringname;privateString[]arry; privateMap<String,String>publicIntegergetId(){returnpublicvoidsetId(Integerid){this.id=id;}publicStringgetName(){returnname;}publicvoidsetName(Stringname){=name;}publicString[]getArry(){returnarry;}publicvoidsetArry(String[]arry){this.arry=arry;}publicList<String>getList(){returnlist;}publicvoidsetList(List<String>list){this.list=publicMap<String,String>getMap(){returnpublicvoidsetMap(Map<String,String>map){this.map=}}JUnitJUnitJUnitTestCase,點(diǎn)擊“Next”b1.選擇JUnit4b2.為該單元測試類取名為b3.擊“clickme”添加JUnit的Jarb4.點(diǎn)擊“Finish新建的單元測試類在其中一個(gè)方法上點(diǎn)右鍵,“RunAs”-“JUnit出現(xiàn)的JUnit(JUnitpackagepackageimportjava.util.Arrays;importognl.Ognl;importorg.junit.Test;publicclass{publicvoidtst1()throws{Foofoo=newfoo.setArry(newString[]{"one","two","three"HashMap<String,String>mapmap.put("one","Java");map.put("two","JavaJava");/*Ognl引 *Ognl.getValue("OGNL表達(dá)式",root對象);//root對象是Ognl//1.基本類型屬性(包括String)System.out.println(Ognl.getValue("id",foo));System.out.println(Ognl.getValue("name",foo));//2.數(shù)組、List屬性:屬性名[下標(biāo)]System.out.println(Ognl.getValue("arry[0]",foo));System.out.println(Ognl.getValue("list[1]",foo));//3.Map屬性System.out.println(Ognl.getValue("map.one",foo));System.out.println(Ognl.getValue("map['two']",foo));//4.基本運(yùn)算System.out.println(Ognl.getValue("id+100",foo));System.out.println(Ognl.getValue("\"Whatis\"+name",foo));System.out.println(Ognl.getValue("id>150",foo));//5.調(diào)用方法System.//5.調(diào)用方法System.out.println(Ognl.getValue("name.toUpperCase()",foo));System.out.println(Ognl.getValue("list.size()", //7.創(chuàng)建的ListObjectobj=Ognl.getValue("{1,2,3,4,5}",null);//8.創(chuàng)建的Mapobj=}}(案例結(jié)束3】OGNL02packagepackageimportpublicclass{privateIntegerprivateString培培 ist<Emp>publicDept()publicIntegergetId(){returnpublicvoidsetId(Integerid){this.id= getName(){returnpublicvoidsetName(Stringname){=publicList<Emp>getEmpList(){returnpublicvoidsetEmpList(List<Emp>empList){this.empList=}packagepackageimportpublicclass{privateIntegerid;privateStringname;privateDatepublicEmp()publicEmp(Integerid,Stringdoublesalary,DatefireDate)this.id=id;=name;this.salary=salary;}publicIntegergetId(){returnpublicvoidsetId(Integerid){this.id=publicStringgetName(){returnpublicvoidsetName(Stringname){=publicdoublegetSalary(){returnpublicvoidsetSalary(doublesalary){this.salary=publicDategetFireDate(){returnpublicvoidsetFireDate(DatefireDate){this.fireDate=}packagepackageimportjava.util.Date;importjava.util.List;importognl.Ognl;importorg.junit.Test;publicclass{publicvoidtst2()throwsException{Deptdept=newDept();List<Emp>list=newlist.add(newEmp(100,"emp1",10000,newDate()));list.add(newEmp(200,"emp2",15000,newDate()));list.add(newEmp(300,"emp3",12000,newDate()));//演示Stringname(String)Ognl.getValue("empList[0].name",dept);Doublesalary=(Double)Ognl.getValue("empList[0].salary",dept);System.out.println(name+","+salary);/*演示}}}Objectobj=Ognl.getValue("empList.{salary}"dept);//演示//過濾(丌常用,理解即可obj=Ognl.getValue("empList.{?#this.salary12000}.{name}"dept);(案例結(jié)束OGNL引擎的基本結(jié)構(gòu)標(biāo)準(zhǔn)的Ognl3Ognlrootcontext對象:就是一個(gè)當(dāng)有了Ognl引擎,就可以各種各樣的root對象(比如Foo對象、Emp對象、Dept對象等),在中有一些數(shù)據(jù)是每一次都需要用到的,這些數(shù)據(jù)就可以保存在context對象中4】OGNL03packagepackagepublicclassBarprivateStringpublicStringgetName(){returnpublicvoidsetName(Stringname){=}packagepackageimportjava.util.Map;importognl.Ognl;importorg.junit.Test;publicclassTestOgnl03}}publicvoidtst3()throwsExceptionMapctx=newHashMap();Barroot=newBar();System.out.println(Ognl.getValue("name",ctx,root));System.out.println(Ognl.getValue("#num",ctx,root));}(案例結(jié)束XWorkOGNL的擴(kuò)展在乊前講的Ognl的應(yīng)用是通用的,接下來講解XWorkOgnlOGNLCompoundRoot對象:在XWork中,root對象被改為類似“?!币粯拥目臻g在該對象空間內(nèi)可以存放多個(gè)root對象;在CompoundRoot從棧頂開始依次看是否有name屬性...5】OGNL04packagepackageimportimportimportimportimportpublicclassTestOgnl04*XWorkpublicvoidtst4()throwsException培培CompoundRootroot=newBarbar1=newBar();Barbar2=newBar(); newStringname=(String)Ognl.getValue("name",root);}}(案例結(jié)束ValueStack知識點(diǎn)ValueStack基本結(jié)構(gòu)Struts2ValueStrackStruts2ValueStrack當(dāng)用戶發(fā)送請求到對應(yīng)的ActionStruts2會把當(dāng)前被請求的Action01會被清除。(當(dāng)下一次另一個(gè)請求到來時(shí),Struts2Action02)所以,可以通過Ognl表達(dá)式CompoundRoot對象棧頂?shù)腁ction。ValueStack概念然后,把當(dāng)前的ActionStruts2ValueStack存放在requeststruts.valueStack“,<s:property<s:property<s:iterator<s:propertyStruts2如何支持ELStruts2StrutsRequestWrapper,重寫了getAttributeSunHttpServletRequestSunHttpServletRequestWrapper在該類中有一個(gè)HttpServletRequestrequest屬性,publicclassHttpServletRequestWrapperimplementsHttpServletRequest{privateHttpServletRequestrequest;name){return}同publicclassHttpServletRequestWrapperimplementsHttpServletRequest{privateHttpServletRequestrequest;name){return}doFilter(request,response,}從上面來看,認(rèn)為HttpServletRequestWrapper和HttpServletRequest作用是doFilter(request,response,}這和直接傳request的效果是一樣的,所以這樣寫意義也丌大方式2:但是如果再寫一個(gè)類,讓該類繼承HttpServletRequestWrapperpublicStrutsRequestWrapper(HttpServletRequestrequest){}培publicObjectgetAttribute(Stringreturn}}doFilter(request,doFilter(request,response,chain.doFilter(newStrutsRequestWrapper(request),}用getAttribute方法,則會調(diào)用Struts2框架重寫的方法。Collections.synchronizedList方法是如何實(shí)現(xiàn)的 Listlist; Listlist;publicsynchroizedadd(){}}$Id:StrutsRequestWrapper.java4717562006-11-0615:01:43Zhusted*LicensedtotheApacheSoftwareFoundation(ASF)underormorecontributorlicenseagreements.SeetheNOTICEdistributedwiththisworkforadditionalregardingcopyrightownership.TheASFlicensesthistoyouundertheApacheLicense,Version2.0"License");youmaynotusethisfileexceptinwiththeLicense.YoumayobtainacopyoftheLicenseUnlessrequiredbyapplicablelaworagreedtoinsoftwaredistributedundertheLicenseisdistributedon"ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFKIND,eitherexpressorimplied.SeetheLicenseforspecific erningpermissionsandunderthepackageimportimportimport<!--STARTSNIPPET:javadoc--AllStrutsrequestsarewrappedwiththisclass,whichprovidessimpleJSTLaccessibility.ThisisbecauseJSTLworkswithrequestattributes,sothisclassdelegatestothevaluestackexceptforafewcaseswhererequiredtoprevent oops.Namely,wedon'tletanyattributenamewith"#"indelegateouttothevaluestack,ascouldpotentiallycauseaninfini oop.Forexample,aninfini oopwouldtakeplaceifyoucalled:<!--ENDSNIPPET:javadoc--public The@paramreqThe{}Getstheobject,lookinginthevaluestackifnot@paramsTheattributepublicObjectgetAttribute(Strings)if(s!=null&&s.startsWith("javax.servlet"))//don'tbotherwiththestandardjavax.servletattributes,wecanshort-circuitthis//seeWW-953andtheforumspostlinkedinthatissueformoreinforeturnsuper.getAttribute(s);}Objectattribute=super.getAttribute(s); readyIn=false;Booleanb=(Boolean)ctx.get("if(b!=null){

alreadyIn=}培培//note:wedon'tlet#comethroughorelsearequest//#attr.fooor#request.foocouldcauseanendlessif(!alreadyIn&&attribute==null&&s.indexOf("#")==-{try//Ifnotfound,thentrythectx.put("requestWrapper.getAttribute",Boolean.TRUE);stack=ctx.getValueStack();if(stack!=null)attribute=}}finallyctx.put("requestWrapper.getAttribute",}}return}}案例演示6】ValueStack演示準(zhǔn)備好Struts2導(dǎo)入Jar<?xml<?xmlversion="1.0"encoding="UTF-<!DOCTYPEstruts"-//ApacheSoftwareFoundation//DTDStrutsConfiguration"<packageoworld"extends="struts-<action<resultname="success">/WEB-<action<resultname="success">/WEB-<action<resultname="success">/WEB-<packagename="valuestack"extends="struts-default"<actionname="debug"<resultname="success">/WEB-packagepackagepublicclass{privateStringprivateintprivateString[]publicString{name=id=return}publicintgetId(){returnpublicvoidsetId(intid){this.id=publicStringgetName(){returnpublicvoidsetName(Stringname){=}}<%@pageimport="java.util.*"Enumerationen= }Objectobj=request.getAttribute("struts.valueStack");<%@tagliburi="/struts-tags"Objectobj=request.getAttribute("struts.valueStack");<!-- <s:debug通用的標(biāo)記<s:propertyvalue=<%@tagliburi="/struts-tags"<!--struts2通過標(biāo)記 <h2><s:propertyvalue="name"/><<h2><s:propertyvalue="id"<h2><s:propertypackagepackagepublicclass{privateStringprivateint;publicString{name=id=arry=newString[]"spring"};return}publicintgetId(){returnprivateString[]培培publicvoidsetId(intid){this.id=publicStringgetName(){returnpublicvoidsetName(Stringname){=publicString[]getArry(){returnpublicvoidsetArry(String[]arry){this.arry=}<%@tagliburi="/struts-tags"<s:propertyvalue="name+'java'"<s:propertyvalue="arry[1].toUpperCase()"Struts2如何支持<%@tagliburi="/struts-tags"<s:propertyvalue="name"<!--valueStack--EL中依次查找name屬性,nameDebugActionDebugAction存放于ValueStackValueStackrequest中,也就是說在rquest中,是丌能直接找到name的但是為何卻可以在頁面使用EL表達(dá)式?Struts2ELStrutsRequestWrapper,重寫了getAttribute<%@tagliburi="/struts-tags"Objectobj=注意觀察Response對象是原本的tomcat(案例結(jié)束【案例7】重構(gòu) oWorld項(xiàng)目使用Ognl表達(dá)式重構(gòu)day01Struts2oWorld頃目,將projectlist.jsp的jstl標(biāo)記改為請參考Struts2的幫助文檔(本案例中使用struts-點(diǎn)擊“Tag<%@tagliburi="/struts-tags"Project<s:iftest="page><ahref="projectlist.action?page=${1}">上一頁<s:propertyvalue="page"<s:iftest="page<<ahref="projectlist.action?page=${page+1}">下一頁<tablewidth="90%"StartEnd<s:iterator<s:propertyvalue="id"<s:propertyvalue="name"<s:propertyvalue="startDate"培培<s:propertyvalue="endDate"知識點(diǎn)列1StrutsAction深入了解Struts2Action523注 錯誤!未定義書簽 【案例1】Action演示 錯誤!未定義書簽【案例2】屬性注入 2錯誤!未定義書簽使用 【案例3】Reslut演示 【案例4】綜合練習(xí) StrutsActionActionAction基本原理Action對象將置于ValueStack的業(yè)務(wù)方法在Action中如何Mapsession=ctx.getSession();MapMapsession=ctx.getSession();Mapapplication=session,application將存放在ValueStackContext<s:property<s:property通過實(shí)現(xiàn)SessionAware<s:property<s:property首先,新建BaseActionimplements其次,所有需要sessionXXXActionextends使用通配符配置<resultname="success">/WEB-Action(屬性注入<param<paramresult的配置中使用OGNL<<resultname="success"1】Action演示使用通配符配置result的配置中使用OGNL準(zhǔn)備好Struts2Jar在Action中如何使用ActionContextpackagepackagepublicclassUserprivateint}}privateStringprivateStringpublicStringgetPassword(){returnpublicvoidsetPassword(Stringpassword){this.password=publicStringgetUsername(){returnpublicvoidsetUsername(Stringusername){this.username=publicintgetUserId(){returnpublicvoidsetUserId(intuserId){this.userId=packagecom.tarena.outman.day03.dao;packagecom.tarena.outman.day03.dao;publicclassUserDao{publicUservalidate(Stringusername,Stringpassword)/**whatisjavaif{Useruser=newUser();returnuser;}return}}<?xml<?xmlversion="1.0"encoding="UTF-<!DOCTYPEstruts"-//ApacheSoftwareFoundation//DTDStrutsConfiguration""<packagename="core"extends="struts-default"<actionname="loginform"<result<action<result<resultpackagepackageimportimportcom.tarena.outman.day03.dao.UserDao;importcom.tarena.outman.day03.entity.User;publicclassLoginActionprivateprivateUser privateUserDaouserDao=newpublttn"sfe(s;}publicStringuser=userDao.validate(user.getUsername(),user.getPassword());if(user!=null){sessionActionContextctx=ActionContext.getContext();Map<String,Object>session=ctx.getSession();session.put("day03.user",user);return}else//登錄失敗return}}publicUsergetUser(){returnpublicvoidsetUser(Useruser){this.user=}}<formaction="login.action":<inputname="user.password"type="password"<tr"提交""<%@tagliburi="/struts-tags"在頁面從session<%@tagliburi="/struts-tags"<s:propertyvalue="user.username"不使用ActionContextSession的方式,因?yàn)檫@種方式的“侵入性”較強(qiáng)ActionContextStruts2的API,如果使用其他框架代替目前的Struts2實(shí)際頃目中的Action的數(shù)量非常龐大,每個(gè)類都修改會很費(fèi)勁。ifif(user!=null)//獲得sessionActionContextctx=ActionContext.getContext();Map<String,Object>session=ctx.getSession();session.put("day03.user",user);return}else//登錄失敗return}通過實(shí)現(xiàn)SessionAware接口培packageimportimportpublicclassBaseActionimplements Map<String,Object>session;publicvoidsetSession(Map<String,Object>session)this.session=}}該類實(shí)現(xiàn)了SessionAware接口,表明Struts2在啟勱BaseAction時(shí),首先,創(chuàng)建出該Action然后,會調(diào)用BaseActionsetSession方法,把sessionBaseAction(注意:如果是普通的Action,Struts2Action按照這樣的機(jī)制,可以讓所有的Action(如LoginAction)繼承實(shí)現(xiàn)了SessionAware接口的BaseAction,當(dāng)需要更換Struts2框架為其他框架時(shí),只需要修改BaseAction即可(另外的框架只要提供一個(gè)類似SessionAware接口的接口,由BaseAction繼承)packagepackageimportimportpublicclassLoginActionextendsprivateUser privateUserDaouserDao=new}}publicStringform()return}publicStringlogin()user=user.getUsername(),if(user!=null)//ActionContextctx=//Map<String,Object>session=ctx.getSession();session.put("day03.user",user);return}elsereturn}}publicUsergetUser(){returnpublicvoidsetUser(Useruser){this.user=如果指定從session<%@tagliburi="/struts-tags"<s:propertyvalue="#session['day03.user'].username"#session['day03.usersessionMapkeyday03.user"requestresponsesessionpackagepackageimporterceptor.ServletRequestAware;importerceptor.SessionAware;importpublicclassTestpublicstaticvoidmain(String[]{SessionAwaresessAware;ServletRequestAwarea1;ServletResponseAwarea2;ServletContextAwarea3;}}使用通配符配置配置文件struts.xml中的名字里帶“<action"<result培“*_*”指名稱中有“_”下劃線的所有action(a_b.action、aaa_bbb.action),培<action<action<result同理,當(dāng)這樣寫時(shí),表明除了所調(diào)用的Action丌確定,方法也丌確定<action<action<resultjsp3“*”<action""<resultpackagepackagepublicclassOneActionpublicString{return}}}publicString{);return}packagepackagepublicclassTwoActionpublicString{return}publicString{return}}<?xml<?xmlversion="1.0"encoding="UTF-<!DOCTYPEstruts"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.1//EN" <packagename="core"extends="struts-default"<actionname="*_*_*"<result表示調(diào)用OneAction的f()方法,轉(zhuǎn)向one.jsp頁Action(注入屬性此外,還有一些屬性是Action自用的參數(shù)packagepackage培培publicclassParamAction/*input屬性///*output屬性//privateStringprivateintpublicStringSystem.out.println("param2:"+param2);returnnull;}publicStringgetParam1(){returnpublicvoidsetParam1(Stringparam1){this.param1=publicintgetParam2(){returnpublicvoidsetParam2(intparam2){this.param2=}24)/*參數(shù)<?<?xmlversion="1.0"encoding="UTF-<!DOCTYPEstruts"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.1//EN" <packagename="core"extends="struts-default"<actionname="param"<param<paramParamActionStruts2啟勱時(shí),兩個(gè)參數(shù)param1param2result的配置中使用OGNLpackagepackageimportcom.tarena.outman.day03.entity.User;{privateUserprivateUserDaouserDao=newpublicStringexecute()user=userDao.newUser();/*當(dāng)userId*userIdreturn}publicUsergetUser(){returnpublicvoidsetUser(Useruser){this.user=}importjava.util.Random;publicclassUserDao{publicUservalidate(Stringusername,Stringpassword)/**whatisjavaif{Useruser=newUser();returnuser;}return}publicUsernewUser()Useruser=newUser();RandomrnewRandom();intrn=r.nextInt(100);return}}<?xml<?xmlversion="1.0"encoding="UTF-<!<!DOCTYPEstruts"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.1//EN" <packagename="core"extends="struts-default"<actionname="user"<!--使用 --<resultname="success"<%@tagliburi="/struts-tags"out.println("<h1>"+request.getParameter("userId")+<s:propertyvalue="user.username"(案例結(jié)束【案例2】屬性注入day02102請day03案例2源碼importjava.util.List;importcom.tarena.outman.entity.Project;publicclassProjectListAction//privateintpage=// privateinttotalPages;privateintpublicStringexecute()ProjectDaoprojectDao=newProjectDao();projectList=projectDao.findAll(page,rowsPerPage);return"success";}publicintgetPage(){returnpublicintgetTotalPages(){returntotalPages;}publicvoidsetTotalPages(inttotalPages){this.totalPages=publicvoidsetPage(intpage){this.page=page;}publicList<Project>getProjectList(){returnprojectList;}publicvoidsetProjectList(List<Project>projectList){jectList=}publicintgetRowsPerPage(){returnrowsPerPage;}publicvoidsetRowsPerPage(introwsPerPage){this.rowsPerPage=}}<?xml<?xmlversion="1.0"encoding="UTF-<!DOCTYPEstruts"-//ApacheSoftwareFoundation//DTDStr

溫馨提示

  • 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)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論