@Controller
:修飾class,用來建立處理http請求的對象@RestController
:Spring4以後加入的註解,原來在@Controller
中返回json須要@ResponseBody
來配合,若是直接用@RestController
替代@Controller
就不須要再配置@ResponseBody
,默認返回json格式。@RequestMapping
:配置url映射下面咱們嘗試使用Spring MVC來實現一組對User對象操做的RESTful API,配合註釋詳細說明在Spring MVC中如何映射HTTP請求、如何傳參、如何編寫單元測試。web
RESTful API具體設計以下:spring
User實體定義:json
public class User { private Long id; private String name; private Integer age; // 省略setter和getter }
實現對User對象的操做接口api
1 @RestController 2 @RequestMapping(value="/users") // 經過這裏配置使下面的映射都在/users下 3 public class UserController { 4 5 // 建立線程安全的Map 6 static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); 7 8 @RequestMapping(value="/", method=RequestMethod.GET) 9 public List<User> getUserList() { 10 // 處理"/users/"的GET請求,用來獲取用戶列表 11 // 還能夠經過@RequestParam從頁面中傳遞參數來進行查詢條件或者翻頁信息的傳遞 12 List<User> r = new ArrayList<User>(users.values()); 13 return r; 14 } 15 16 @RequestMapping(value="/", method=RequestMethod.POST) 17 public String postUser(@ModelAttribute User user) { 18 // 處理"/users/"的POST請求,用來建立User 19 // 除了@ModelAttribute綁定參數以外,還能夠經過@RequestParam從頁面中傳遞參數 20 users.put(user.getId(), user); 21 return "success"; 22 } 23 24 @RequestMapping(value="/{id}", method=RequestMethod.GET) 25 public User getUser(@PathVariable Long id) { 26 // 處理"/users/{id}"的GET請求,用來獲取url中id值的User信息 27 // url中的id可經過@PathVariable綁定到函數的參數中 28 return users.get(id); 29 } 30 31 @RequestMapping(value="/{id}", method=RequestMethod.PUT) 32 public String putUser(@PathVariable Long id, @ModelAttribute User user) { 33 // 處理"/users/{id}"的PUT請求,用來更新User信息 34 User u = users.get(id); 35 u.setName(user.getName()); 36 u.setAge(user.getAge()); 37 users.put(id, u); 38 return "success"; 39 } 40 41 @RequestMapping(value="/{id}", method=RequestMethod.DELETE) 42 public String deleteUser(@PathVariable Long id) { 43 // 處理"/users/{id}"的DELETE請求,用來刪除User 44 users.remove(id); 45 return "success"; 46 } 47 48 }
下面針對該Controller編寫測試用例驗證正確性,具體以下。固然也能夠經過瀏覽器插件等進行請求提交驗證。瀏覽器
1 2 3 import org.junit.Before; 4 import org.junit.Test; 5 import org.junit.runner.RunWith; 6 import org.springframework.boot.test.context.SpringBootTest; 7 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 8 import org.springframework.test.context.web.WebAppConfiguration; 9 import org.springframework.test.web.servlet.MockMvc; 10 import org.springframework.test.web.servlet.RequestBuilder; 11 import org.springframework.test.web.servlet.setup.MockMvcBuilders; 12 13 import static org.hamcrest.Matchers.equalTo; 14 import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; 15 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; 16 import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; 17 18 @RunWith(SpringJUnit4ClassRunner.class) 19 @SpringBootTest 20 @WebAppConfiguration 21 public class ApplicationTest { 22 23 private MockMvc mvc; 24 25 @Before 26 public void setUp() throws Exception { 27 mvc = MockMvcBuilders.standaloneSetup(new UserController()).build(); 28 } 29 30 @Test 31 public void testUserController() throws Exception { 32 // 測試UserController 33 RequestBuilder request = null; 34 35 // 一、get查一下user列表,應該爲空 36 request = get("/users/"); 37 mvc.perform(request) 38 .andExpect(status().isOk()) 39 .andExpect(content().string(equalTo("[]"))); 40 41 // 二、post提交一個user 42 request = post("/users/") 43 .param("id", "1") 44 .param("name", "測試大師") 45 .param("age", "20"); 46 mvc.perform(request) 47 .andExpect(content().string(equalTo("success"))); 48 49 // 三、get獲取user列表,應該有剛纔插入的數據 50 request = get("/users/"); 51 mvc.perform(request) 52 .andExpect(status().isOk()) 53 .andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"測試大師\",\"age\":20}]"))); 54 55 // 四、put修改id爲1的user 56 request = put("/users/1") 57 .param("name", "測試終極大師") 58 .param("age", "30"); 59 mvc.perform(request) 60 .andExpect(content().string(equalTo("success"))); 61 62 // 五、get一個id爲1的user 63 request = get("/users/1"); 64 mvc.perform(request) 65 .andExpect(content().string(equalTo("{\"id\":1,\"name\":\"測試終極大師\",\"age\":30}"))); 66 67 // 六、del刪除id爲1的user 68 request = delete("/users/1"); 69 mvc.perform(request) 70 .andExpect(content().string(equalTo("success"))); 71 72 // 七、get查一下user列表,應該爲空 73 request = get("/users/"); 74 mvc.perform(request) 75 .andExpect(status().isOk()) 76 .andExpect(content().string(equalTo("[]"))); 77 78 } 79 80 }
至此,咱們經過引入web模塊(沒有作其餘的任何配置),就能夠輕鬆利用Spring MVC的功能,以很是簡潔的代碼完成了對User對象的RESTful API的建立以及單元測試的編寫。其中同時介紹了Spring MVC中最爲經常使用的幾個核心註解:@Controller
,@RestController
,RequestMapping
以及一些參數綁定的註解:@PathVariable
,@ModelAttribute
,@RequestParam
等。安全