简介:

@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. vue富文本编辑器

    基于webpack和vue 一.npm 安装 vue-quill-editor 二.在main.js中引入 import VueQuillEditor from 'vue-quill-editor'/ ...

  2. PLSQL安装教程,无需oracle客户端(解决本地需要安装oracle客户端的烦恼)

    最近用笔记本开发,项目用的是Oracle数据库,不想本地安装Oracle客户端. 就只装了一个PLSQL 连接数据库的时候各种错误,现在解决了记录一下. 详细内容见  附件

  3. lambda函数式编程

    一.接口注解(@FunctionalInterface) @FunctionalInterface interface Interface1 { public void print(); } publ ...

  4. VM下安装Windows 2008 R2服务器操作系统

    打开虚拟机,双击双击新的虚拟机. 2 硬件兼容性选择workstation10.点击下一步. 3 选择我以后安装操作系统.点击继续 4 选择Microsoft windows,版本为windows s ...

  5. node-服务器

    原生: const http=require('http'); http.createServer((request,response)=>{ response.writeHead(200,{& ...

  6. Java学习随笔(2)--爬虫--天气预报

    public class Spiderweather { public static void main(String[] args) { List<String> list = null ...

  7. 对抗生成网络-图像卷积-mnist数据生成(代码) 1.tf.layers.conv2d(卷积操作) 2.tf.layers.conv2d_transpose(反卷积操作) 3.tf.layers.batch_normalize(归一化操作) 4.tf.maximum(用于lrelu) 5.tf.train_variable(训练中所有参数) 6.np.random.uniform(生成正态数据

    1. tf.layers.conv2d(input, filter, kernel_size, stride, padding) # 进行卷积操作 参数说明:input输入数据, filter特征图的 ...

  8. linux下redis的安装方法

    一.Linux环境下安装Redis   Redis的官方下载网址是:http://redis.io/download  (这里下载的是Linux版的Redis源码包) Redis服务器端的默认端口是6 ...

  9. 如何解决 快速点击多次触发的bug 期望快速点击只一次生效

    var lastClick; lockClick(){ var nowClick = new Date(); if (lastClick === undefined) { lastClick = no ...

  10. 去除编辑器的HTML标签

    去除HTML携带的标签常用函数 string strip_tags(string str); 编辑器存放内容到数据库时p标签会转换成这种<p></p> 需要使用htmlspec ...