@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.pswp.cn/news/396361.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/396361.shtml
英文地址,請注明出處:http://en.pswp.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…