JavaWeb-RESTful(一)_RESTful初認識 傳送門html
JavaWeb-RESTful(二)_使用SpringMVC開發RESTful_上 傳送門java
JavaWeb-RESTful(三)_使用SpringMVC開發RESTful_下 傳送門git
項目已上傳至github 傳送門github
Learnweb
1、單元測試:添加用戶spring
2、單元測試:修改用戶json
3、單元測試:刪除用戶數組
4、SpringBoot默認處理異常路徑服務器
1、單元測試:添加用戶app
在MainController.java中添加addUser()添加用戶的單元測試方法
@Test public void addUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"username\":\"Gary\"}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); }
給User實體對象設置三個熟悉,id、username、password
private String username; private String password; private String id;
經過id和username得到的試圖都是簡單試圖,經過password得到的試圖是複雜試圖
@JsonView(UserSimpleView.class) public String getId() { return id; } @JsonView(UserSimpleView.class) public String getUsername() { return username; } @JsonView(UserDetailView.class) public String getPassword() { return password; }
在UserController.java中經過addUser()方法得到MainController.java中的addUser()的POST請求
@RequestMapping(value="/user",method= RequestMethod.POST) public User addUser(@RequestBody User user) { //傳輸json格式的時候,必定要記得加上@RequestBody註解 //輸出 null System.out.println(user.getPassword()); //輸出 Gary System.out.println(user.getUsername()); user.setId("1"); return user; }
package com.Gary.GaryRESTful; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GaryResTfulApplication { public static void main(String[] args) { SpringApplication.run(GaryResTfulApplication.class, args); } }
package com.Gary.GaryRESTful.controller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; //這是SpringBoot測試類 @RunWith(SpringRunner.class) @SpringBootTest public class MainController { @Autowired private WebApplicationContext webApplicationContext; //SpringMV單元測試獨立測試類 private MockMvc mockMvc; @Before public void before() { //建立獨立測試類 mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } //@Test //查詢user public void test() throws Exception { //發起一個Get請求 String str = mockMvc.perform(MockMvcRequestBuilders.get("/user") .param("username", "Gary") //json的形式發送一個請求 .contentType(MediaType.APPLICATION_JSON_UTF8)) //指望服務器返回什麼(指望返回的狀態碼爲200) .andExpect(MockMvcResultMatchers.status().isOk()) //指望服務器返回json中的數組長度爲3 .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3)) .andReturn().getResponse().getContentAsString(); System.out.println("查詢簡單試圖"+str); } //@Test public void getInfo() throws Exception { //發起一個get請求,查看用戶詳情 String str = mockMvc.perform(MockMvcRequestBuilders.get("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Gary")) .andReturn().getResponse().getContentAsString(); System.out.println("查詢複雜試圖"+str); } @Test public void addUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"username\":\"Gary\"}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); } }
package com.Gary.GaryRESTful.controller; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.Gary.GaryRESTful.dto.User; import com.fasterxml.jackson.annotation.JsonView; //表示這個Controller提供R二十天API @RestController public class UserController { @RequestMapping(value="/user",method = RequestMethod.GET) /* * default value 默認 * name 請求的名字 * required 是不是必須的,true * value 別名 * * */ @JsonView(User.UserSimpleView.class) public List<User> query(@RequestParam(name="username",required=false) String username) { System.out.println(username); //知足指望服務器返回json中的數組長度爲3 List<User> list = new ArrayList<>(); list.add(new User()); list.add(new User()); list.add(new User()); return list; } @RequestMapping(value="/user/{id}",method= RequestMethod.GET) //將@PathVariable路徑中的片斷映射到java代碼中 @JsonView(User.UserDetailView.class) public User getInfo(@PathVariable String id) { User user = new User(); user.setUsername("Gary"); return user; } @RequestMapping(value="/user",method= RequestMethod.POST) public User addUser(@RequestBody User user) { //傳輸json格式的時候,必定要記得加上@RequestBody註解 //輸出 null System.out.println(user.getPassword()); //輸出 Gary System.out.println(user.getUsername()); user.setId("1"); return user; } }
package com.Gary.GaryRESTful.dto; import com.fasterxml.jackson.annotation.JsonView; public class User { //簡單試圖 只有一個username public interface UserSimpleView{}; //複雜試圖 有username 和 password public interface UserDetailView extends UserSimpleView{}; private String username; private String password; private String id; @JsonView(UserSimpleView.class) public String getId() { return id; } public void setId(String id) { this.id = id; } @JsonView(UserSimpleView.class) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @JsonView(UserDetailView.class) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
2、單元測試:修改用戶
在MainController.java中添加updataUser()修改用戶的單元測試方法
//修改用戶 @Test public void updataUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.put("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"username\":\"Garyary\",\"id\":\"1\"}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); }
在UserController.java中接收來自updataUser的請求
//修改用戶資料 @RequestMapping(value="/user/{id}",method = RequestMethod.PUT) public User updataUser(@RequestBody User user) { System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); return user; }
package com.Gary.GaryRESTful; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GaryResTfulApplication { public static void main(String[] args) { SpringApplication.run(GaryResTfulApplication.class, args); } }
package com.Gary.GaryRESTful.controller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; //這是SpringBoot測試類 @RunWith(SpringRunner.class) @SpringBootTest public class MainController { @Autowired private WebApplicationContext webApplicationContext; //SpringMV單元測試獨立測試類 private MockMvc mockMvc; @Before public void before() { //建立獨立測試類 mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } //@Test //查詢user public void test() throws Exception { //發起一個Get請求 String str = mockMvc.perform(MockMvcRequestBuilders.get("/user") .param("username", "Gary") //json的形式發送一個請求 .contentType(MediaType.APPLICATION_JSON_UTF8)) //指望服務器返回什麼(指望返回的狀態碼爲200) .andExpect(MockMvcResultMatchers.status().isOk()) //指望服務器返回json中的數組長度爲3 .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3)) .andReturn().getResponse().getContentAsString(); System.out.println("查詢簡單試圖"+str); } //@Test public void getInfo() throws Exception { //發起一個get請求,查看用戶詳情 String str = mockMvc.perform(MockMvcRequestBuilders.get("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Gary")) .andReturn().getResponse().getContentAsString(); System.out.println("查詢複雜試圖"+str); } //添加用戶 //@Test public void addUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"username\":\"Gary\"}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); } //修改用戶 @Test public void updataUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.put("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"username\":\"Garyary\",\"id\":\"1\"}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); } }
package com.Gary.GaryRESTful.controller; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.Gary.GaryRESTful.dto.User; import com.fasterxml.jackson.annotation.JsonView; //表示這個Controller提供R二十天API @RestController public class UserController { @RequestMapping(value="/user",method = RequestMethod.GET) /* * default value 默認 * name 請求的名字 * required 是不是必須的,true * value 別名 * * */ @JsonView(User.UserSimpleView.class) public List<User> query(@RequestParam(name="username",required=false) String username) { System.out.println(username); //知足指望服務器返回json中的數組長度爲3 List<User> list = new ArrayList<>(); list.add(new User()); list.add(new User()); list.add(new User()); return list; } @RequestMapping(value="/user/{id}",method= RequestMethod.GET) //將@PathVariable路徑中的片斷映射到java代碼中 @JsonView(User.UserDetailView.class) public User getInfo(@PathVariable String id) { User user = new User(); user.setUsername("Gary"); return user; } @RequestMapping(value="/user",method= RequestMethod.POST) public User addUser(@RequestBody User user) { //傳輸json格式的時候,必定要記得加上@RequestBody註解 //輸出 null System.out.println(user.getPassword()); //輸出 Gary System.out.println(user.getUsername()); user.setId("1"); return user; } //修改用戶資料 @RequestMapping(value="/user/{id}",method = RequestMethod.PUT) public User updataUser(@RequestBody User user) { System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); return user; } }
package com.Gary.GaryRESTful.dto; import com.fasterxml.jackson.annotation.JsonView; public class User { //簡單試圖 只有一個username public interface UserSimpleView{}; //複雜試圖 有username 和 password public interface UserDetailView extends UserSimpleView{}; private String username; private String password; private String id; @JsonView(UserSimpleView.class) public String getId() { return id; } public void setId(String id) { this.id = id; } @JsonView(UserSimpleView.class) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @JsonView(UserDetailView.class) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
3、單元測試:刪除用戶
在MainController.java中添加deleteUser()修改用戶的單元測試方法
//刪除用戶 @Test public void deleteUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.delete("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()); }
在UserController.java中接收來自deleteUser的請求
@RequestMapping(value="/user/{id}",method = RequestMethod.DELETE) public User deleteUser(@PathVariable String id) { System.out.println(id); return null; }
package com.Gary.GaryRESTful; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GaryResTfulApplication { public static void main(String[] args) { SpringApplication.run(GaryResTfulApplication.class, args); } }
package com.Gary.GaryRESTful.controller; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; //這是SpringBoot測試類 @RunWith(SpringRunner.class) @SpringBootTest public class MainController { @Autowired private WebApplicationContext webApplicationContext; //SpringMV單元測試獨立測試類 private MockMvc mockMvc; @Before public void before() { //建立獨立測試類 mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } //@Test //查詢user public void test() throws Exception { //發起一個Get請求 String str = mockMvc.perform(MockMvcRequestBuilders.get("/user") .param("username", "Gary") //json的形式發送一個請求 .contentType(MediaType.APPLICATION_JSON_UTF8)) //指望服務器返回什麼(指望返回的狀態碼爲200) .andExpect(MockMvcResultMatchers.status().isOk()) //指望服務器返回json中的數組長度爲3 .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3)) .andReturn().getResponse().getContentAsString(); System.out.println("查詢簡單試圖"+str); } //@Test public void getInfo() throws Exception { //發起一個get請求,查看用戶詳情 String str = mockMvc.perform(MockMvcRequestBuilders.get("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Gary")) .andReturn().getResponse().getContentAsString(); System.out.println("查詢複雜試圖"+str); } //添加用戶 //@Test public void addUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/user") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"username\":\"Gary\"}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); } //修改用戶 //@Test public void updataUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.put("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8) .content("{\"username\":\"Garyary\",\"id\":\"1\"}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value("1")); } //刪除用戶 @Test public void deleteUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.delete("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()); } }
package com.Gary.GaryRESTful.controller; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.Gary.GaryRESTful.dto.User; import com.fasterxml.jackson.annotation.JsonView; //表示這個Controller提供R二十天API @RestController public class UserController { @RequestMapping(value="/user",method = RequestMethod.GET) /* * default value 默認 * name 請求的名字 * required 是不是必須的,true * value 別名 * * */ @JsonView(User.UserSimpleView.class) public List<User> query(@RequestParam(name="username",required=false) String username) { System.out.println(username); //知足指望服務器返回json中的數組長度爲3 List<User> list = new ArrayList<>(); list.add(new User()); list.add(new User()); list.add(new User()); return list; } @RequestMapping(value="/user/{id}",method= RequestMethod.GET) //將@PathVariable路徑中的片斷映射到java代碼中 @JsonView(User.UserDetailView.class) public User getInfo(@PathVariable String id) { User user = new User(); user.setUsername("Gary"); return user; } @RequestMapping(value="/user",method= RequestMethod.POST) public User addUser(@RequestBody User user) { //傳輸json格式的時候,必定要記得加上@RequestBody註解 //輸出 null System.out.println(user.getPassword()); //輸出 Gary System.out.println(user.getUsername()); user.setId("1"); return user; } //修改用戶資料 @RequestMapping(value="/user/{id}",method = RequestMethod.PUT) public User updataUser(@RequestBody User user) { System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); return user; } //刪除 @RequestMapping(value="/user/{id}",method = RequestMethod.DELETE) public User deleteUser(@PathVariable String id) { //輸出刪除的用戶 能夠查看JUnit中的狀態嗎 System.out.println(id); return null; } }
package com.Gary.GaryRESTful.dto; import com.fasterxml.jackson.annotation.JsonView; public class User { //簡單試圖 只有一個username public interface UserSimpleView{}; //複雜試圖 有username 和 password public interface UserDetailView extends UserSimpleView{}; private String username; private String password; private String id; @JsonView(UserSimpleView.class) public String getId() { return id; } public void setId(String id) { this.id = id; } @JsonView(UserSimpleView.class) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @JsonView(UserDetailView.class) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
在UserController.java中經過@RequestMapping("/user")映射來處理全部user請求,使代碼變得簡介一些
package com.Gary.GaryRESTful.controller; import java.util.ArrayList; import java.util.List; import org.junit.Test; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.Gary.GaryRESTful.dto.User; import com.fasterxml.jackson.annotation.JsonView; //表示這個Controller提供R二十天API @RestController @RequestMapping("/user") public class UserController { //@RequestMapping(value="/user",method = RequestMethod.GET) /* * default value 默認 * name 請求的名字 * required 是不是必須的,true * value 別名 * * */ @GetMapping @JsonView(User.UserSimpleView.class) public List<User> query(@RequestParam(name="username",required=false) String username) { System.out.println(username); //知足指望服務器返回json中的數組長度爲3 List<User> list = new ArrayList<>(); list.add(new User()); list.add(new User()); list.add(new User()); return list; } //@RequestMapping(value="/user/{id}",method= RequestMethod.GET) //將@PathVariable路徑中的片斷映射到java代碼中 @GetMapping("/{id}") @JsonView(User.UserDetailView.class) public User getInfo(@PathVariable String id) { User user = new User(); user.setUsername("Gary"); return user; } //添加用戶 //@RequestMapping(value="/user",method= RequestMethod.POST) @PostMapping public User addUser(@RequestBody User user) { //傳輸json格式的時候,必定要記得加上@RequestBody註解 //輸出 null System.out.println(user.getPassword()); //輸出 Gary System.out.println(user.getUsername()); user.setId("1"); return user; } //修改用戶資料 //@RequestMapping(value="/user/{id}",method = RequestMethod.PUT) @PutMapping("/{id}") public User updataUser(@RequestBody User user) { System.out.println(user.getId()); System.out.println(user.getUsername()); System.out.println(user.getPassword()); return user; } //刪除 //@RequestMapping(value="/user/{id}",method = RequestMethod.DELETE) @DeleteMapping("/{id}") public User deleteUser(@PathVariable String id) { //輸出刪除的用戶 能夠查看JUnit中的狀態嗎 System.out.println(id); return null; } }
4、SpringBoot默認處理異常路徑
在項目static->error目錄下建立一個404.html,運行項目
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>404頁面</title> </head> <body> <h1>404錯誤,你的頁面找不到了!!!</h1> </body> </html>