溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Spring MVC 3.0 深入及對(duì)注解的詳細(xì)講解

發(fā)布時(shí)間:2020-06-26 20:56:32 來(lái)源:網(wǎng)絡(luò) 閱讀:294 作者:沙漏半杯 欄目:編程語(yǔ)言

核心原理

1.? ? ? ?用戶發(fā)送請(qǐng)求給服務(wù)器。url:user.do


2.? ? ? ?服務(wù)器收到請(qǐng)求。發(fā)現(xiàn)Dispatchservlet可以處理。于是調(diào)用DispatchServlet。


3.? ? ? DispatchServlet內(nèi)部,通過(guò)HandleMapping檢查這個(gè)url有沒(méi)有對(duì)應(yīng)的Controller。如果有,則調(diào)用Controller。


4、? ? Control開(kāi)始執(zhí)行


5.? ? ? Controller執(zhí)行完畢后,如果返回字符串,則ViewResolver將字符串轉(zhuǎn)化成相應(yīng)的視圖對(duì)象;如果返回ModelAndView對(duì)象,該對(duì)象本身就包含了視圖對(duì)象信息。


6.? ? ? DispatchServlet將執(zhí)視圖對(duì)象中的數(shù)據(jù),輸出給服務(wù)器。


7.? ? ? 服務(wù)器將數(shù)據(jù)輸出給客戶端。


spring3.0中相關(guān)jar包的含義

org.springframework.aop-3.0.3.RELEASE.jar


spring的aop面向切面編程


org.springframework.asm-3.0.3.RELEASE.jar


spring獨(dú)立的asm字節(jié)碼生成程序


org.springframework.beans-3.0.3.RELEASE.jar


IOC的基礎(chǔ)實(shí)現(xiàn)


org.springframework.context-3.0.3.RELEASE.jar


IOC基礎(chǔ)上的擴(kuò)展服務(wù)


org.springframework.core-3.0.3.RELEASE.jar


spring的核心包


org.springframework.expression-3.0.3.RELEASE.jar


spring的表達(dá)式語(yǔ)言


org.springframework.web-3.0.3.RELEASE.jar


web工具包


org.springframework.web.servlet-3.0.3.RELEASE.jar


mvc工具包


?


@Controller控制器定義

和Struts1一樣,Spring的Controller是Singleton的。這就意味著會(huì)被多個(gè)請(qǐng)求線程共享。因此,我們將控制器設(shè)計(jì)成無(wú)狀態(tài)類。


?


在spring 3.0中,通過(guò)@controller標(biāo)注即可將class定義為一個(gè)controller類。為使spring能找到定義為controller的bean,需要在spring-context配置文件中增加如下定義:


?


<context:component-scan base-package="com.sxt.web"/>


?


? ? ? ? 注:實(shí)際上,使用@component,也可以起到@Controller同樣的作用。


@RequestMapping

?


? ? 在類前面定義,則將url和類綁定。


? ?在方法前面定義,則將url和類的方法綁定


@RequestParam

? ? ? ? ?一般用于將指定的請(qǐng)求參數(shù)付給方法中形參。示例代碼如下:


? ? ? ??


@RequestMapping(params="method=reg5")


? ? public String reg5(@RequestParam("name")String uname,ModelMap map) {


? ? ? ?System.out.println("HelloController.handleRequest()");


? ? ? ?System.out.println(uname);


? ? ? ?return"index";


? ? }


? ?這樣,就會(huì)將name參數(shù)的值付給uname。當(dāng)然,如果請(qǐng)求參數(shù)名稱和形參名稱保持一致,則不需要這種寫(xiě)法。


@SessionAttributes

? ? 將ModelMap中指定的屬性放到session中。示例代碼如下:


? ?


@Controller


@RequestMapping("/user.do")


@SessionAttributes({"u","a"})? //將ModelMap中屬性名字為u、a的再放入session中。這樣,request和session中都有了。


publicclass UserController {


? ? @RequestMapping(params="method=reg4")


? ? public String reg4(ModelMap map) {? ? ? ? System.out.println("HelloController.handleRequest()");


? ? ? ?map.addAttribute("u","uuuu"); //將u放入request作用域中,這樣轉(zhuǎn)發(fā)頁(yè)面也可以取到這個(gè)數(shù)據(jù)。


? ? ? ?return"index";


? ? }


}


? <body>


? ?<h2>**********${requestScope.u.uname}</h2>


? ?<h2>**********${sessionScope.u.uname}</h2>


