您好,登錄后才能下訂單哦!
核心原理
1.? ? ? ?用戶發送請求給服務器。url:user.do
2.? ? ? ?服務器收到請求。發現Dispatchservlet可以處理。于是調用DispatchServlet。
3.? ? ? DispatchServlet內部,通過HandleMapping檢查這個url有沒有對應的Controller。如果有,則調用Controller。
4、? ? Control開始執行
5.? ? ? Controller執行完畢后,如果返回字符串,則ViewResolver將字符串轉化成相應的視圖對象;如果返回ModelAndView對象,該對象本身就包含了視圖對象信息。
6.? ? ? DispatchServlet將執視圖對象中的數據,輸出給服務器。
7.? ? ? 服務器將數據輸出給客戶端。
spring3.0中相關jar包的含義
org.springframework.aop-3.0.3.RELEASE.jar
spring的aop面向切面編程
org.springframework.asm-3.0.3.RELEASE.jar
spring獨立的asm字節碼生成程序
org.springframework.beans-3.0.3.RELEASE.jar
IOC的基礎實現
org.springframework.context-3.0.3.RELEASE.jar
IOC基礎上的擴展服務
org.springframework.core-3.0.3.RELEASE.jar
spring的核心包
org.springframework.expression-3.0.3.RELEASE.jar
spring的表達式語言
org.springframework.web-3.0.3.RELEASE.jar
web工具包
org.springframework.web.servlet-3.0.3.RELEASE.jar
mvc工具包
?
@Controller控制器定義
和Struts1一樣,Spring的Controller是Singleton的。這就意味著會被多個請求線程共享。因此,我們將控制器設計成無狀態類。
?
在spring 3.0中,通過@controller標注即可將class定義為一個controller類。為使spring能找到定義為controller的bean,需要在spring-context配置文件中增加如下定義:
?
<context:component-scan base-package="com.sxt.web"/>
?
? ? ? ? 注:實際上,使用@component,也可以起到@Controller同樣的作用。
@RequestMapping
?
? ? 在類前面定義,則將url和類綁定。
? ?在方法前面定義,則將url和類的方法綁定
@RequestParam
? ? ? ? ?一般用于將指定的請求參數付給方法中形參。示例代碼如下:
? ? ? ??
@RequestMapping(params="method=reg5")
? ? public String reg5(@RequestParam("name")String uname,ModelMap map) {
? ? ? ?System.out.println("HelloController.handleRequest()");
? ? ? ?System.out.println(uname);
? ? ? ?return"index";
? ? }
? ?這樣,就會將name參數的值付給uname。當然,如果請求參數名稱和形參名稱保持一致,則不需要這種寫法。
@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作用域中,這樣轉發頁面也可以取到這個數據。
? ? ? ?return"index";
? ? }
}
? <body>
? ?<h2>**********${requestScope.u.uname}</h2>
? ?<h2>**********${sessionScope.u.uname}</h2>
? </body>
? ?
? ? 注:名字為”user”的屬性再結合使用注解@SessionAttributes可能會報錯。
?
@ModelAttribute
? ? ?這個注解可以跟@SessionAttributes配合在一起用。可以將ModelMap中屬性的值通過該注解自動賦給指定變量。
? ? 示例代碼如下:
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","尚學堂高淇");
? ? ? ?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";
? ? }
? ?
}
?
先調用reg4方法,再調用reg5方法。?
Controller類中方法參數的處理
?
Controller類中方法返回值的處理
1.? ? ? ?返回string(建議)
a)? ? ? ? ?根據返回值找對應的顯示頁面。路徑規則為:prefix前綴+返回值+suffix后綴組成
b)? ? ? ? ?代碼如下:
@RequestMapping(params="method=reg4")
? ? public String reg4(ModelMap map) {
? ? ? ?System.out.println("HelloController.handleRequest()");
? ? ? ?return"index";
? ? }
前綴為:/WEB-INF/jsp/? ?后綴是:.jsp
在轉發到:/WEB-INF/jsp/index.jsp
?
2.? ? ? ?也可以返回ModelMap、ModelAndView、map、List、Set、Object、無返回值。一般建議返回字符串!
?
請求轉發和重定向
? ? ? ? ?代碼示例:
? ? ? ??
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"; //轉發
//? ? ?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";
? ? }
? ?
}
? ? ? ??
? ? ? ? ?訪問reg4方法,既可以看到效果。
??
獲得request對象、session對象
普通的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的實現,可以在其中存放屬性,作用域同request。下面這個示例,我們可以在modelMap中放入數據,然后在forward的頁面上顯示這些數據。通過el表達式、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的值賦給形參uname
ModelAndView模型視圖類
見名知意,從名字上我們可以知道ModelAndView中的Model代表模型,View代表視圖。即,這個類把要顯示的數據存儲到了Model屬性中,要跳轉的視圖信息存儲到了view屬性。我們看一下ModelAndView的部分源碼,即可知其中關系:
[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
測試代碼如下:??
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);? ?//查看源代碼,得知,直接放入對象。屬性名為”首字母小寫的類名”。 一般建議手動增加屬性名稱。??
? ? ? ? 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??
? ? ?
-----------
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。