spring30MVC注解附實(shí)例_第1頁(yè)
spring30MVC注解附實(shí)例_第2頁(yè)
spring30MVC注解附實(shí)例_第3頁(yè)
spring30MVC注解附實(shí)例_第4頁(yè)
spring30MVC注解附實(shí)例_第5頁(yè)
已閱讀5頁(yè),還剩31頁(yè)未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

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

文檔簡(jiǎn)介

1、0.提示1) Spring發(fā)行版本附帶了PetClinic 示例,它是一個(gè)在簡(jiǎn)單的表單處理的上下文中, 利用了本節(jié)中說(shuō)明的注解支持的Web應(yīng)用程序。 可以在“samples/petclinic ”目錄中找到PetClinic 應(yīng)用程序。 2) 另外一個(gè)建立在基于注解的Web MVC上的示例應(yīng)用程序,請(qǐng)見(jiàn)imagedb 。 這個(gè)示例集中在無(wú)狀態(tài)的multi-action控制器,包括多段文件上傳的處理。 可以在“samples/imagedb ”目錄找到imagedb 應(yīng)用程序。1.建立dispatcher實(shí)現(xiàn)注解支持只有對(duì)應(yīng)的HandlerMapping (為了實(shí)現(xiàn)類(lèi)型級(jí)別的注解)和/ 或Han

2、dlerAdapter (為了實(shí)現(xiàn)方法級(jí)別的注解)出現(xiàn)在 dispatcher中時(shí), RequestMapping 才會(huì)被處理。 這在DispatcherServlet 和DispatcherPortlet 中都是缺省的行為。 然而,如果是在定義自己的HandlerMappings 或HandlerAdapters , 就需要確保一個(gè)對(duì)應(yīng)的自定義的DefaultAnnotationHandlerMapping 和 /或AnnotationMethodHandlerAdapter 同樣被定義假設(shè)想要使用RequestMapping 。 . (controller bean definitions

3、) .例1:雁聯(lián)zfpt-servlet.xml配置DefaultAnnotationHandlerMapping 和 /或AnnotationMethodHandlerAdapter 1 例2:web.xmlSpring PetClinic Spring PetClinic sample application2.1 webAppRootKey webAppRootKey petclinic.root2.3 log4jConfigLocation log4jConfigLocation /WEB-INF/classes/perties2.4 contextConfigLocationcont

4、extConfigLocation/WEB-INF/spring/applicationContext-jdbc.xml/WEB-INF/applicationContext-security.xml !-/WEB-INF/spring/applicationContext-hibernate.xml/WEB-INF/spring/applicationContext-jpa.xml-2.5 springSecurityFilterChain springSecurityFilterChainorg.springframework.web.filter.DelegatingFilterProx