? </body>


? ?


? ? 注:名字為”user”的屬性再結(jié)合使用注解@SessionAttributes可能會(huì)報(bào)錯(cuò)。


?


@ModelAttribute

? ? ?這個(gè)注解可以跟@SessionAttributes配合在一起用??梢詫odelMap中屬性的值通過(guò)該注解自動(dòng)賦給指定變量。


? ? 示例代碼如下:


package com.sxt.web;


import javax.annotation.Resource;


import org.springframework.stereotype.Controller;


import org.springframework.ui.ModelMap;


import org.springframework.web.bind.annotation.ModelAttribute;


import org.springframework.web.bind.annotation.RequestMapping;


import org.springframework.web.bind.annotation.SessionAttributes;


@Controller


@RequestMapping("/user.do")


@SessionAttributes({"u","a"})?


publicclass UserController {


? ?


? ? @RequestMapping(params="method=reg4")


? ? public String reg4(ModelMap map) {


? ? ? ?System.out.println("HelloController.handleRequest()");


? ? ? ?map.addAttribute("u","尚學(xué)堂高淇");


? ? ? ?return"index";


? ? }


? ?


? ? @RequestMapping(params="method=reg5")


public String reg5(@ModelAttribute("u")String uname ,ModelMap map) {


? ? ? ?System.out.println("HelloController.handleRequest()");


? ? ? ?System.out.println(uname);


? ? ? ?return"index";


? ? }


? ?


}


?


先調(diào)用reg4方法,再調(diào)用reg5方法。?


Controller類中方法參數(shù)的處理

?


Controller類中方法返回值的處理

1.? ? ? ?返回string(建議)


a)? ? ? ? ?根據(jù)返回值找對(duì)應(yīng)的顯示頁(yè)面。路徑規(guī)則為:prefix前綴+返回值+suffix后綴組成


b)? ? ? ? ?代碼如下:


@RequestMapping(params="method=reg4")


? ? public String reg4(ModelMap map) {


? ? ? ?System.out.println("HelloController.handleRequest()");


? ? ? ?return"index";


? ? }


前綴為:/WEB-INF/jsp/? ?后綴是:.jsp


在轉(zhuǎn)發(fā)到:/WEB-INF/jsp/index.jsp


?


2.? ? ? ?也可以返回ModelMap、ModelAndView、map、List、Set、Object、無(wú)返回值。一般建議返回字符串!


?


請(qǐng)求轉(zhuǎn)發(fā)和重定向

? ? ? ? ?代碼示例:


? ? ? ??


package com.sxt.web;


?


import javax.annotation.Resource;


import org.springframework.stereotype.Controller;


import org.springframework.ui.ModelMap;


import org.springframework.web.bind.annotation.ModelAttribute;


import org.springframework.web.bind.annotation.RequestMapping;


import org.springframework.web.bind.annotation.SessionAttributes;


?


@Controller


@RequestMapping("/user.do")


publicclass UserController {


? ?


? ? @RequestMapping(params="method=reg4")


? ? public String reg4(ModelMap map) {


? ? ? ?System.out.println("HelloController.handleRequest()");


//? ? ?return "forward:index.jsp";


//? ? ?return "forward:user.do?method=reg5"; //轉(zhuǎn)發(fā)


//? ? ?return "redirect:user.do?method=reg5";? //重定向


? ? ? ?return"redirect:http://www.baidu.com"; //重定向


? ? }


? ?


? ? @RequestMapping(params="method=reg5")


? ? public String reg5(String uname,ModelMap map) {


? ? ? ?System.out.println("HelloController.handleRequest()");


? ? ? ?System.out.println(uname);


? ? ? ?return"index";


? ? }


? ?


}


? ? ? ??


? ? ? ? ?訪問(wèn)reg4方法,既可以看到效果。


??


獲得request對(duì)象、session對(duì)象

普通的Controller類,示例代碼如下:


@Controller


@RequestMapping("/user.do")


publicclass UserController {


? ?


? ? @RequestMapping(params="method=reg2")


? ? public String reg2(String uname,HttpServletRequest req,ModelMap map){


? ? ? ?req.setAttribute("a","aa");


? ? ? ?req.getSession().setAttribute("b","bb");


? ? ? ?return"index";


? ? }


}


?


ModelMap

