spring MVC理解和主要使用的注解详解


核心原理

1、       用户发送请求给服务器。url:user

2、       服务器收到请求。发现Dispatchservlet可以处理。于是调用DispatchServlet。

3、       DispatchServlet内部,通过HandleMapping检查这个url有没有对应的Controller。如果有,则调用Controller。

4、     Control开始执行

5、       Controller执行完毕后,如果返回字符串,则ViewResolver将字符串转化成相应的视图对象;如果返回ModelAndView对象,该对象本身就包含了视图对象信息。

6、       DispatchServlet将执视图对象中的数据,输出给服务器。

7、       服务器将数据输出给客户端

 

相关jar包含义:

1、   org.springframework.aop-3.0.3.RELEASE.jar         ----->  spring的aop面向切面编程

2、   org.springframework.asm-3.0.3.RELEASE.jar      ----->  spring独立的asm字节码生成程序

3、   org.springframework.beans-3.0.3.RELEASE.jar     ----->  IOC的基础实现

4、   org.springframework.context-3.0.3.RELEASE.jar      ----->  IOC基础上的扩展服务

5、   org.springframework.core-3.0.3.RELEASE.jar     ----->  spring的核心包

6、   org.springframework.expression-3.0.3.RELEASE.jar   ----->  spring的表达式语言

7、   org.springframework.web-3.0.3.RELEASE.jar     ----->  web工具包

8、   org.springframework.web.servlet-3.0.3.RELEASE.jar  ----->  mvc工具包

 

 

注解

1、@Controller

@Controller
public class UserController {
.......
.......

}

 

和Struts1一样,Spring的Controller是Singleton的。这就意味着会被多个请求线程共享。因此,我们将控制器设计成无状态类。

 

下为web.xml里面配置

 <!-- Spring MVC配置  -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mvc.xml</param-value>
  </context-param>

 

需要在spring-mvc.xml配置(包名为你controller所在的包)

    <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
    <context:component-scan base-package="controller" />

 

 

 

2、@RequestMapping

① 在类前面定义,则将url和类绑定;(如果该类里只有单个方法的话可以这样写,访问该地址直接调用该方法)

示例代码如下:

@Controller
@RequestMapping("/queryuser")
public class UserController {
......
......
}

 

 

② 在方法前面定义,则将url和类的方法绑定。

示例代码如下:

复制代码
@Controller
public class UserController {

    @RequestMapping("/queryuser")
    public Object queryUserList(HttpServletRequest request, HttpServletResponse response) {
.....
.....
    }
}
复制代码

 

 

 

3、@RequestParam

A) 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;

B)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;

  • GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。
  • POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。

C) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;

 

复制代码
/**
     * 删除代理商操作
     * **/
    @RequestMapping(value = "/del")
    @ResponseBody
    public MsgBean deleteAgents(@RequestParam("ids")String ids[]){
        MsgBean msg = null;
        try {
            msg = agentsService.delAgents(ids);
        } catch (Exception e) {
            logger.error("代理商删除操作出错..." + e.getMessage());
            throw new BusinessException(e.getMessage());
        }
        return msg;
    }
复制代码
复制代码
@Controller  
public class PersonController {  
  
    /** 
     * 查询个人信息 
     *  
     * @param id 
     * @return 
     */  
    @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)  
    public @ResponseBody  
    Person porfile(@PathVariable int id, @PathVariable String name,  
            @PathVariable boolean status) {  
        return new Person(id, name, status);  
    }  
  
    /** 
     * 登录 
     *  
     * @param person 
     * @return 
     */  
    @RequestMapping(value = "/person/login", method = RequestMethod.POST)  
    public @ResponseBody  
    Person login(@RequestBody Person person) {  
        return person;  
    }  
}  
复制代码

备注:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的{id}/{name}/{status}@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一对应,按名匹配。这是restful式风格。 

如果映射名称有所不一,可以参考如下方式:

@RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)  
public @ResponseBody  
Person porfile(@PathVariable("id") int uid) {  
    return new Person(uid, name, status);  
}  

 

 

 

4、@ResponseBody

作用: 

      该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:

      返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

 代码如上

 

 

5、@RequestBody

作用: 

      i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;

      ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

使用时机:

A) GET、POST方式提时, 根据request header Content-Type的值来判断:

  •     application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
  •     multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
  •     其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

B) PUT方式提交时, 根据request header Content-Type的值来判断:

  •     application/x-www-form-urlencoded, 必须;
  •     multipart/form-data, 不能处理;
  •     其他格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定;

 

 

6、@SessionAttributes

@SessionAttributes:

该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。

该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;

