zoukankan      html  css  js  c++  java
  • JavaWeb-RESTful(二)_使用SpringMVC开发RESTful_上

      JavaWeb-RESTful(一)_RESTful初认识  传送门

      JavaWeb-RESTful(二)_使用SpringMVC开发RESTful_上  传送门

      JavaWeb-RESTful(三)_使用SpringMVC开发RESTful_下  传送门

      项目已上传至github  传送门 

      Learn

         一、实现一个成功的SpringMVC单元测试类

        二、RequestParam注解:

        三、JsonView注解

      创建SpringBoot项目  传送门

      

      【 添加Spring Web Starter,Spring Data JPA,Spring Security,Thymeleaf,Spring Data Elasticsearch,Cloud OAuth2,Spring Session,MySQL Driver,H2 Database依赖】 

    一、实现一个成功的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);
        }
    
    }
    GaryResTfulApplication.java
    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));
                
            }
            
    }
    MainController.java
    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;
        }
        
    }
    UserController.java
    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;
        }
        
    }
    User.java

    二、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));
                
            }
            
    }
    MainController.java
    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
        
    }
    UserController.java

      如果需要访问用户详细信息,在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);
        }
    
    }
    GaryResTfulApplication.java
    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"));
            }
    }
    MainController.java
    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;
        }
        
        
        
    }
    UserController.java
    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;
        }
        
    }
    User.java

    三、JsonView注解

      @JsonView是Jackson的一个注解,可以用来过滤序列化对象的字段属性,是你可以选择序列化对象哪些属性,哪些过滤掉。

      @JsonView使用步骤:

        1、使用接口来声明多个视图

        2、在值对象的get方法上指定视图

        3、在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);
                        
            }
    }
    MainController.java

      发现此时输出来的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);
        }
    
    }
    GaryResTfulApplication.java
    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);
                        
            }
    }
    MainController.java
    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;
        }
        
        
        
    }
    UserController.java
    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;
        }
        
    }
    User.java
  • 相关阅读:
    PHP和Redis实现在高并发下的抢购及秒杀功能示例详解
    thinkphp整合系列之微信公众号支付
    JS之变量的运算
    (php)thinkphp3.2配置sql_server
    jyd数据结构
    mac终端下svn常用命令
    项目学习
    抛错
    phpunit
    Python
  • 原文地址:https://www.cnblogs.com/1138720556Gary/p/11441219.html
Copyright © 2011-2022 走看看