? ? ? ? ?是map的實(shí)現(xiàn),可以在其中存放屬性,作用域同request。下面這個(gè)示例,我們可以在modelMap中放入數(shù)據(jù),然后在forward的頁(yè)面上顯示這些數(shù)據(jù)。通過(guò)el表達(dá)式、JSTL、java代碼均可。代碼如下:


? ? ? ??


package com.sxt.web;


?


import org.springframework.stereotype.Controller;


import org.springframework.ui.ModelMap;


import org.springframework.web.bind.annotation.RequestMapping;


import org.springframework.web.servlet.mvc.multiaction.MultiActionController;


?


@Controller


@RequestMapping("/user.do")


publicclass UserControllerextends MultiActionController {


? ?


? ? @RequestMapping(params="method=reg")


? ? public String reg(String uname,ModelMap map){


? ? ? ?map.put("a","aaa");


? ? ? ?return"index";


? ? }


}


<%@ page language="java"import="java.util.*"pageEncoding="gbk"%>


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


<!DOCTYPEHTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<html>


? <head></head>


? <body>


? ? ? ?<h2>${requestScope.a}</h2>


? ? ? ?<c:out value="${requestScope.a}"></c:out>


? </body>


</html>


將屬性u(píng)的值賦給形參uname


ModelAndView模型視圖類

見(jiàn)名知意,從名字上我們可以知道ModelAndView中的Model代表模型,View代表視圖。即,這個(gè)類把要顯示的數(shù)據(jù)存儲(chǔ)到了Model屬性中,要跳轉(zhuǎn)的視圖信息存儲(chǔ)到了view屬性。我們看一下ModelAndView的部分源碼,即可知其中關(guān)系:


[java] view plaincopy