复制代码
@Controller
@RequestMapping("/user")
@SessionAttributes({"u","a"})   //将ModelMap中属性名字为u、a的再放入session中。这样,request和session中都有了。
publicclass UserController  {
    @RequestMapping(params="method=list")
    public String list(ModelMap map) {              
  System.out.println("HelloController.handleRequest()"); map.addAttribute("u","users"); //将u放入request作用域中,这样转发页面也可以取到这个数据。 return"index"; } }
复制代码

 

index里面的代码

<body>
   <h1>${requestScope.u.uname}</h1>
   <h1>${sessionScope.u.uname}</h1>
  </body>

 

 

 

7、@ModelAttribute

该注解有两个用法,一个是用于方法上,一个是用于参数上;

用于方法上时:  通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;

用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:

A) @SessionAttributes 启用的attribute 对象上;

B) @ModelAttribute 用于方法上时指定的model对象;

C) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。

 

 用到方法上@ModelAttribute的示例代码: 

@ModelAttribute  
public Account addAccount(@RequestParam String number) {  
    return accountManager.findAccount(number);  
}  

这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account);

 

用在参数上的@ModelAttribute示例代码:

@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)  
public String processSubmit(@ModelAttribute Pet pet) {  
     
} 

首先查询 @SessionAttributes有无绑定的Pet对象,若没有则查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URI template中的值按对应的名称绑定到Pet对象的各属性上。

 

 

@ModelAttribute可以和@SessionAttributes配合在一块使用。可以通过ModelMap中属性的值通过该注解自动赋给指定变量。

 示例代码如下:

复制代码
@Controller
@RequestMapping("/user")
@SessionAttributes({"u","a"}) 
publicclass UserController  {
   
    @RequestMapping(params="method=list1")
    public String list1(ModelMap map) {
       System.out.println("HelloController.handleRequest()");
       map.addAttribute("u","光头强");
       return"index";
    }
   
    @RequestMapping(params="method=list2")
public String list2(@ModelAttribute("u")String username ,ModelMap map) {
       System.out.println("HelloController.handleRequest()");
       System.out.println(username );
       return"index";
    }
   
}
复制代码

上述先调用list1方法,再调用list2方法。

1、       用户发送请求给服务器。url:user

2、       服务器收到请求。发现Dispatchservlet可以处理。于是调用DispatchServlet。

3、       DispatchServlet内部,通过HandleMapping检查这个url有没有对应的Controller。如果有,则调用Controller。

4、     Control开始执行

5、       Controller执行完毕后,如果返回字符串,则ViewResolver将字符串转化成相应的视图对象;如果返回ModelAndView对象,该对象本身就包含了视图对象信息。

6、       DispatchServlet将执视图对象中的数据,输出给服务器。

7、       服务器将数据输出给客户端

 

相关jar包含义:

1、   org.springframework.aop-3.0.3.RELEASE.jar         ----->  spring的aop面向切面编程

2、   org.springframework.asm-3.0.3.RELEASE.jar      ----->  spring独立的asm字节码生成程序

3、   org.springframework.beans-3.0.3.RELEASE.jar     ----->  IOC的基础实现

4、   org.springframework.context-3.0.3.RELEASE.jar      ----->  IOC基础上的扩展服务

5、   org.springframework.core-3.0.3.RELEASE.jar     ----->  spring的核心包

6、   org.springframework.expression-3.0.3.RELEASE.jar   ----->  spring的表达式语言

7、   org.springframework.web-3.0.3.RELEASE.jar     ----->  web工具包

8、   org.springframework.web.servlet-3.0.3.RELEASE.jar  ----->  mvc工具包

 

 

注解

1、@Controller

@Controller
public class UserController {
.......
.......

}

 

和Struts1一样,Spring的Controller是Singleton的。这就意味着会被多个请求线程共享。因此,我们将控制器设计成无状态类。

 

下为web.xml里面配置

 <!-- Spring MVC配置  -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mvc.xml</param-value>
  </context-param>

 

需要在spring-mvc.xml配置(包名为你controller所在的包)

    <!-- 扫描类包,将标注Spring注解的类自动转化Bean,同时完成Bean的注入 -->
    <context:component-scan base-package="controller" />

 

 

 

2、@RequestMapping

① 在类前面定义,则将url和类绑定;(如果该类里只有单个方法的话可以这样写,访问该地址直接调用该方法)

示例代码如下:

@Controller
@RequestMapping("/queryuser")
public class UserController {
......
......
}

 

 

② 在方法前面定义,则将url和类的方法绑定。

示例代码如下:

复制代码
@Controller
public class UserController {

    @RequestMapping("/queryuser")
    public Object queryUserList(HttpServletRequest request, HttpServletResponse response) {
.....
.....
    }
}
复制代码

 

 

 

3、@RequestParam

A) 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;

