简介:

@RequestMapping

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

RequestMapping注解有六个属性(分成三类进行说明)与六个基本用法,

一、属性

1、 value, method;

value:     指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);

method:  指定请求的method类型, GET、POST、PUT、DELETE等;

2、 consumes,produces;

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

3、 params,headers;

params: 指定request中必须包含某些参数值是,才让该方法处理。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

1、value  / method 示例

默认RequestMapping("....str...")即为value的值;

@Controller
@RequestMapping("/appointments")
public class AppointmentsController { private AppointmentBook appointmentBook; @Autowired
public AppointmentsController(AppointmentBook appointmentBook) {
this.appointmentBook = appointmentBook;
} @RequestMapping(method = RequestMethod.GET)
public Map<String, Appointment> get() {
return appointmentBook.getAppointmentsForToday();
} @RequestMapping(value="/{day}", method = RequestMethod.GET)
public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
return appointmentBook.getAppointmentsForDay(day);
} @RequestMapping(value="/new", method = RequestMethod.GET)
public AppointmentForm getNewForm() {
return new AppointmentForm();
} @RequestMapping(method = RequestMethod.POST)
public String add(@Valid AppointmentForm appointment, BindingResult result) {
if (result.hasErrors()) {
return "appointments/new";
}
appointmentBook.addAppointment(appointment);
return "redirect:/appointments";
}
}

value的uri值为以下三类:

A) 可以指定为普通的具体值;

B)  可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);

C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);

example B)

@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
Owner owner = ownerService.findOwner(ownerId);
model.addAttribute("owner", owner);
return "displayOwner";
}

example C)

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:\d\.\d\.\d}.{extension:\.[a-z]}")
public void handle(@PathVariable String version, @PathVariable String extension) {
// ...
}

2 consumes、produces 示例

cousumes的样例:

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
// implementation omitted
}

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

produces的样例:

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
// implementation omitted
}

方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;

3 params、headers 示例

params的样例:

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController { @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}

仅处理请求中包含了名为“myParam”,值为“myValue”的请求;

headers的样例:

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController { @RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}

仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;

二、用法

1)最基本的,方法级别上应用,例如:

@RequestMapping(value="/departments")
public String simplePattern(){ System.out.println("simplePattern method was called");
return "someResult"; }

则访问http://localhost/xxxx/departments的时候,会调用 simplePattern方法了 
2) 参数绑定

@RequestMapping(value="/departments")
public String findDepatment(
@RequestParam("departmentId") String departmentId){ System.out.println("Find department with ID: " + departmentId);
return "someResult"; }

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

@RequestMapping(value="/departments/{departmentId}")
public String findDepatment(@PathVariable String departmentId){ System.out.println("Find department with ID: " + departmentId);
return "someResult"; }

