@RequestMapping 用法详解之地址映射

引言:

前段时间项目中用到了RESTful模式来开发程序,但是当用POST、PUT模式提交数据时,发现服务器端接受不到提交的数据(服务器端参数绑定 没有加任何注解),查看了提交方式为application/json, 而且服务器端通过request.getReader() 打出的数据里确实存在浏览器提交的数据。为了找出原因,便对参数绑定(@RequestParam、 @RequestBody、 @RequestHeader 、 @PathVariable)进行了研究,同时也看了一下HttpMessageConverter的相关内容,在此一并总结。

 

简介:

@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;@Autowiredpublic 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/”的请求;

上面仅仅介绍了,RequestMapping指定的方法处理哪些请求,下面一篇将讲解怎样处理request提交的数据(数据绑定)和返回的数据。

 

参考资料:

1、 Spring Web Doc: 

spring-3.1.0/docs/spring-framework-reference/html/mvc.html

转载于:https://www.cnblogs.com/powerwu/articles/5369646.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/396361.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

我的第一个网页 代码_我在免费代码营的第一个月

我的第一个网页 代码by Elliott McNary埃利奥特麦克纳里(Elliott McNary) 我在免费代码营的第一个月 (My First Month At Free Code Camp) I wanted to build an app that would help artists to make more money.我想开发一个可以帮助艺术家赚更多钱的应用。 I had a clear …

java pem rsa_如何从java中的pfx文件/ pem文件中获取RSA公钥的指数和模数值

I want to extract information about RSA Public Key from the pfx file using java.我有一个pfx文件并转换为x509 Pem文件 . 从pem文件&#xff0c;在终端中使用以下命令&#xff1a;openssl x509 -in file.pem -text我能够查看公钥指数和模数值主题公钥信息&#xff1a;Publ…

jmeter+maven+jenkins自动化接口测试(下)

mavenjmeter已经写好了&#xff0c;可以通过maven来执行jmeter的接口测试脚本&#xff0c;怎样实现定时执行测试并发送报告邮件就需要通过jenkins了&#xff08;jmeter或者testng也可以结合不同的邮件jar包来发送邮件&#xff0c;这里使用jenkins&#xff09; 安装jenkins笔记有…

在使用angularjs过程,ng-repeat中track by的作用

转载&#xff1a;http://segmentfault.com/q/1010000000405730<div ng-repeat"links in slides"> <div ng-repeat"link in links track by $index">link.name</div></div>Error: [ngRepeat:dupes]这个出错提示具体到题主的情况…

java判断读到末尾_IO流如何判断读取到了流的结尾,程序中以-1来判断,是流中写入一个EOF表示流结束吗,底层实现呢?...

-1不是流中写入的数据。read()方法返回的数据都是unsigned byte&#xff0c;即是[0,255]。底层实现有很多&#xff0c;比如socket IO和文件IO&#xff0c;甚至你自己也可以实现。——————————————————————给两个类的代码给你看看&#xff0c;理解一下这个东…

结束书

by William Countiss威廉Countiss 结束书 (Closing the Book on Closures) JavaScript closures are an important, but notoriously confusing concept. There’s no escaping it — if you want to grow as a developer, you need to understand what closures are and how …

java激励_激励干个人java的不足之处

