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

核心原理

1.       用户发送请求给服务器。urluser.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

springaop面向切面编程

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一样,SpringControllerSingleton的。这就意味着会被多个请求线程共享。因此,我们将控制器设计成无状态类。

 

spring 3.0中,通过@controller标注即可将class定义为一个controller类。为使spring能找到定义为controllerbean,需要在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中属性名字为ua的再放入session中。这样,requestsession中都有了。

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.       也可以返回ModelMapModelAndViewmapListSetObject、无返回值。一般建议返回字符串!

 

请求转发和重定向

         代码示例:

        

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表达式、JSTLJava代码均可。代码如下:

        

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


 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值