形如REST风格的地址访问,比如: 
/departments/23,其中用(@PathVariable接收rest风格的参数

4 REST风格的参数绑定形式之2 
   先看例子,这个有点象之前的:

@RequestMapping(value="/departments/{departmentId}")
public String findDepatmentAlternative(
@PathVariable("departmentId") String someDepartmentId){ System.out.println("Find department with ID: " + someDepartmentId);
return "someResult"; }

这个有点不同,就是接收形如/departments/23的URL访问,把23作为传入的departmetnId,,但是在实际的方法findDepatmentAlternative中,使用 
@PathVariable("departmentId") String someDepartmentId,将其绑定为 
someDepartmentId,所以这里someDepartmentId为23

5 url中同时绑定多个id

@RequestMapping(value="/departments/{departmentId}/employees/{employeeId}")
public String findEmployee(
@PathVariable String departmentId,
@PathVariable String employeeId){ System.out.println("Find employee with ID: " + employeeId +
" from department: " + departmentId);
return "someResult"; }

6 支持正则表达式

@RequestMapping(value="/{textualPart:[a-z-]+}.{numericPart:[\\d]+}")
public String regularExpression(
@PathVariable String textualPart,
@PathVariable String numericPart){ System.out.println("Textual part: " + textualPart +
", numeric part: " + numericPart);
return "someResult";
}

---恢复内容结束---

Springmvc中@RequestMapping 属性用法归纳的更多相关文章

  1. SpringMVC中 -- @RequestMapping的作用及用法

    一.@RequestMapping 简介 在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,相当于Servlet中在web.x ...

  2. springmvc中RequestMapping的解析

    在研究源码的时候,我们应该从最高层来看,所以我们先看这个接口的定义: package org.springframework.web.servlet; import javax.servlet.htt ...

  3. 在springmvc中 @RequestMapping(value={"", "/"})是什么意思

    这个意思是说请求路径 可以为空或者/ 我给你举个例子:比如百度知道的个人中心 访问路径是 http://zhidao.baidu.com/ihome,当然你也可以通过 http://zhidao.ba ...

  4. SpringMVC中的session用法及细节记录

    前言 初学SpringMVC,最近在给公司做的系统做登录方面,需要用到session. 在网上找了不少资料,大致提了2点session保存方式: 1.javaWeb工程通用的HttpSession 2 ...

  5. springmvc 中RequestMapping注解的使用

    1.RequestMapping注解既可以修饰方法,又可以修饰类型,类型指定的url相对于web跟路径,而方法修饰的url相对于类url: 2.RequestMapping的几个属性: value:用 ...

  6. DIV CSS布局中position属性用法深入探究

    本文向大家描述一下DIV CSS布局中的position属性的用法,position属性主要有四种属性值,任何元素的默认position的属性值均是static,静态.这节课主要讲讲relative( ...

  7. SSM-SpringMVC-10:SpringMVC中PropertiesMethodNameResolver属性方法名称解析器

    ------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥------------- 上次的以继承MultiActionController可以实现一个处理器中多个处理方法,但是局限出来了,他们的 ...

  8. java中protect属性用法总结

    测试代码: pojo类: package com.lky.h1; public class Base { private Integer id; protected String name; publ ...

  9. Spring mvc中@RequestMapping 基本用法

    @RequestMapping(value="/departments") public String simplePattern(){ System.out.println(&q ...

随机推荐

  1. 在c#中利用keep-alive处理socket网络异常断开的方法

    本文摘自 http://www.z6688.com/info/57987-1.htm 最近我负责一个IM项目的开发,服务端和客户端采用TCP协议连接.服务端采用C#开发,客户端采用Delphi开发.在 ...

  2. 链表实现python list数据类型

    #1.<--用单链表的数据结构实现列表class error(Exception): def __init__(self,msg): super(error,self).__init__(sel ...

  3. JS stacktrace(Node内存溢出)

    vscode运行项目时,保存.vue文件,项目突然终止运行.输入命令npm run dev重新运行后,终端显示下面的错误. 解决方案: 如果是run dev时报错,在package.json文件里的s ...

  4. [Flutter] 写第一个 Flutter app,part1 要点

    模拟器中调试元素的布局: Android Studio 右侧边栏 Flutter Inspector,选择 Toggle Debug Paint 打开. 格式化代码: 编辑器中右键 Reformat ...

  5. week07 codelab02 C72

    ss 我们要改一下backendserver的service 因为要写几个api还要做很多操作 我们单独写出来 然后由service来调用 import json import os import p ...

  6. Failed to introspect annotated methods on class 异常

    用@enable时出现错误 Failed to introspect annotated methods on class 很可能是库和springboot版本不一致

  7. form表单的三个属性 action 、mothod 、 enctype。

    form_action: 表单数据提交到此页面 下面的表单拥有两个输入字段以及一个提交按钮,当提交表单时,表单数据会提交到名为 "form_action.asp" 的页面: < ...

  8. Java框架spring学习笔记(十七):事务操作

    事务操作创建service和dao类,完成注入关系 service层叫业务逻辑层 dao层单纯对数据库操作层,在dao层不添加业务 假设现在有一个转账的需求,狗蛋有10000元,建国有20000元,狗 ...

  9. Python设计模式 - UML - 组合结构图(Composite Structure Diagram)

    简介 组合结构图用来显示组合结构或部分系统的内部构造,包括类.接口.包.组件.端口和连接器等元素,是UML2.0的新增图. 组合结构图侧重复合元素的方式展示系统内部结构,包括与其他系统的交互接口和通信 ...

  10. mysql concat筛选查询重复数据

    SELECT * from (SELECT *,concat(field0,field1)as c from tableName) tt GROUP BY c HAVING count(c) > ...