這段時間一直在着手於RESTful風格的接口設計。springmvc的RESTful風格的url是通過@RequestMapping 及@PathVariable annotation提供的。爲此我好好研究了一下關於Springmvc請求這方面的內容,也借鑑了前人的經驗寫下這篇博客,記錄下我的學習心得。
一、@RequestMapping簡介
@RequestMapping是用來映射URL,它可用在類定義處和方法定義處。我們映射的url是相對於根目錄而言的,如代碼所示:
package com.gray.user.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.gray.user.entity.User;
import com.gray.user.service.impl.UserServiceImpl;
@Controller
@RequestMapping("/test")
public class LoginController {
@Autowired
private UserServiceImpl userService;
@RequestMapping("/dologin.do") //url
public String dologin(User user, Model model){
if(userService.doUserLogin(user)){
model.addAttribute("successMsg", "登陸成功!");//返回到頁面所夾帶的參數
model.addAttribute("name", user.getUsername());
return "/success";//返回的頁面
}else{
model.addAttribute("failMsg", "用戶不存在或密碼錯誤!");
return "/fail";
}
}
}
dologin方法所映射的url地址我們寫成http://localhost:9090/test/dologin.do
關於RequestMapping這個註解,裏面一共有6個屬性
1.value
指定請求的實際地址;
2.method
指定請求的method類型, GET、POST、PUT、DELETE等;
3.consumes
指定處理請求的提交內容類型(Content-Type),例如application/json, text/html;
4.produces
指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回;
5.params
指定request中必須包含某些參數值;
6.headers
指定request中必須包含某些指定的header值;
二、@PathVariable簡介
當使用@RequestMapping URI template 樣式映射時, 即 someUrl/{paramId}, 這時的paramId可通過 @Pathvariable註解綁定它傳過來的值到方法的參數上。
三、@RequestBody簡介
該註解用於讀取Request請求的body部分數據,這主要是通過spring的消息轉換器messageConverter實現的,首先我們需要在配置文件裏面配上這個bean,通過已經配置的消息轉換器把相應的數據轉換成要傳入的對象進而綁定到方法的參數中。
四、@RequestParam簡介
在處理方法入參處使用 @RequestParam 可以把請求參數傳遞給請求方法,我們可以對傳入參數指定參數名,前端傳進來的參數名要和這個value值一致。我們也可以通過required=false或者true來要求@RequestParam配置的前端參數是否一定要傳。
五、@ResponseBody簡介
和@RequestBody相似的用法,根據配置的消息轉換器將對象轉換爲指定格式後,寫入到Response對象的body數據區。
六、@CookieValue簡介
從Http請求頭中的Cookie提取指定的某個Cookie。
七、常見註解用法實例
- 關於@RequestMapping
- value
value是默認屬性,即@RequestMapping("/dologin.do")和@RequestMapping(value="/dologin.do")是等價的。
- method
@RequestMapping(value = {"/ws/createEmployeeBasic","/ws/updateEmployeeBasic"}, method = RequestMethod.POST)
注:mapping的value是可以寫多個的。
- consumes
consumes="application/json",就是需要參數以json格式傳進來我才能接收。如1的代碼所示,隨後我們把傳進來的數據通過@RequestBody轉換成我要的對象。
- produces
@RequestMapping(value="/test.do",produces="application/json;charset=UTF-8"),和上面那個用法差不多。兩者區別就是前者只管請求,後者兩個都管。
- params
@RequestMapping(value="/dologin.do",params={"user=gray","pwd=111111"})
這種寫法就限制了只有當傳進來的參數user=gray並且pwd=111111時才能映射到下面的方法,否則報404。
- headers
老實說這個用法我幾乎沒用過。它用於指定請求頭裏面的參數,限客戶端的請求。如:
@RequestMapping(value="/dologin.do", headers="Host=localhost:9090")
這種寫法就是限制了只有本機發來的請求才接收。
2.關於@RequestBody和@PathVariable
在這裏我要說一下,帶佔位符的url,是Spring 3.0的新功能,我在項目中實現restful風格的url就是根據這個來實現的。
例如:
{token}等需要通過@PathVariable註解將佔位符中的參數綁定到方法的參數中。@RequestMapping(value = "/ws/OEmployeeBasic/{token}/{timestamp}", method = RequestMethod.POST, consumes="application/json") @ResponseBody public void pageList( @RequestBody Employee emp, @PathVariable String token, @PathVariable String timestamp, HttpServletRequest request, HttpServletResponse response){ ...... }
3.關於@ResponseBody
在springmvc的開發中,所有返回數據的請求都需要加上這個註解。如:
@RequestMapping("/myEspPageList.do") @ResponseBody public Object myPageList(Employee emp, HttpServletRequest request, HttpServletResponse response){ Object obj = super.pageList(emp, request, response); return obj; }
4.關於@RequestParam
差不多常用的和我項目中用過都一一列舉出來的。方便大家學習。正如上面所說的,返回頁面是不需要加@ResponseBody。@RequestMapping("/empTableList.do") public String list(Model model,@RequestParam(value="tabs",required=false)Integer tabs){ if (tabs == null || tabs > 3 || tabs < 0) tabs = 0; // tabs只允許0/1/2/3,默認爲0 model.addAttribute("tabs",tabs); return "/configuration/basetable_list"; }