1.你需要精通面向对象分析与设计(OOA/OOD)、涉及模式(GOF&#xff0c;J2EEDP)以及综合模式。你应该十分了解UML&#xff0c;尤其是class&#xff0c;object&#xff0c;interaction以及statediagrams。2.你需要学习JAVA语言的基础知识以及它的核心类库(collections&#xff0c;…

Bioconductor软件安装与升级

1 安装工具Bioc的软件包不能使用直接install.packages函数&#xff0c;它有自己的安装工具&#xff0c;使用下面的代码&#xff1a; source("https://bioconductor.org/biocLite.R")biocLite() 上面第二个语句将安装Bioconductor一些基础软件包&#xff0c;包括BiocI…

Laravel Kernel引导流程分析

Laravel Kernel引导流程分析 代码展示 protected function sendRequestThroughRouter($request) {# $this->app->instance(request, $request);# Facade::clearResolvedInstance(request);// 主要是这句代码$this->bootstrap();# return (new Pipeline($this->app)…

Android RecyclerView (一) 使用完全解析

转载请标明出处&#xff1a; http://blog.csdn.net/lmj623565791/article/details/45059587&#xff1b; 本文出自:【张鸿洋的博客】 概述 RecyclerView出现已经有一段时间了&#xff0c;相信大家肯定不陌生了&#xff0c;大家可以通过导入support-v7对其进行使用。 据官方的…

数据透视表日期怎么选范围_透视范围

数据透视表日期怎么选范围by Tiffany White蒂芙尼怀特(Tiffany White) 透视范围 (Putting Scope in Perspective) In JavaScript, lexical scope deals with where your variables are defined, and how they will be accessible — or not accessible — to the rest of your…

feign调用多个服务_Spring Cloud 快速入门系列之feign–微服务之间的调用

我们将一个大的应用拆成多个小的服务之后&#xff0c;紧接着的一个问题就是&#xff0c;原本都在一个项目里&#xff0c;方法我可以随便调用&#xff0c;但是拆开后&#xff0c;原来的方法就没法直接调用了&#xff0c;这时候要怎么办&#xff1f;Spring Cloud提供了feign&…

Asix下日志包冲突

为什么80%的码农都做不了架构师&#xff1f;>>> Class org.apache.commons.logging.impl.SLF4JLogFactory does not implement org.apache.commons.logging. 最近集成asix包的时候发生如下错误&#xff0c;原因是程序运行时logFactoryImple加载了JBOSS下面的sff4j包…

kubernetes中mysql乱码_在kubernetes中部署tomcat与mysql集群-Go语言中文社区

在kubernetes中部署tomcat与mysql集群之前必须要有以下这些基础&#xff1a;1. 已安装、配置kubernetes2. 集群中有tomcat与mysql容器镜像3. 有docker基础具体步骤部署tomcat创建tomcat RC对象我们想要在kubernetes集群中配置tomcat服务器&#xff0c;首先要保证集群中的节点上…

c# 测试运行时间毫秒级

long currentMillis (DateTime.Now.Ticks - (new DateTime(1970, 1, 1, 0, 0, 0, 0)).Ticks) / 10000;/*代码*/long currentMillis1 (DateTime.Now.Ticks - (new DateTime(1970, 1, 1, 0, 0, 0, 0)).Ticks) / 10000;MessageBox.Show((currentMillis1 - currentMillis).ToStri…

nodejs_NodeJS历险记

nodejsby Elliott McNary埃利奥特麦克纳里(Elliott McNary) NodeJS历险记 (Adventures in NodeJS) I built an app a couple of weeks ago after going through FreeCodeCamp’s Front-End curriculum and wanted to write an update as I head into NodeJS-land. I was final…

pytdx 获取板块指数_能否增加一个通过股票代码,板块指数代码获得中文名称的接口?...

T0002/hq_cache/shex.tnfT0002/hq_cache/szex.tnf这个解码就是。/***************************************************股票代码列表和股票名称T0002/hq_cache/shex.tnfT0002/hq_cache/szex.tnf***************************************************/struct TdxSymbolMap {cha…

灵动标签调用友情链接

1、文字形式[e:loop{select * from [!db.pre!]enewslink where checked1 and classid1 order by myorder,20,24,0}] <li><a href"<?$bqr[lurl]?>" title"<?$bqr[lname]?>" target"_blank"><?$bqr[lname]?>&…

4-----Scrapy框架中选择器的用法

Scrapy提取数据有自己的一套机制&#xff0c;被称作选择器&#xff08;selectors&#xff09;,通过特定的Xpath或者CSS表达式来选择HTML文件的某个部分Xpath是专门在XML文件中选择节点的语言&#xff0c;也可以用在HTML上。CSS是一门将HTML文档样式化语言&#xff0c;选择器由它…

【原】Jenkins持续集成环境搭建之创建java项目的job【centos6.5 java maven git 项目】...

一、构建一个maven项目在jenkins主页上&#xff0c;左侧&#xff0c;选择“新建”&#xff0c;然后填写项目名称&#xff0c;选择“构建一个maven项目”二、Git配置保存之后&#xff0c;进入详细配置页面&#xff1a;这里的源码管理&#xff1a;选择git&#xff0c;输入代码的g…