美文网首页
Spring MVC(二) 基于注解的控制器

Spring MVC(二) 基于注解的控制器

作者: TiredHu | 来源:发表于2018-08-03 16:58 被阅读34次

1、@Controller

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

}

和Struts1一样,Spring的Controller是Singleton的。这就意味着会被多个请求线程共享。因此,我们将控制器设计成无状态类。
2、@RequestMapping
① 在类前面定义,则将url和类绑定;(如果该类里只有单个方法的话可以这样写,访问该地址直接调用该方法)

示例代码如下:

@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;
   }

@PathVaribale

image.png

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方法。
转载至https://www.cnblogs.com/wzqkalil/p/5328100.html

相关文章

网友评论

      本文标题:Spring MVC(二) 基于注解的控制器

      本文链接:https://www.haomeiwen.com/subject/httuvftx.html