public class ModelAndView {??

??

? ? /** View instance or view name String */??

? ? private Object view;??

??

? ? /** Model Map */??

? ? private ModelMap model;??

??

? ? /**?

? ? ?* Indicates whether or not this instance has been cleared with a call to {@link #clear()}.?

? ? ?*/??

? ? private boolean cleared = false;??

??

??

? ? /**?

? ? ?* Default constructor for bean-style usage: populating bean?

? ? ?* properties instead of passing in constructor arguments.?

? ? ?* @see #setView(View)?

? ? ?* @see #setViewName(String)?

? ? ?*/??

? ? public ModelAndView() {??

? ? }??

??

? ? /**?

? ? ?* Convenient constructor when there is no model data to expose.?

? ? ?* Can also be used in conjunction with <code>addObject</code>.?

? ? ?* @param viewName name of the View to render, to be resolved?

? ? ?* by the DispatcherServlet's ViewResolver?

? ? ?* @see #addObject?

? ? ?*/??

? ? public ModelAndView(String viewName) {??

? ? ? ? this.view = viewName;??

? ? }??

??

? ? /**?

? ? ?* Convenient constructor when there is no model data to expose.?

? ? ?* Can also be used in conjunction with <code>addObject</code>.?

? ? ?* @param view View object to render?

? ? ?* @see #addObject?

? ? ?*/??

? ? public ModelAndView(View view) {??

? ? ? ? this.view = view;??

? ? }??

??

? ? /**?

? ? ?* Creates new ModelAndView given a view name and a model.?

? ? ?* @param viewName name of the View to render, to be resolved?

? ? ?* by the DispatcherServlet's ViewResolver?

? ? ?* @param model Map of model names (Strings) to model objects?

? ? ?* (Objects). Model entries may not be <code>null</code>, but the?

? ? ?* model Map may be <code>null</code> if there is no model data.?

? ? ?*/??

? ? public ModelAndView(String viewName, Map<String, ?> model) {??

? ? ? ? this.view = viewName;??

? ? ? ? if (model != null) {??

? ? ? ? ? ? getModelMap().addAllAttributes(model);??

? ? ? ? }??

? ? }??

??

? ? /**?

? ? ?* Creates new ModelAndView given a View object and a model.?

? ? ?* <emphasis>Note: the supplied model data is copied into the internal?

? ? ?* storage of this class. You should not consider to modify the supplied?

? ? ?* Map after supplying it to this class</emphasis>?

? ? ?* @param view View object to render?

? ? ?* @param model Map of model names (Strings) to model objects?

? ? ?* (Objects). Model entries may not be <code>null</code>, but the?

? ? ?* model Map may be <code>null</code> if there is no model data.?

? ? ?*/??

? ? public ModelAndView(View view, Map<String, ?> model) {??

? ? ? ? this.view = view;??

? ? ? ? if (model != null) {??

? ? ? ? ? ? getModelMap().addAllAttributes(model);??

? ? ? ? }??

? ? }??

??

? ? /**?

? ? ?* Convenient constructor to take a single model object.?

? ? ?* @param viewName name of the View to render, to be resolved?

? ? ?* by the DispatcherServlet's ViewResolver?

? ? ?* @param modelName name of the single entry in the model?

? ? ?* @param modelObject the single model object?

? ? ?*/??

? ? public ModelAndView(String viewName, String modelName, Object modelObject) {??

? ? ? ? this.view = viewName;??

? ? ? ? addObject(modelName, modelObject);??

? ? }??

??

? ? /**?

? ? ?* Convenient constructor to take a single model object.?

? ? ?* @param view View object to render?

? ? ?* @param modelName name of the single entry in the model?

? ? ?* @param modelObject the single model object?

? ? ?*/??

? ? public ModelAndView(View view, String modelName, Object modelObject) {??

? ? ? ? this.view = view;??

? ? ? ? addObject(modelName, modelObject);??

? ? }??

??

??

? ? /**?

? ? ?* Set a view name for this ModelAndView, to be resolved by the?

? ? ?* DispatcherServlet via a ViewResolver. Will override any?

? ? ?* pre-existing view name or View.?

? ? ?*/??

? ? public void setViewName(String viewName) {??

? ? ? ? this.view = viewName;??

? ? }??

??

? ? /**?

? ? ?* Return the view name to be resolved by the DispatcherServlet?

? ? ?* via a ViewResolver, or <code>null</code> if we are using a View object.?

? ? ?*/??

? ? public String getViewName() {??

? ? ? ? return (this.view instanceof String ? (String) this.view : null);??

? ? }??

??

? ? /**?

? ? ?* Set a View object for this ModelAndView. Will override any?

? ? ?* pre-existing view name or View.?

? ? ?*/??

? ? public void setView(View view) {??

? ? ? ? this.view = view;??

? ? }??

??

? ? /**?

? ? ?* Return the View object, or <code>null</code> if we are using a view name?

? ? ?* to be resolved by the DispatcherServlet via a ViewResolver.?

? ? ?*/??

? ? public View getView() {??

? ? ? ? return (this.view instanceof View ? (View) this.view : null);??

? ? }??

??

? ? /**?

? ? ?* Indicate whether or not this <code>ModelAndView</code> has a view, either?

? ? ?* as a view name or as a direct {@link View} instance.?

? ? ?*/??

? ? public boolean hasView() {??

? ? ? ? return (this.view != null);??

? ? }??

??

? ? /**?

? ? ?* Return whether we use a view reference, i.e. <code>true</code>?

? ? ?* if the view has been specified via a name to be resolved by the?

? ? ?* DispatcherServlet via a ViewResolver.?

? ? ?*/??

? ? public boolean isReference() {??

? ? ? ? return (this.view instanceof String);??

? ? }??

??

? ? /**?

? ? ?* Return the model map. May return <code>null</code>.?

? ? ?* Called by DispatcherServlet for evaluation of the model.?

? ? ?*/??

? ? protected Map<String, Object> getModelInternal() {??

? ? ? ? return this.model;??

? ? }??

??

? ? /**?

? ? ?* Return the underlying <code>ModelMap</code> instance (never <code>null</code>).?

? ? ?*/??

? ? public ModelMap getModelMap() {??

? ? ? ? if (this.model == null) {??

? ? ? ? ? ? this.model = new ModelMap();??

? ? ? ? }??

? ? ? ? return this.model;??

? ? }??

??

? ? /**?

? ? ?* Return the model map. Never returns <code>null</code>.?

? ? ?* To be called by application code for modifying the model.?

? ? ?*/??

? ? public Map<String, Object> getModel() {??

? ? ? ? return getModelMap();??

? ? }??

??

??

? ? /**?

? ? ?* Add an attribute to the model.?

? ? ?* @param attributeName name of the object to add to the model?

? ? ?* @param attributeValue object to add to the model (never <code>null</code>)?

? ? ?* @see ModelMap#addAttribute(String, Object)?

? ? ?* @see #getModelMap()?

? ? ?*/??

? ? public ModelAndView addObject(String attributeName, Object attributeValue) {??

? ? ? ? getModelMap().addAttribute(attributeName, attributeValue);??

? ? ? ? return this;??

? ? }??

??

? ? /**?

? ? ?* Add an attribute to the model using parameter name generation.?

? ? ?* @param attributeValue the object to add to the model (never <code>null</code>)?

? ? ?* @see ModelMap#addAttribute(Object)?

? ? ?* @see #getModelMap()?

? ? ?*/??

? ? public ModelAndView addObject(Object attributeValue) {??

? ? ? ? getModelMap().addAttribute(attributeValue);??

? ? ? ? return this;??

? ? }??

??

? ? /**?

? ? ?* Add all attributes contained in the provided Map to the model.?

? ? ?* @param modelMap a Map of attributeName -> attributeValue pairs?

? ? ?* @see ModelMap#addAllAttributes(Map)?

? ? ?* @see #getModelMap()?

? ? ?*/??

? ? public ModelAndView addAllObjects(Map<String, ?> modelMap) {??

? ? ? ? getModelMap().addAllAttributes(modelMap);??

? ? ? ? return this;??

? ? }??

??

??

? ? /**?

? ? ?* Clear the state of this ModelAndView object.?

? ? ?* The object will be empty afterwards.?

? ? ?* <p>Can be used to suppress rendering of a given ModelAndView object?

? ? ?* in the <code>postHandle</code> method of a HandlerInterceptor.?

? ? ?* @see #isEmpty()?

? ? ?* @see HandlerInterceptor#postHandle?

? ? ?*/??

? ? public void clear() {??

? ? ? ? this.view = null;??

? ? ? ? this.model = null;??

? ? ? ? this.cleared = true;??

? ? }??

??

? ? /**?

? ? ?* Return whether this ModelAndView object is empty,?

? ? ?* i.e. whether it does not hold any view and does not contain a model.?

? ? ?*/??

? ? public boolean isEmpty() {??

? ? ? ? return (this.view == null && CollectionUtils.isEmpty(this.model));??

? ? }??

??

? ? /**?

? ? ?* Return whether this ModelAndView object is empty as a result of a call to {@link #clear}?

? ? ?* i.e. whether it does not hold any view and does not contain a model.?

? ? ?* <p>Returns <code>false</code> if any additional state was added to the instance?

? ? ?* <strong>after</strong> the call to {@link #clear}.?

? ? ?* @see #clear()?

? ? ?*/??

? ? public boolean wasCleared() {??

? ? ? ? return (this.cleared && isEmpty());??

? ? }??

??

??

? ? /**?

? ? ?* Return diagnostic information about this model and view.?

? ? ?*/??

? ? @Override??

? ? public String toString() {??

? ? ? ? StringBuilder sb = new StringBuilder("ModelAndView: ");??

? ? ? ? if (isReference()) {??

? ? ? ? ? ? sb.append("reference to view with name '").append(this.view).append("'");??

? ? ? ? }??

? ? ? ? else {??

? ? ? ? ? ? sb.append("materialized View is [").append(this.view).append(']');??

? ? ? ? }??

? ? ? ? sb.append("; model is ").append(this.model);??

? ? ? ? return sb.toString();??

? ? }??

}??