5、y springSecurityFilterChain /*2.6 Log4jConfigListenerorg.springframework.web.util.Log4jConfigListener2.7 ContextLoaderListenerorg.springframework.web.context.ContextLoaderListener2.8 DispatcherServletpetclinic org.springframework.web.servlet.DispatcherServlet2petclinic/2.9 exception.javajava.lang.Ex

6、ception/WEB-INF/jsp/uncaughtException.jsp例3:雁聯(lián)web.xml如果你想要自定義映射策略,顯式的定義一個(gè)DefaultAnnotationHandlerMapping 和 /或AnnotationMethodHandlerAdapter 也有實(shí)際意義。 例如,指定一個(gè)自定義的PathMatcher 或者WebBindingInitializer1.一個(gè)簡(jiǎn)單的基于注解的 Controller使用過(guò)低版本 Spring MVC 的讀者都知道:1.當(dāng)創(chuàng)建一個(gè) Controller 時(shí),我們需要直接或間接地實(shí)現(xiàn) org.springframework.web.

7、servlet.mvc.Controller 接口。一般情況下,我們是通過(guò)繼承 SimpleFormController 或 MultiActionController 來(lái)定義自己的 Controller 的。2.在定義 Controller 后,一個(gè)重要的事件是在 Spring MVC 的配置文件中通過(guò) HandlerMapping 定義請(qǐng)求和控制器的映射關(guān)系,以便將兩者關(guān)聯(lián)起來(lái)。3.來(lái)看一下基于注解的 Controller 是如何定義做到這一點(diǎn)的,下面是使用注解的 BbtForumController:實(shí)現(xiàn)效果:啟動(dòng) Tomcat,發(fā)送 http:/localhost/forum.do U

8、RL 請(qǐng)求,BbtForumController 的 listAllBoard() 方法將響應(yīng)這個(gè)請(qǐng)求,并轉(zhuǎn)向 WEB-INF/jsp/listBoard.jsp 的視圖頁(yè)面。清單 1. BbtForumController.javapackage com.baobaotao.web; import com.baobaotao.service.BbtForumService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;

9、import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import java.util.Collection;Controller /RequestMapping(/forum.do)public class BbtForumController Autowired private

10、BbtForumService bbtForumService; RequestMapping / public String listAllBoard() bbtForumService.getAllBoard(); System.out.println(call listAllBoard method.); return listBoard; 在 處使用了兩個(gè)注解,分別是 Controller 和 RequestMapping。在“使用 Spring 2.5 基于注解驅(qū)動(dòng)的 IoC”這篇文章里,筆者曾經(jīng)指出過(guò) Controller、Service 以及 Repository 和 Compo

11、nent 注解的作用是等價(jià)的:將一個(gè)類(lèi)成為 Spring 容器的 Bean。由于 Spring MVC 的 Controller 必須事先是一個(gè) Bean,所以 Controller 注解是不可缺少的。真正讓 BbtForumController 具備 Spring MVC Controller 功能的是 RequestMapping 這個(gè)注解。RequestMapping 可以標(biāo)注在類(lèi)定義處,將 Controller 和特定請(qǐng)求關(guān)聯(lián)起來(lái);還可以標(biāo)注在方法簽名處,以便進(jìn)一步對(duì)請(qǐng)求進(jìn)行分流。在 處,我們讓 BbtForumController 關(guān)聯(lián)“/forum.do”的請(qǐng)求,而 處,我們具體地

12、指定 listAllBoard() 方法來(lái)處理請(qǐng)求。所以在類(lèi)聲明處標(biāo)注的 RequestMapping 相當(dāng)于讓 POJO 實(shí)現(xiàn)了 Controller 接口,而在方法定義處的 RequestMapping 相當(dāng)于讓 POJO 擴(kuò)展 Spring 預(yù)定義的 Controller(如 SimpleFormController 等)。清單 2. web.xml:?jiǎn)⒂?Spring 容器和 Spring MVC 框架為了讓基于注解的 Spring MVC 真正工作起來(lái),需要在 Spring MVC 對(duì)應(yīng)的 xxx-servlet.xml 配置文件中做一些手腳。在此之前,還是先來(lái)看一下 web.xml

13、 的配置吧Spring Annotation MVC Sample contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener annomvc org.springframework.web.servlet.DispatcherServlet 2 annomvc *.do 清單 3. annomvc-servlet.xmlweb.xml 中定義了一個(gè)名為 annomvc 的 Spring MVC 模塊,按照 Spring MVC 的契約,

14、需要在 WEB-INF/annomvc-servlet.xml 配置文件中定義 Spring MVC 模塊的具體配置。annomvc-servlet.xml 的配置內(nèi)容如下所示: 因?yàn)?Spring 所有功能都在 Bean 的基礎(chǔ)上演化而來(lái),所以必須事先將 Controller 變成 Bean,這是通過(guò)在類(lèi)中標(biāo)注 Controller 并在 annomvc-servlet.xml 中啟用組件掃描機(jī)制來(lái)完成的,如 所示。在 處,配置了一個(gè) AnnotationMethodHandlerAdapter,它負(fù)責(zé)根據(jù) Bean 中的 Spring MVC 注解對(duì) Bean 進(jìn)行加工處理,使這些 Bea

15、n 變成控制器并映射特定的 URL 請(qǐng)求。而 處的工作是定義模型視圖名稱(chēng)的解析規(guī)則,這里我們使用了 Spring 2.5 的特殊命名空間,即 p 命名空間,它將原先需要通過(guò) 元素配置的內(nèi)容轉(zhuǎn)化為 屬性配置,在一定程度上簡(jiǎn)化了 的配置。2.讓一個(gè) Controller 處理多個(gè) URL 請(qǐng)求在低版本的 Spring MVC 中,我們可以通過(guò)繼承 MultiActionController 讓一個(gè) Controller 處理多個(gè) URL 請(qǐng)求。使用 RequestMapping 注解后,這個(gè)功能更加容易實(shí)現(xiàn)了。請(qǐng)看下面的代碼:清單 3. 每個(gè)請(qǐng)求處理參數(shù)對(duì)應(yīng)一個(gè) URLpackage com.ba

16、obaotao.web;import com.baobaotao.service.BbtForumService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;Controllerpublic class BbtForumController Autowired private BbtForumSe

17、rvice bbtForumService; RequestMapping(/listAllBoard.do) / public String listAllBoard() bbtForumService.getAllBoard(); System.out.println(call listAllBoard method.); return listBoard; RequestMapping(/listBoardTopic.do) / public String listBoardTopic(int topicId) bbtForumService.getBoardTopics(topicId

18、); System.out.println(call listBoardTopic method.); return listTopic; 在這里,我們分別在 和 處為 listAllBoard() 和 listBoardTopic() 方法標(biāo)注了 RequestMapping 注解,分別指定這兩個(gè)方法處理的 URL 請(qǐng)求,這相當(dāng)于將 BbtForumController 改造為 MultiActionController。這樣 /listAllBoard.do 的 URL 請(qǐng)求將由 listAllBoard() 負(fù)責(zé)處理,而 /listBoardTopic.do?topicId=1 的 UR

19、L 請(qǐng)求則由 listBoardTopic() 方法處理。清單 4. 一個(gè) Controller 對(duì)應(yīng)一個(gè) URL,由請(qǐng)求參數(shù)決定請(qǐng)求處理方法對(duì)于處理多個(gè) URL 請(qǐng)求的 Controller 來(lái)說(shuō),我們傾向于通過(guò)一個(gè) URL 參數(shù)指定 Controller 處理方法的名稱(chēng)(如 method=listAllBoard),而非直接通過(guò)不同的 URL 指定 Controller 的處理方法。使用 RequestMapping 注解很容易實(shí)現(xiàn)這個(gè)常用的需求。來(lái)看下面的代碼package com.baobaotao.web;import com.baobaotao.service.BbtForumSe

20、rvice;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;ControllerRequestMapping(/bbtForum.do) / 指定控制器對(duì)應(yīng)URL請(qǐng)求public class BbtForumController Autowired private BbtForumService bb

21、tForumService; / 如果URL請(qǐng)求中包括method=listAllBoard的參數(shù),由本方法進(jìn)行處理 RequestMapping(params = method=listAllBoard) public String listAllBoard() bbtForumService.getAllBoard(); System.out.println(call listAllBoard method.); return listBoard; / 如果URL請(qǐng)求中包括method=listBoardTopic的參數(shù),由本方法進(jìn)行處理 RequestMapping(params = m

22、ethod=listBoardTopic) public String listBoardTopic(int topicId) bbtForumService.getBoardTopics(topicId); System.out.println(call listBoardTopic method.); return listTopic; 在類(lèi)定義處標(biāo)注的 RequestMapping 讓 BbtForumController 處理所有包含 /bbtForum.do 的 URL 請(qǐng)求,而 BbtForumController 中的請(qǐng)求處理方法對(duì) URL 請(qǐng)求的分流規(guī)則在 和 處定義分流規(guī)則按

23、照 URL 的 method 請(qǐng)求參數(shù)確定。所以分別在類(lèi)定義處和方法定義處使用 RequestMapping 注解,就可以很容易通過(guò) URL 參數(shù)指定 Controller 的處理方法了。清單5. 讓請(qǐng)求處理方法處理特定的 HTTP 請(qǐng)求方法RequestMapping 注解中除了 params 屬性外,還有一個(gè)常用的屬性是 method,它可以讓 Controller 方法處理特定 HTTP 請(qǐng)求方式的請(qǐng)求,如讓一個(gè)方法處理 HTTP GET 請(qǐng)求,而另一個(gè)方法處理 HTTP POST 請(qǐng)求,如下所示:package com.baobaotao.web;import com.baobaota

24、o.service.BbtForumService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;ControllerRequestMapping(/bbtForum.do) p

25、ublic class BbtForumController RequestMapping(params = method=createTopic, method = RequestMethod.POST) public String createTopic() System.out.println(call createTopic method.); return createTopic; 這樣只有當(dāng) /bbtForum.do?method=createTopic 請(qǐng)求以 HTTP POST 方式提交時(shí),createTopic()才會(huì)進(jìn)行處理。3.處理 方法入?yún)?如何 綁定 URL參數(shù)3.1

26、 按契約綁定Controller 的方法標(biāo)注了 RequestMapping 注解后,它就能處理特定的 URL 請(qǐng)求。我們不禁要問(wèn):請(qǐng)求處理方法入?yún)⑹侨绾谓壎?URL 參數(shù)的呢?在回答這個(gè)問(wèn)題之前先來(lái)看下面的代碼清單 5. 按參數(shù)名匹配進(jìn)行綁定RequestMapping(params = method=listBoardTopic) / topicId入?yún)⑹侨绾谓壎║RL請(qǐng)求參數(shù)的? public String listBoardTopic(int topicId) bbtForumService.getBoardTopics(topicId); System.out.println(cal

27、l listBoardTopic method.); return listTopic; 當(dāng)我們發(fā)送 http:/localhost/bbtForum.do?method=listBoardTopic&topicId=10 的 URL 請(qǐng)求時(shí),Spring 不但讓 listBoardTopic() 方法處理這個(gè)請(qǐng)求,而且還將 topicId 請(qǐng)求參數(shù)在類(lèi)型轉(zhuǎn)換后綁定到 listBoardTopic() 方法的 topicId 入?yún)⑸稀6?listBoardTopic() 方法的返回類(lèi)型是 String,它將被解析為邏輯視圖的名稱(chēng)。也就是說(shuō) Spring 在如何給處理方法入?yún)⒆詣?dòng)賦值以及如何將處

28、理方法返回值轉(zhuǎn)化為 ModelAndView 中的過(guò)程中存在一套潛在的規(guī)則,不熟悉這個(gè)規(guī)則就不可能很好地開(kāi)發(fā)基于注解的請(qǐng)求處理方法,因此了解這個(gè)潛在規(guī)則無(wú)疑成為理解 Spring MVC 框架基于注解功能的核心問(wèn)題。我們不妨從最常見(jiàn)的開(kāi)始說(shuō)起:請(qǐng)求處理方法入?yún)⒌念?lèi)型可以是 Java 基本數(shù)據(jù)類(lèi)型或 String 類(lèi)型,這時(shí)方法入?yún)磪?shù)名匹配的原則綁定到 URL 請(qǐng)求參數(shù),同時(shí)還自動(dòng)完成 String 類(lèi)型的 URL 請(qǐng)求參數(shù)到請(qǐng)求處理方法參數(shù)類(lèi)型的轉(zhuǎn)換。下面給出幾個(gè)例子:listBoardTopic(int topicId):和 topicId URL 請(qǐng)求參數(shù)綁定; listBoardTo

29、pic(int topicId,String boardName):分別和 topicId、boardName URL 請(qǐng)求參數(shù)綁定; 特別的,如果入?yún)⑹腔緮?shù)據(jù)類(lèi)型(如 int、long、float 等),URL 請(qǐng)求參數(shù)中一定要有對(duì)應(yīng)的參數(shù),否則將拋出 TypeMismatchException 異常,提示無(wú)法將 null 轉(zhuǎn)換為基本數(shù)據(jù)類(lèi)型。清單 6. User.java:一個(gè) JavaBean另外,請(qǐng)求處理方法的入?yún)⒁部梢砸粋€(gè) JavaBean,如下面的 User 對(duì)象就可以作為一個(gè)入?yún)ackage com.baobaotao.web;public class User privat

30、e int userId; private String userName; /省略get/setter方法 public String toString() return this.userName +,+this.userId; 清單 7. 使用 JavaBean 作為請(qǐng)求處理方法的入?yún)⑾旅媸菍?User 作為 listBoardTopic() 請(qǐng)求處理方法的入?yún)ⅲ篟equestMapping(params = method=listBoardTopic) public String listBoardTopic(int topicId,User user) bbtForumService

31、.getBoardTopics(topicId); System.out.println(topicId:+topicId); System.out.println(user:+user); System.out.println(call listBoardTopic method.); return listTopic; 這時(shí),如果我們使用以下的 URL 請(qǐng)求:http:/localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tom topicId URL 參數(shù)將綁定到 topicId 入?yún)⑸?,?u

32、serId 和 userName URL 參數(shù)將綁定到 user 對(duì)象的 userId 和 userName 屬性中。和 URL 請(qǐng)求中不允許沒(méi)有 topicId 參數(shù)不同,雖然 User 的 userId 屬性的類(lèi)型是基本數(shù)據(jù)類(lèi)型,但如果 URL 中不存在 userId 參數(shù),Spring 也不會(huì)報(bào)錯(cuò),此時(shí) user.userId 值為 0。如果 User 對(duì)象擁有一個(gè) dept.deptId 的級(jí)聯(lián)屬性,那么它將和 dept.deptId URL 參數(shù)綁定。3.2通過(guò)注解指定綁定的 URL 參數(shù)如果我們想改變這種默認(rèn)的按名稱(chēng)匹配的策略,比如讓 listBoardTopic(int topi

33、cId,User user) 中的 topicId 綁定到 id 這個(gè) URL 參數(shù),那么可以通過(guò)對(duì)入?yún)⑹褂?RequestParam 注解來(lái)達(dá)到目的:清單 8. 通過(guò) RequestParam 注解指定這里,對(duì) listBoardTopic() 請(qǐng)求處理方法的 topicId 入?yún)?biāo)注了 RequestParam(id) 注解,所以它將和 id 的 URL 參數(shù)綁定。package com.baobaotao.web;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework

34、.web.bind.annotation.RequestParam; ControllerRequestMapping(/bbtForum.do)public class BbtForumController RequestMapping(params = method=listBoardTopic)public String listBoardTopic(RequestParam(id) int topicId, User user) bbtForumService.getBoardTopics(topicId); System.out.println(topicId:+topicId);

35、System.out.println(user:+user); System.out.println(call listBoardTopic method.); return listTopic; 這里RequestParam注解可以用來(lái)提取名為“topicId”的int類(lèi)型的參數(shù),并將之作為輸入?yún)?shù)傳入。 RequestParam支持類(lèi)型轉(zhuǎn)換,還有必需和可選參數(shù)。類(lèi)型轉(zhuǎn)換目前支持所有的基本Java類(lèi)型,你可通過(guò)定制的PropertyEditors 來(lái)擴(kuò)展它的范圍。下面是一些例子,其中包括了必需和可選參數(shù):RequestParam(value=number, required=false) S

36、tring numberRequestParam(id) Long idRequestParam(balance) double balanceRequestParam double amount注意,最后一個(gè)例子沒(méi)有提供清晰的參數(shù)名。當(dāng)且僅當(dāng)代碼帶調(diào)試符號(hào)編譯時(shí),結(jié)果會(huì)提取名為“amount ”的參數(shù),否則,將拋出IllegalStateException異常,因?yàn)楫?dāng)前的信息不足以從請(qǐng)求中提取參數(shù)。由于這個(gè)原因,在編碼時(shí)最好顯式的指定參數(shù)名。3.3 綁定模型對(duì)象中某個(gè)屬性ModelMapSpring 2.0 定義了一個(gè) org.springframework.ui.ModelMap 類(lèi),它作

37、為通用的模型數(shù)據(jù)承載對(duì)象,傳遞數(shù)據(jù)供視圖所用。我們可以在請(qǐng)求處理方法中聲明一個(gè) ModelMap 類(lèi)型的入?yún)?,Spring 會(huì)將本次請(qǐng)求模型對(duì)象引用通過(guò)該入?yún)鬟f進(jìn)來(lái),這樣就可以在請(qǐng)求處理方法內(nèi)部訪問(wèn)模型對(duì)象了。來(lái)看下面的例子:清單 9. 使用 ModelMap 訪問(wèn)請(qǐng)示對(duì)應(yīng)的隱含模型對(duì)象RequestMapping(params = method=listBoardTopic) public String listBoardTopic(RequestParam(id)int topicId, User user, ModelMap model) bbtForumService.getBoar

38、dTopics(topicId); System.out.println(topicId: + topicId); System.out.println(user: + user); / 將user對(duì)象以currUser為鍵放入到model中 model.addAttribute(currUser,user); return listTopic; 對(duì)于當(dāng)次請(qǐng)求所對(duì)應(yīng)的模型對(duì)象來(lái)說(shuō),其所有屬性都將存放到 request 的屬性列表中。象上面的例子,ModelMap 中的 currUser 屬性將放到 request 的屬性列表中,所以可以在 JSP 視圖頁(yè)面中通過(guò) request.getAttr

39、ibute(“currUser”) 或者通過(guò) $currUser EL 表達(dá)式訪問(wèn)模型對(duì)象中的 user 對(duì)象。從這個(gè)角度上看, ModelMap 相當(dāng)于是一個(gè)向 request 屬性列表中添加對(duì)象的一條管道,借由 ModelMap 對(duì)象的支持,我們可以在一個(gè)不依賴(lài) Servlet API 的 Controller 中向 request 中添加屬性。清單 10. 使模型對(duì)象的特定屬性具有 Session 范圍的作用域在默認(rèn)情況下,ModelMap 中的屬性作用域是 request 級(jí)別,也就是說(shuō),當(dāng)本次請(qǐng)求結(jié)束后,ModelMap 中的屬性將銷(xiāo)毀。如果希望在多個(gè)請(qǐng)求中共享 ModelMap 中

40、的屬性,必須將其屬性轉(zhuǎn)存到 session 中,這樣 ModelMap 的屬性才可以被跨請(qǐng)求訪問(wèn)。Spring 允許我們有選擇地指定 ModelMap 中的哪些屬性需要轉(zhuǎn)存到 session 中,以便下一個(gè)請(qǐng)求屬對(duì)應(yīng)的 ModelMap 的屬性列表中還能訪問(wèn)到這些屬性。這一功能是通過(guò)類(lèi)定義處標(biāo)注 SessionAttributes 注解來(lái)實(shí)現(xiàn)的。請(qǐng)看下面的代碼:package com.baobaotao.web;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.Sessio

41、nAttributes;ControllerRequestMapping(/bbtForum.do)SessionAttributes(currUser) /將ModelMap中屬性名為currUser的屬性/放到Session屬性列表中,以便這個(gè)屬性可以跨請(qǐng)求訪問(wèn)public class BbtForumController RequestMapping(params = method=listBoardTopic)public String listBoardTopic(RequestParam(id)int topicId, User user,ModelMap model) bbtFo

42、rumService.getBoardTopics(topicId); System.out.println(topicId: + topicId); System.out.println(user: + user); model.addAttribute(currUser,user); /向ModelMap中添加一個(gè)屬性 return listTopic; 我們?cè)?處添加了一個(gè) ModelMap 屬性,其屬性名為 currUser,而 處通過(guò) SessionAttributes 注解將 ModelMap 中名為 currUser 的屬性放置到 Session 中,所以我們不但可以在 list

43、BoardTopic() 請(qǐng)求所對(duì)應(yīng)的 JSP 視圖頁(yè)面中通過(guò) request.getAttribute(“currUser”) 和 session.getAttribute(“currUser”) 獲取 user 對(duì)象,還可以在下一個(gè)請(qǐng)求所對(duì)應(yīng)的 JSP 視圖頁(yè)面中通過(guò) session.getAttribute(“currUser”) 或 ModelMap#get(“currUser”) 訪問(wèn)到這個(gè)屬性。1)這里我們僅將一個(gè) ModelMap 的屬性放入 Session 中,其實(shí) SessionAttributes 允許指定多個(gè)屬性: 你可以通過(guò)字符串?dāng)?shù)組的方式指定多個(gè)屬性,如 Sessio

44、nAttributes(“attr1”,”attr2”)。2)此外,SessionAttributes 還可以通過(guò)屬性類(lèi)型指定要 session 化的 ModelMap 屬性: 如 SessionAttributes(types = User.class), 當(dāng)然也可以指定多個(gè)類(lèi),如 SessionAttributes(types = User.class,Dept.class),3)還可以聯(lián)合使用屬性名和屬性類(lèi)型指定: SessionAttributes(types = User.class,Dept.class,value=“attr1”,”attr2”)。清單 11. 使模型對(duì)象的特定屬

45、性具有 Session 范圍的作用域上面講述了如何往ModelMap中放置屬性以及如何使ModelMap中的屬性擁有Session域的作用范圍。除了在JSP視圖頁(yè)面中通過(guò)傳統(tǒng)的方法訪問(wèn)ModelMap中的屬性外,讀者朋友可能會(huì)問(wèn):是否可以將ModelMap中的屬性綁定到請(qǐng)求處理方法的入?yún)⒅心??答案是肯定的。Spring為此提供了一個(gè)ModelAttribute的注解,下面是使用ModelAttribute注解的例子ControllerRequestMapping(/bbtForum.do)SessionAttributes(currUser) /讓ModelMap的currUser屬性擁有se

46、ssion級(jí)作用域public class BbtForumController Autowiredprivate BbtForumService bbtForumService; RequestMapping(params = method=listBoardTopic)public String listBoardTopic(RequestParam(id)int topicId, User user, ModelMap model) bbtForumService.getBoardTopics(topicId); System.out.println(topicId: + topicId

47、); System.out.println(user: + user); model.addAttribute(currUser,user); /向ModelMap中添加一個(gè)屬性 return listTopic; /將ModelMap中的currUser屬性綁定到user入?yún)⒅?。因?yàn)閏urrUser是session級(jí)別的RequestMapping(params = method=listAllBoard) public String listAllBoard(ModelAttribute(currUser) User user) bbtForumService.getAllBoard();

48、 System.out.println(user:+user); return listBoard; 在 處,我們向 ModelMap 中添加一個(gè)名為 currUser 的屬性,而 外的注解使這個(gè) currUser 屬性擁有了 session 級(jí)的作用域。所以,我們可以在 處通過(guò) ModelAttribute 注解將 ModelMap 中的 currUser 屬性綁定以請(qǐng)求處理方法的 user 入?yún)⒅?。所以?dāng)我們先調(diào)用以下 URL 請(qǐng)求: http:/localhost/bbtForum.do?method=listBoardTopic&id=1&userName=tom&dept.deptI

49、d=12 以執(zhí)行l(wèi)istBoardTopic()請(qǐng)求處理方法,然后再訪問(wèn)以下URL: http:/localhost/sample/bbtForum.do?method=listAllBoard你將可以看到 listAllBoard() 的 user 入?yún)⒁呀?jīng)成功綁定到 listBoardTopic() 中注冊(cè)的 session 級(jí)的 currUser 屬性上了4.請(qǐng)求處理方法的簽名規(guī)約4.1 方法入?yún)⑽覀冎罉?biāo)注了 RequestMapping 注解的 Controller 方法就成為了請(qǐng)求處理方法,Spring MVC 允許極其靈活的請(qǐng)求處理方法簽名方式。對(duì)于方法入?yún)?lái)說(shuō),它允許多種類(lèi)型的

50、入?yún)?,通過(guò)下表進(jìn)行說(shuō)明請(qǐng)求處理方法入?yún)⒌目蛇x類(lèi)型說(shuō)明Java 基本數(shù)據(jù)類(lèi)型和 String默認(rèn)情況下將按名稱(chēng)匹配的方式綁定到 URL 參數(shù)上,可以通過(guò) RequestParam 注解改變默認(rèn)的綁定規(guī)則request/response/session既可以是 Servlet API 的也可以是 Portlet API 對(duì)應(yīng)的對(duì)象,Spring 會(huì)將它們綁定到 Servlet 和 Portlet 容器的相應(yīng)對(duì)象上內(nèi)部包含了 request 對(duì)象綁定到 request 對(duì)應(yīng)的 Locale 對(duì)象上可以借此訪問(wèn) request 的內(nèi)容可以借此操作 response 的內(nèi)容任何標(biāo)注了 RequestPa

51、ram 注解的入?yún)⒈粯?biāo)注 RequestParam 注解的入?yún)⒔壎ǖ教囟ǖ?request 參數(shù)上。它綁定 Spring MVC 框架中每個(gè)請(qǐng)求所創(chuàng)建的潛在的模型對(duì)象,它們可以被 Web 視圖對(duì)象訪問(wèn)(如 JSP)命令/表單對(duì)象(注:一般稱(chēng)綁定使用 HTTP GET 發(fā)送的 URL 參數(shù)的對(duì)象為命令對(duì)象,而稱(chēng)綁定使用 HTTP POST 發(fā)送的 URL 參數(shù)的對(duì)象為表單對(duì)象)它們的屬性將以名稱(chēng)匹配的規(guī)則綁定到 URL 參數(shù)上,同時(shí)完成類(lèi)型的轉(zhuǎn)換。而類(lèi)型轉(zhuǎn)換的規(guī)則可以通過(guò) InitBinder 注解或通過(guò) HandlerAdapter 的配置進(jìn)行調(diào)整org.springframework.va

52、lidation.Errors/ org.springframework.validation.BindingResult為屬性列表中的命令/表單對(duì)象的校驗(yàn)結(jié)果,注意檢驗(yàn)結(jié)果參數(shù)必須緊跟在命令/表單對(duì)象的后面可以通過(guò)該類(lèi)型 status 對(duì)象顯式結(jié)束表單的處理,這相當(dāng)于觸發(fā) session 清除其中的通過(guò) SessionAttributes 定義的屬性Spring MVC 框架的易用之處在于,你可以按任意順序定義請(qǐng)求處理方法的入?yún)ⅲǔ?Errors 和 BindingResult 必須緊跟在命令對(duì)象/表單參數(shù)后面以外),Spring MVC 會(huì)根據(jù)反射機(jī)制自動(dòng)將對(duì)應(yīng)的對(duì)象通過(guò)入?yún)鬟f給請(qǐng)求處

53、理方法。這種機(jī)制讓開(kāi)發(fā)者完全可以不依賴(lài) Servlet API 開(kāi)發(fā)控制層的程序,當(dāng)請(qǐng)求處理方法需要特定的對(duì)象時(shí),僅僅需要在參數(shù)列表中聲明入?yún)⒓纯?,不需要考慮如何獲取這些對(duì)象,Spring MVC 框架就象一個(gè)大管家一樣“不辭辛苦”地為我們準(zhǔn)備好了所需的一切。下面演示一下使用 SessionStatus 的例子:清單 12. 使用 SessionStatus 控制 Session 級(jí)別的模型屬性RequestMapping(method = RequestMethod.POST)public String processSubmit(ModelAttribute Owner owner, Bi

54、ndingResult result, SessionStatus status) / new OwnerValidator().validate(owner, result); if (result.hasErrors() return ownerForm; else this.clinic.storeOwner(owner); status.setComplete();/ return redirect:owner.do?ownerId= + owner.getId(); processSubmit() 方法中的 owner 表單對(duì)象將綁定到 ModelMap 的“owner”屬性中,re

55、sult 參數(shù)用于存放檢驗(yàn) owner 結(jié)果的對(duì)象,而 status 用于控制表單處理的狀態(tài)。在 處,我們通過(guò)調(diào)用 status.setComplete() 方法,該 Controller 所有放在 session 級(jí)別的模型屬性數(shù)據(jù)將從 session 中清空。在默認(rèn)情況下,ModelMap 中的屬性作用域是 request 級(jí)別是,也就是說(shuō),當(dāng)本次請(qǐng)求結(jié)束后,ModelMap 中的屬性將銷(xiāo)毀。如果希望在多個(gè)請(qǐng)求中共享 ModelMap 中的屬性,必須將其屬性轉(zhuǎn)存到 session 中,這樣 ModelMap 的屬性才可以被跨請(qǐng)求訪問(wèn)。Spring 允許我們有選擇地指定 ModelMap 中

56、的哪些屬性需要轉(zhuǎn)存到 session 中,以便下一個(gè)請(qǐng)求屬對(duì)應(yīng)的 ModelMap 的屬性列表中還能訪問(wèn)到這些屬性。這一功能是通過(guò)類(lèi)定義處標(biāo)注 SessionAttributes 注解來(lái)實(shí)現(xiàn)的。請(qǐng)看下面的代碼:清單 10. 使模型對(duì)象的特定屬性具有 Session 范圍的作用域package com.baobaotao.web;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.SessionAttributes;ControllerRequestMapping(/bbtFo

57、rum.do)SessionAttributes(currUser) /將ModelMap中屬性名為currUser的屬性/放到Session屬性列表中,以便這個(gè)屬性可以跨請(qǐng)求訪問(wèn)public class BbtForumController RequestMapping(params = method=listBoardTopic)public String listBoardTopic(RequestParam(id)int topicId, User user,ModelMap model) bbtForumService.getBoardTopics(topicId); System.

58、out.println(topicId: + topicId); System.out.println(user: + user); model.addAttribute(currUser,user); /向ModelMap中添加一個(gè)屬性 return listTopic; 我們?cè)?處添加了一個(gè) ModelMap 屬性,其屬性名為 currUser,而 處通過(guò) SessionAttributes 注解將 ModelMap 中名為 currUser 的屬性放置到 Session 中,所以我們不但可以在 listBoardTopic() 請(qǐng)求所對(duì)應(yīng)的 JSP 視圖頁(yè)面中通過(guò) request.get

59、Attribute(“currUser”) 和 session.getAttribute(“currUser”) 獲取 user 對(duì)象,還可以在下一個(gè)請(qǐng)求所對(duì)應(yīng)的 JSP 視圖頁(yè)面中通過(guò) session.getAttribute(“currUser”) 或 ModelMap#get(“currUser”) 訪問(wèn)到這個(gè)屬性。1)這里我們僅將一個(gè) ModelMap 的屬性放入 Session 中,其實(shí) SessionAttributes 允許指定多個(gè)屬性: 你可以通過(guò)字符串?dāng)?shù)組的方式指定多個(gè)屬性,如 SessionAttributes(“attr1”,”attr2”)。2)此外,SessionAt

60、tributes 還可以通過(guò)屬性類(lèi)型指定要 session 化的 ModelMap 屬性: 如 SessionAttributes(types = User.class), 當(dāng)然也可以指定多個(gè)類(lèi),如 SessionAttributes(types = User.class,Dept.class),3)還可以聯(lián)合使用屬性名和屬性類(lèi)型指定: SessionAttributes(types = User.class,Dept.class,value=“attr1”,”attr2”)。清單 11. 使模型對(duì)象的特定屬性具有 Session 范圍的作用域上面講述了如何往ModelMap中放置屬性以及如何

溫馨提示

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

評(píng)論

0/150

提交評(píng)論