Spring MVC理解和主要使用的注解详解(2)

/** * 删除代理商操作 * **/ @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里面的代码

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/cd240bf160ad13a7ea84bb4d0998c0d4.html