核心原理
1. 用戶發送請求給服務器。url:user.do html
2. 服務器收到請求。發現Dispatchservlet能夠處理。因而調用DispatchServlet。 java
3. DispatchServlet內部,經過HandleMapping檢查這個url有沒有對應的Controller。若是有,則調用Controller。 web
四、 Control開始執行 spring
5. Controller執行完畢後,若是返回字符串,則ViewResolver將字符串轉化成相應的視圖對象;若是返回ModelAndView對象,該對象自己就包含了視圖對象信息。 express
6. DispatchServlet將執視圖對象中的數據,輸出給服務器。 編程
7. 服務器將數據輸出給客戶端。 服務器
spring3.0中相關jar包的含義
org.springframework.aop-3.0.3.RELEASE.jar session |
spring的aop面向切面編程 mvc |
org.springframework.asm-3.0.3.RELEASE.jar app |
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工具包 |
和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> <h1>**********${requestScope.u.uname}</h1> <h1>**********${sessionScope.u.uname}</h1> </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 UserController extends 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" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head></head> <body> <h1>${requestScope.a}</h1> <c:out value="${requestScope.a}"></c:out> </body> </html> |
ModelAndView模型視圖類
見名知意,從名字上咱們能夠知道ModelAndView中的Model表明模型,View表明視圖。即,這個類把要顯示的數據存儲到了Model屬性中,要跳轉的視圖信息存儲到了view屬性。咱們看一下ModelAndView的部分源碼,便可知其中關係:
- 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();
- }
- }
- 測試代碼以下:
- 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>
- <h1>${requestScope.a}</h1>
- <h1>${requestScope.user.uname}</h1>
- </body>
- </html>
- 地址欄輸入:http://localhost:8080/springmvc03/user.do?method=reg
- 結果爲: