Spring MVC 3.0 深入及对注解的详细讲解

核心原理

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>

<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>


将属性u的值赋给形参uname

ModelAndView模型视图类

见名知意,从名字上我们可以知道ModelAndView中的Model代表模型,View代表视图。即,这个类把要显示的数据存储到了Model属性中,要跳转的视图信息存储到了view属性。我们看一下ModelAndView的部分源码,即可知其中关系:

[java] view plaincopy

  1. public class ModelAndView {
  2. /** View instance or view name String */
  3. private Object view;
  4. /** Model Map */
  5. private ModelMap model;
  6. /**
  7. * Indicates whether or not this instance has been cleared with a call to {@link #clear()}.
  8. */
  9. private boolean cleared = false;
  10. /**
  11. * Default constructor for bean-style usage: populating bean
  12. * properties instead of passing in constructor arguments.
  13. * @see #setView(View)
  14. * @see #setViewName(String)
  15. */
  16. public ModelAndView() {
  17. }
  18. /**
  19. * Convenient constructor when there is no model data to expose.
  20. * Can also be used in conjunction with <code>addObject</code>.
  21. * @param viewName name of the View to render, to be resolved
  22. * by the DispatcherServlet‘s ViewResolver
  23. * @see #addObject
  24. */
  25. public ModelAndView(String viewName) {
  26. this.view = viewName;
  27. }
  28. /**
  29. * Convenient constructor when there is no model data to expose.
  30. * Can also be used in conjunction with <code>addObject</code>.
  31. * @param view View object to render
  32. * @see #addObject
  33. */
  34. public ModelAndView(View view) {
  35. this.view = view;
  36. }
  37. /**
  38. * Creates new ModelAndView given a view name and a model.
  39. * @param viewName name of the View to render, to be resolved
  40. * by the DispatcherServlet‘s ViewResolver
  41. * @param model Map of model names (Strings) to model objects
  42. * (Objects). Model entries may not be <code>null</code>, but the
  43. * model Map may be <code>null</code> if there is no model data.
  44. */
  45. public ModelAndView(String viewName, Map<String, ?> model) {
  46. this.view = viewName;
  47. if (model != null) {
  48. getModelMap().addAllAttributes(model);
  49. }
  50. }
  51. /**
  52. * Creates new ModelAndView given a View object and a model.
  53. * <emphasis>Note: the supplied model data is copied into the internal
  54. * storage of this class. You should not consider to modify the supplied
  55. * Map after supplying it to this class</emphasis>
  56. * @param view View object to render
  57. * @param model Map of model names (Strings) to model objects
  58. * (Objects). Model entries may not be <code>null</code>, but the
  59. * model Map may be <code>null</code> if there is no model data.
  60. */
  61. public ModelAndView(View view, Map<String, ?> model) {
  62. this.view = view;
  63. if (model != null) {
  64. getModelMap().addAllAttributes(model);
  65. }
  66. }
  67. /**
  68. * Convenient constructor to take a single model object.
  69. * @param viewName name of the View to render, to be resolved
  70. * by the DispatcherServlet‘s ViewResolver
  71. * @param modelName name of the single entry in the model
  72. * @param modelObject the single model object
  73. */
  74. public ModelAndView(String viewName, String modelName, Object modelObject) {
  75. this.view = viewName;
  76. addObject(modelName, modelObject);
  77. }
  78. /**
  79. * Convenient constructor to take a single model object.
  80. * @param view View object to render
  81. * @param modelName name of the single entry in the model
  82. * @param modelObject the single model object
  83. */
  84. public ModelAndView(View view, String modelName, Object modelObject) {
  85. this.view = view;
  86. addObject(modelName, modelObject);
  87. }
  88. /**
  89. * Set a view name for this ModelAndView, to be resolved by the
  90. * DispatcherServlet via a ViewResolver. Will override any
  91. * pre-existing view name or View.
  92. */
  93. public void setViewName(String viewName) {
  94. this.view = viewName;
  95. }
  96. /**
  97. * Return the view name to be resolved by the DispatcherServlet
  98. * via a ViewResolver, or <code>null</code> if we are using a View object.
  99. */
  100. public String getViewName() {
  101. return (this.view instanceof String ? (String) this.view : null);
  102. }
  103. /**
  104. * Set a View object for this ModelAndView. Will override any
  105. * pre-existing view name or View.
  106. */
  107. public void setView(View view) {
  108. this.view = view;
  109. }
  110. /**
  111. * Return the View object, or <code>null</code> if we are using a view name
  112. * to be resolved by the DispatcherServlet via a ViewResolver.
  113. */
  114. public View getView() {
  115. return (this.view instanceof View ? (View) this.view : null);
  116. }
  117. /**
  118. * Indicate whether or not this <code>ModelAndView</code> has a view, either
  119. * as a view name or as a direct {@link View} instance.
  120. */
  121. public boolean hasView() {
  122. return (this.view != null);
  123. }
  124. /**
  125. * Return whether we use a view reference, i.e. <code>true</code>
  126. * if the view has been specified via a name to be resolved by the
  127. * DispatcherServlet via a ViewResolver.
  128. */
  129. public boolean isReference() {
  130. return (this.view instanceof String);
  131. }
  132. /**
  133. * Return the model map. May return <code>null</code>.
  134. * Called by DispatcherServlet for evaluation of the model.
  135. */
  136. protected Map<String, Object> getModelInternal() {
  137. return this.model;
  138. }
  139. /**
  140. * Return the underlying <code>ModelMap</code> instance (never <code>null</code>).
  141. */
  142. public ModelMap getModelMap() {
  143. if (this.model == null) {
  144. this.model = new ModelMap();
  145. }
  146. return this.model;
  147. }
  148. /**
  149. * Return the model map. Never returns <code>null</code>.
  150. * To be called by application code for modifying the model.
  151. */
  152. public Map<String, Object> getModel() {
  153. return getModelMap();
  154. }
  155. /**
  156. * Add an attribute to the model.
  157. * @param attributeName name of the object to add to the model
  158. * @param attributeValue object to add to the model (never <code>null</code>)
  159. * @see ModelMap#addAttribute(String, Object)
  160. * @see #getModelMap()
  161. */
  162. public ModelAndView addObject(String attributeName, Object attributeValue) {
  163. getModelMap().addAttribute(attributeName, attributeValue);
  164. return this;
  165. }
  166. /**
  167. * Add an attribute to the model using parameter name generation.
  168. * @param attributeValue the object to add to the model (never <code>null</code>)
  169. * @see ModelMap#addAttribute(Object)
  170. * @see #getModelMap()
  171. */
  172. public ModelAndView addObject(Object attributeValue) {
  173. getModelMap().addAttribute(attributeValue);
  174. return this;
  175. }
  176. /**
  177. * Add all attributes contained in the provided Map to the model.
  178. * @param modelMap a Map of attributeName -> attributeValue pairs
  179. * @see ModelMap#addAllAttributes(Map)
  180. * @see #getModelMap()
  181. */
  182. public ModelAndView addAllObjects(Map<String, ?> modelMap) {
  183. getModelMap().addAllAttributes(modelMap);
  184. return this;
  185. }
  186. /**
  187. * Clear the state of this ModelAndView object.
  188. * The object will be empty afterwards.
  189. * <p>Can be used to suppress rendering of a given ModelAndView object
  190. * in the <code>postHandle</code> method of a HandlerInterceptor.
  191. * @see #isEmpty()
  192. * @see HandlerInterceptor#postHandle
  193. */
  194. public void clear() {
  195. this.view = null;
  196. this.model = null;
  197. this.cleared = true;
  198. }
  199. /**
  200. * Return whether this ModelAndView object is empty,
  201. * i.e. whether it does not hold any view and does not contain a model.
  202. */
  203. public boolean isEmpty() {
  204. return (this.view == null && CollectionUtils.isEmpty(this.model));
  205. }
  206. /**
  207. * Return whether this ModelAndView object is empty as a result of a call to {@link #clear}
  208. * i.e. whether it does not hold any view and does not contain a model.
  209. * <p>Returns <code>false</code> if any additional state was added to the instance
  210. * <strong>after</strong> the call to {@link #clear}.
  211. * @see #clear()
  212. */
  213. public boolean wasCleared() {
  214. return (this.cleared && isEmpty());
  215. }
  216. /**
  217. * Return diagnostic information about this model and view.
  218. */
  219. @Override
  220. public String toString() {
  221. StringBuilder sb = new StringBuilder("ModelAndView: ");
  222. if (isReference()) {
  223. sb.append("reference to view with name ‘").append(this.view).append("‘");
  224. }
  225. else {
  226. sb.append("materialized View is [").append(this.view).append(‘]‘);
  227. }
  228. sb.append("; model is ").append(this.model);
  229. return sb.toString();
  230. }
  231. }

[java] view plaincopy

    1. 测试代码如下:
    2. package com.sxt.web;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. import org.springframework.web.servlet.ModelAndView;
    6. import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
    7. import com.sxt.po.User;
    8. @Controller
    9. @RequestMapping("/user.do")
    10. public class UserController extends MultiActionController  {
    11. @RequestMapping(params="method=reg")
    12. public ModelAndView reg(String uname){
    13. ModelAndView mv = new ModelAndView();
    14. mv.setViewName("index");
    15. //      mv.setView(new RedirectView("index"));
    16. User u = new User();
    17. u.setUname("高淇");
    18. mv.addObject(u);   //查看源代码,得知,直接放入对象。属性名为”首字母小写的类名”。 一般建议手动增加属性名称。
    19. mv.addObject("a", "aaaa");
    20. return mv;
    21. }
    22. }
    23. <%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
    24. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    25. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    26. <html>
    27. <head>
    28. </head>
    29. <body>
    30. <h1>${requestScope.a}</h1>
    31. <h1>${requestScope.user.uname}</h1>
    32. </body>
    33. </html>
    34. 地址栏输入:http://localhost:8080/springmvc03/user.do?method=reg
    35. 结果为:
时间: 2024-08-02 18:14:07

Spring MVC 3.0 深入及对注解的详细讲解的相关文章

Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(三)

前两章我为大家详细介绍了如何搭建Maven环境.Spring MVC的流程结构.Spring MVC与Struts2的区别以及示例中的一些配置文件的分析.在这一章,我就对示例的层次结构进行说明,以及MyBatis的一些简单介绍. 本文不会对MyBatis作详细说明,大象还是假定阅读本文的朋友对MyBatis(ibatis)有最基本的了解,只有这样才能较好的理解本文的内容.关于MyBatis请查看它的官方文档及其它参考资料,本文不作详细讨论. 一.工程结构图      上面这是典型的Maven项目

Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(一)

Spring更新到3.0之后,其MVC框架加入了一个非常不错的东西——那就是REST.它的开放式特性,与Spring的无缝集成,以及Spring框架的优秀表现,使得现在很多公司将其作为新的系统开发框架.大象根据实际的项目经验,以之前SSH2例子为基础,对其进行一次大改造,详细的为大家讲解如何实现SSM3全注解式的开发. 这次大象将采取两种构建方式,一是很多人喜欢用的MyEclipse,另一个,则是用Eclipse+Maven.这一篇,将主要讲解开发环境设置与Maven构建方式. 1. 开发环境

Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(二)

在上一篇文章中我详细的介绍了如何搭建maven环境以及生成一个maven骨架的web项目,那么这章中我将讲述Spring MVC的流程结构,Spring MVC与Struts2的区别,以及例子中的一些配置文件的分析. 一.Spring MVC 3.0介绍 Spring MVC是一个典型的MVC框架,是Spring内置的Web框架,可以作为应用项目的展示层,继Spring 2.0对Spring MVC进行重大升级后,Spring 2.5又为Spring MVC引入了注解驱动功能,再到3.0时代,全

Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(四)

这一章大象将详细分析web层代码,以及使用Spring MVC的注解及其用法和其它相关知识来实现控制器功能.     之前在使用Struts2实现MVC的注解时,是借助struts2-convention这个插件,如今我们使用Spring自带的spring-webmvc组件来实现同样的功能,而且比之以前更简单.另外,还省掉了整合两个框架带来的不稳定因素.     对于Spring MVC框架,我主要讲一下它的常用注解,再结合一些示例进行说明,方便大家能够快速理解.     一.Spring MV

Spring MVC 3.0.5+Spring 3.0.5+MyBatis3.0.4全注解实例详解(五)

这是本系列的最后一篇,主要讲一下FreeMarker模板引擎的基本概念与常用指令的使用方式.     一.FreemMarker基本概念     FreemMarker是一个用Java语言编写的模板引擎,它是一个基于模板来生成文本输出的一个工具.是除了JSP之外被使用得最多的页面模板技术之一,另一个比较有名的模板则是Velocity.     用户可以使用FreeMarker来生成所需要的内容,通常由Java提供数据模型,FreeMarker通过模板引擎渲染数据模型,这样最终得到我们想要的内容.

CRUD using Spring MVC 4.0 RESTful Web Services and AngularJS

原文: http://www.tuicool.com/articles/MneeU3f Based on the requests from many readers, I am now presenting an article on how to make CRUD operations using Spring MVC 4.0 RESTFul web services and AngularJS. I had already written few articles on Spring M

Spring MVC 3.0简介

1.    背景介绍 Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块.使用 Spring 可插入的 MVC 架构,可以选择是使用内置的 Spring Web 框架还是 Struts 这样的 Web 框架.通过策略接口,Spring 框架是高度可配置的,而且包含多种视图技术,例如 JavaServer Pages(JSP)技术.Velocity.Tiles.iText 和 POI.Spring MVC 框架并不知道使用的视图,所以不会强迫您只使用 JSP 技术.Spring

Spring + Spring MVC + Hibernate项目开发集成(注解)

在自己从事的项目中都是使用xml配置的方式来进行的,随着项目的越来越大,会发现配置文件会相当的庞大,这个不利于项目的进行和后期的维护.于是考虑使用注解的方式来进行项目的开发,前些日子就抽空学习了一下.在网上也查询了很多使用注解来搭建开发框架的文章,但是有一个问题就是,使用更新的软件版本会出错.这里我将使用最新的Spring,Hibernate来进行框架的搭建,经过测试,顺利运行.分享旨在与大家一起分享学习,共同进步,有不足之处,望不吝赐教,谢谢! 本项目使用maven构建,采用Spring +

解决 spring mvc 3.0 结合 hibernate3.2 使用&lt;tx:annotation-driven&gt;声明式事务无法提交的问题(转载)

1.问题复现 spring 3.0 + hibernate 3.2 spring mvc使用注解方式:service使用@service注解 事务使用@Transactional 事务配置使用 Java代码   <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" /> [java] view plaincopy <tx:an