码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC使用@PathVariable,@RequestBody,@ResponseBody,@RequestParam

时间:2016-08-03 22:00:21      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:

  • @Pathvariable
public ResponseEntity<String> ordersBack(  
        @PathVariable String reqKey,  
        @RequestParam(value="intVal") Integer intVal,  
        @RequestParam(value="strVal") String strVal) throws Exception{  
    return new ResponseEntity("ok", HttpStatus.OK);  
} 
  当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。这样就可以实现类似restful风格的请求。
  • @RequestParam
  A) 常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;
  B)用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;
  C) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定
@Controller 
@RequestMapping("/pets") 
@SessionAttributes("pet") 
publicclass EditPetForm { 
    @RequestMapping(method = RequestMethod.GET) 
    public String setupForm(@RequestParam("petId") int petId, ModelMap model) { 
        Pet pet = this.clinic.loadPet(petId); 
        model.addAttribute("pet", pet); 
        return"petForm"; 
    } 
}
  其作用实际就是将url中?后面部分请求参数作为参数的一部分。
  • @RequestBody
  @RequestBody 将HTTP请求正文转换为适合的HttpMessageConverter对象。
  • @ResponseBody
  @ResponseBody 将内容或对象作为 HTTP 响应正文返回,并调用适HttpMessageConverter的Adapter转换对象,写入输出流。

 

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

 

SpringMVC使用@PathVariable,@RequestBody,@ResponseBody,@RequestParam

标签:

原文地址:http://www.cnblogs.com/lcngu/p/5734307.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!