SpringMVC中@RequestMapping详解

一、@RequestMapping属性

@RequestMapping中有六个属性分别是:

value:     指定请求的实际地址,指定的地址可以是URI Template 模式;
method:  指定请求的method类型, GET、POST、PUT、DELETE等;
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;
params: 指定request中必须包含某些参数值是,才让该方法处理。
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

二、value、method的使用

1)在类上使用

表示此类拦截的根路径为/appointments同时不带任何属性的时候其值就是value的值

  
  
  1. @Controller
  2. @RequestMapping("/appointments")
  3. publicclassAppointmentsController{
  4. privateAppointmentBook appointmentBook;
  5. @Autowired
  6. publicAppointmentsController(AppointmentBook appointmentBook){
  7. this.appointmentBook = appointmentBook;
  8. }
  9. @RequestMapping(method =RequestMethod.GET)
  10. publicMap<String,Appointment> get(){
  11. return appointmentBook.getAppointmentsForToday();
  12. }
  13. @RequestMapping(value="/{day}", method =RequestMethod.GET)
  14. publicMap<String,Appointment> getForDay(@PathVariable@DateTimeFormat(iso=ISO.DATE)Date day,Model model){
  15. return appointmentBook.getAppointmentsForDay(day);
  16. }
  17. @RequestMapping(value="/new", method =RequestMethod.GET)
  18. publicAppointmentForm getNewForm(){
  19. returnnewAppointmentForm();
  20. }
  21. @RequestMapping(method =RequestMethod.POST)
  22. publicString add(@ValidAppointmentForm appointment,BindingResult result){
  23. if(result.hasErrors()){
  24. return"appointments/new";
  25. }
  26. appointmentBook.addAppointment(appointment);
  27. return"redirect:/appointments";
  28. }
  29. }

2)在方法上使用 只有value值

   
   
  1. @RequestMapping(value="/departments")
  2. publicString simplePattern(){
  3. System.out.println("simplePattern method was called");
  4. return"someResult";
  5. }
则访问http://localhost/xxxx/departments的时候,会调用 simplePattern方法了  

3)参数绑定-不用@RequestParam

   
   
  1. //商品信息修改提交
  2. @RequestMapping("/editItemsSubmit")
  3. publicString editItemsSubmit(HttpServletRequest request,Integer id,ItemsCustom itemsCustom)throwsException{
  4. //调用service更新商品信息,页面需要将商品信息传到此方法
  5. itemsService.updateItems(id, itemsCustom);
  6. //重定向到商品查询列表
  7. // return "redirect:queryItems.action";
  8. //页面转发
  9. //return "forward:queryItems.action";
  10. return"success";
  11. }

如果不使用@RequestParam,要求request传入参数名称和controller方法的形参名称一致,方可绑定成功。

形如这样的访问形式:  
   /departments?departmentId=23就可以触发访问findDepatment方法了  

4)参数绑定-使用@RequestParam

   
   
  1. @RequestMapping(value="/editItems",method={RequestMethod.POST,RequestMethod.GET})
  2. //@RequestParam里边指定request传入参数名称和形参进行绑定。
  3. //通过required属性指定参数是否必须要传入
  4. //通过defaultValue可以设置默认值,如果id参数没有传入,将默认值和形参绑定。
  5. publicString editItems(Model model,@RequestParam(value="id",required=true)Integer items_id)throwsException{
  6. //调用service根据商品id查询商品信息
  7. ItemsCustom itemsCustom = itemsService.findItemsById(items_id);
  8. //通过形参中的model将model数据传到页面
  9. //相当于modelAndView.addObject方法
  10. model.addAttribute("itemsCustom", itemsCustom);
  11. return"items/editItems";
  12. }

5)REST风格的参数

   
   
  1. @RequestMapping(value="/departments/{departmentId}")
  2. publicString findDepatment(@PathVariableString departmentId){
  3. System.out.println("Find department with ID: "+ departmentId);
  4. return"someResult";
  5. }
形如REST风格的地址访问,比如:  /departments/23,其中用(@PathVariable接收rest风格的参数  

6)REST风格的参数绑定形式之2

   
   
  1. @RequestMapping(value="/departments/{departmentId}")
  2. publicString findDepatmentAlternative(
  3. @PathVariable("departmentId")String someDepartmentId){
  4. System.out.println("Find department with ID: "+ someDepartmentId);
  5. return"someResult";
  6. }
这个有点不同,就是接收形如/departments/23的URL访问,把23作为传入的departmetnId,,但是在实际的方法findDepatmentAlternative中,使用  
@PathVariable("departmentId") String someDepartmentId,将其绑定为  someDepartmentId,所以这里someDepartmentId为23  

7)url中同时绑定多个参数 

   
   
  1. @RequestMapping(value="/departments/{departmentId}/employees/{employeeId}")
  2. publicString findEmployee(
  3. @PathVariableString departmentId,
  4. @PathVariableString employeeId){
  5. System.out.println("Find employee with ID: "+ employeeId +
  6. " from department: "+ departmentId);
  7. return"someResult";
  8. }

8)支持正则表达式

   
   
  1. @RequestMapping(value="/{textualPart:[a-z-]+}.{numericPart:[\\d]+}")
  2. publicString regularExpression(
  3. @PathVariableString textualPart,
  4. @PathVariableString numericPart){
  5. System.out.println("Textual part: "+ textualPart +
  6. ", numeric part: "+ numericPart);
  7. return"someResult";
  8. }
比如如下的URL:/sometext.123,则输出:  
Textual part: sometext, numeric part: 123. 

三、consumes、produces 示例

cousumes的样例:
   
   
  1. @Controller
  2. @RequestMapping(value ="/pets", method =RequestMethod.POST, consumes="application/json")
  3. publicvoid addPet(@RequestBodyPet pet,Model model){
  4. // implementation omitted
  5. }

方法仅处理request Content-Type为“application/json”类型的请求。

produces的样例:

    
    
  1. @Controller
  2. @RequestMapping(value ="/pets/{petId}", method =RequestMethod.GET, produces="application/json")
  3. @ResponseBody
  4. publicPet getPet(@PathVariableString petId,Model model){
  5. // implementation omitted
  6. }
方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;

四、params、headers 示例

params的样例:
   
   
  1. @Controller
  2. @RequestMapping("/owners/{ownerId}")
  3. publicclassRelativePathUriTemplateController{
  4. @RequestMapping(value ="/pets/{petId}", method =RequestMethod.GET, params="myParam=myValue")
  5. publicvoid findPet(@PathVariableString ownerId,@PathVariableString petId,Model model){
  6. // implementation omitted
  7. }
  8. }
仅处理请求中包含了名为“myParam”,值为“myValue”的请求;
headers的样例:
   
   
  1. @Controller
  2. @RequestMapping("/owners/{ownerId}")
  3. publicclassRelativePathUriTemplateController{
  4. @RequestMapping(value ="/pets", method =RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
  5. publicvoid findPet(@PathVariableString ownerId,@PathVariableString petId,Model model){
  6. // implementation omitted
  7. }
  8. }
仅处理request的header中包含了指定“Refer”请求头和对应值为“ http://www.ifeng.com/”的请求;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值