JavaWeb-RESTful(一)_RESTful初認識 傳送門html
JavaWeb-RESTful(二)_使用SpringMVC開發RESTful_上 傳送門java
JavaWeb-RESTful(三)_使用SpringMVC開發RESTful_下 傳送門git
項目已上傳至github 傳送門 github
Learnweb
1、實現一個成功的SpringMVC單元測試類spring
2、RequestParam註解:json
3、JsonView註解數組
建立SpringBoot項目 傳送門服務器
【 添加Spring Web Starter,Spring Data JPA,Spring Security,Thymeleaf,Spring Data Elasticsearch,Cloud OAuth2,Spring Session,MySQL Driver,H2 Database依賴】 app
1、實現一個成功的SpringMVC單元測試類
在MainController.java中向服務器以Json格式發起一個請求,並反回兩個指望
指望一:指望服務器返回狀態碼爲200
指望二:指望服務器返回json中的數組長度爲3
@Test //查詢user public void test() throws Exception { //發起一個Get請求 mockMvc.perform(MockMvcRequestBuilders.get("/user") //json的形式發送一個請求 .contentType(MediaType.APPLICATION_JSON_UTF8)) //指望服務器返回什麼(指望返回的狀態碼爲200) .andExpect(MockMvcResultMatchers.status().isOk()) //指望服務器返回json中的數組長度爲3 .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3)); }
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請求 mockMvc.perform(MockMvcRequestBuilders.get("/user") //json的形式發送一個請求 .contentType(MediaType.APPLICATION_JSON_UTF8)) //指望服務器返回什麼(指望返回的狀態碼爲200) .andExpect(MockMvcResultMatchers.status().isOk()) //指望服務器返回json中的數組長度爲3 .andExpect(MockMvcResultMatchers.jsonPath("$.length()").value(3)); } }
package com.Gary.GaryRESTful.controller; import java.util.ArrayList; import java.util.List; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.Gary.GaryRESTful.dto.User; //表示這個Controller提供R二十天API @RestController public class UserController { @RequestMapping(value="/user",method = RequestMethod.GET) public List<User> query() { //知足指望服務器返回json中的數組長度爲3 List<User> list = new ArrayList<>(); list.add(new User()); list.add(new User()); list.add(new User()); return list; } }
package com.Gary.GaryRESTful.dto; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
2、RequestParam註解:
@RequestParam 獲取請求參數的值
在MainController.java中經過param方法給Get請求添加參數
@Test //查詢user public void test() throws Exception { //發起一個Get請求 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)); }
在UserController.java中經過@RequestParam注入username參數,並經過System.out.println(username)輸出username中的值
@RequestMapping(value="/user",method = RequestMethod.GET) /* * default value 默認 * name 請求的名字 * required 是不是必須的,true * value 別名 * * */ 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; }
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請求 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)); } }
package com.Gary.GaryRESTful.controller; import java.util.ArrayList; import java.util.List; 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; //表示這個Controller提供R二十天API @RestController public class UserController { @RequestMapping(value="/user",method = RequestMethod.GET) public List<User> query(@RequestParam 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; } //@RequestParam }
若是須要訪問用戶詳細信息,在MainController.java中添加getInfo()方法,發起一個get請求去查看用戶詳情
@Test public void getInfo() throws Exception { //發起一個get請求,查看用戶詳情 mockMvc.perform(MockMvcRequestBuilders.get("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Gary")); }
在UserController.java中添加一個getInfo()方法,去接收該請求
@RequestMapping(value="/user/{id}",method= RequestMethod.GET) //將@PathVariable路徑中的片斷映射到java代碼中 public User getInfo(@PathVariable String id) { User user = new User(); user.setUsername("Gary"); 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請求 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)); } @Test public void getInfo() throws Exception { //發起一個get請求,查看用戶詳情 mockMvc.perform(MockMvcRequestBuilders.get("/user/1") .contentType(MediaType.APPLICATION_JSON_UTF8)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.username").value("Gary")); } }
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.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; //表示這個Controller提供R二十天API @RestController public class UserController { @RequestMapping(value="/user",method = RequestMethod.GET) /* * default value 默認 * name 請求的名字 * required 是不是必須的,true * value 別名 * * */ 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代碼中 public User getInfo(@PathVariable String id) { User user = new User(); user.setUsername("Gary"); return user; } }
package com.Gary.GaryRESTful.dto; public class User { private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
3、JsonView註解
@JsonView是Jackson的一個註解,能夠用來過濾序列化對象的字段屬性,是你能夠選擇序列化對象哪些屬性,哪些過濾掉。
@JsonView使用步驟:
一、使用接口來聲明多個視圖
二、在值對象的get方法上指定視圖
三、在Controller方法上指定視圖
經過.andReturn().getResponse().getContentAsString()將mockMvc.perform(MockMvcRequestBuilders.get("/user/1")發送的get請求以字符串的格式打印出來
@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); }
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請求 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)); } @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); } }
發現此時輸出來的json字符串格式是{"username":"Gary","password":null},但咱們此時不但願用戶看到password時,就能夠用到@JsonView這個註解了
使用接口聲明多個視圖
1)username,password
2)username
在值對象的get方法中指定視圖
//簡單試圖 只有一個username public interface UserSimpleView{}; //複雜試圖 有username 和 password public interface UserDetailView extends UserSimpleView{}; private String username; private String password; @JsonView(UserSimpleView.class) public String getUsername() { return username; } @JsonView(UserDetailView.class) public String getPassword() { return password; }
在controller方法中指定視圖
@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; }
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); } }
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.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; } }
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; @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; } }