B)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;

  • GET模式下,这里使用了@PathVariable绑定输入参数,非常适合Restful风格。因为隐藏了参数与路径的关系,可以提升网站的安全性,静态化页面,降低恶意攻击风险。
  • POST模式下,使用@RequestBody绑定请求对象,Spring会帮你进行协议转换,将Json、Xml协议转换成你需要的对象。

C) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;

 

复制代码
/**
     * 删除代理商操作
     * **/
    @RequestMapping(value = "/del")
    @ResponseBody
    public MsgBean deleteAgents(@RequestParam("ids")String ids[]){
        MsgBean msg = null;
        try {
            msg = agentsService.delAgents(ids);
        } catch (Exception e) {
            logger.error("代理商删除操作出错..." + e.getMessage());
            throw new BusinessException(e.getMessage());
        }
        return msg;
    }
复制代码
复制代码
@Controller  
public class PersonController {  
  
    /** 
     * 查询个人信息 
     *  
     * @param id 
     * @return 
     */  
    @RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)  
    public @ResponseBody  
    Person porfile(@PathVariable int id, @PathVariable String name,  
            @PathVariable boolean status) {  
        return new Person(id, name, status);  
    }  
  
    /** 
     * 登录 
     *  
     * @param person 
     * @return 
     */  
    @RequestMapping(value = "/person/login", method = RequestMethod.POST)  
    public @ResponseBody  
    Person login(@RequestBody Person person) {  
        return person;  
    }  
}  
复制代码

备注:@RequestMapping(value = "/person/profile/{id}/{name}/{status}", method = RequestMethod.GET)中的{id}/{name}/{status}@PathVariable int id, @PathVariable String name,@PathVariable boolean status一一对应,按名匹配。这是restful式风格。 

如果映射名称有所不一,可以参考如下方式:

@RequestMapping(value = "/person/profile/{id}", method = RequestMethod.GET)  
public @ResponseBody  
Person porfile(@PathVariable("id") int uid) {  
    return new Person(uid, name, status);  
}  

 

 

 

4、@ResponseBody

作用: 

      该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。

使用时机:

      返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;

 代码如上

 

 

5、@RequestBody

作用: 

      i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;

      ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。

使用时机:

A) GET、POST方式提时, 根据request header Content-Type的值来判断:

  •     application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
  •     multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
  •     其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);

B) PUT方式提交时, 根据request header Content-Type的值来判断:

  •     application/x-www-form-urlencoded, 必须;
  •     multipart/form-data, 不能处理;
  •     其他格式, 必须;

说明:request的body部分的数据编码格式由header部分的Content-Type指定;

 

 

6、@SessionAttributes

@SessionAttributes:

该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。

该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;

复制代码
@Controller
@RequestMapping("/user")
@SessionAttributes({"u","a"})   //将ModelMap中属性名字为u、a的再放入session中。这样,request和session中都有了。
publicclass UserController  {
    @RequestMapping(params="method=list")
    public String list(ModelMap map) {              
  System.out.println("HelloController.handleRequest()"); map.addAttribute("u","users"); //将u放入request作用域中,这样转发页面也可以取到这个数据。 return"index"; } }
复制代码

 

index里面的代码

<body>
   <h1>${requestScope.u.uname}</h1>
   <h1>${sessionScope.u.uname}</h1>
  </body>

 

 

 

7、@ModelAttribute

该注解有两个用法,一个是用于方法上,一个是用于参数上;

用于方法上时:  通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;

用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:

A) @SessionAttributes 启用的attribute 对象上;

B) @ModelAttribute 用于方法上时指定的model对象;

C) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。

 

 用到方法上@ModelAttribute的示例代码: 

@ModelAttribute  
public Account addAccount(@RequestParam String number) {  
    return accountManager.findAccount(number);  
}  

这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account);

 

用在参数上的@ModelAttribute示例代码:

@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)  
public String processSubmit(@ModelAttribute Pet pet) {  
     
} 

首先查询 @SessionAttributes有无绑定的Pet对象,若没有则查询@ModelAttribute方法层面上是否绑定了Pet对象,若没有则将URI template中的值按对应的名称绑定到Pet对象的各属性上。

 

 

@ModelAttribute可以和@SessionAttributes配合在一块使用。可以通过ModelMap中属性的值通过该注解自动赋给指定变量。

 示例代码如下:

复制代码
@Controller
@RequestMapping("/user")
@SessionAttributes({"u","a"}) 
publicclass UserController  {
   
    @RequestMapping(params="method=list1")
    public String list1(ModelMap map) {
       System.out.println("HelloController.handleRequest()");
       map.addAttribute("u","光头强");
       return"index";
    }
   
    @RequestMapping(params="method=list2")
public String list2(@ModelAttribute("u")String username ,ModelMap map) {
       System.out.println("HelloController.handleRequest()");
       System.out.println(username );
       return"index";
    }
   
}
复制代码

上述先调用list1方法,再调用list2方法。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值