?


[java] view plaincopy

測(cè)試代碼如下:??

package com.sxt.web;??

??

import org.springframework.stereotype.Controller;??

import org.springframework.web.bind.annotation.RequestMapping;??

import org.springframework.web.servlet.ModelAndView;??

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;??

??

import com.sxt.po.User;??

??

@Controller??

@RequestMapping("/user.do")??

public class UserController extends MultiActionController? {??

? ? ??

? ? @RequestMapping(params="method=reg")??

? ? public ModelAndView reg(String uname){??

? ? ? ? ModelAndView mv = new ModelAndView();??

? ? ? ? mv.setViewName("index");??

//? ? ? mv.setView(new RedirectView("index"));??

? ? ? ? ??

? ? ? ? User u = new User();??

? ? ? ? u.setUname("高淇");??

? ? ? ? mv.addObject(u);? ?//查看源代碼,得知,直接放入對(duì)象。屬性名為”首字母小寫(xiě)的類名”。 一般建議手動(dòng)增加屬性名稱。??

? ? ? ? mv.addObject("a", "aaaa");??

? ? ? ? return mv;??

? ? }??

??

}??

<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>??

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">??

<html>??

? <head>??

? </head>??

? <body>??

? ? ? ?<h2>${requestScope.a}</h2>??

? ? ? ?<h2>${requestScope.user.uname}</h2>??

? </body>??

</html>??

地址欄輸入:http://localhost:8080/springmvc03/user.do?method=reg??

? ? ?


-----------

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI