目录

spring boot restful API风格

2018年04月18日 15:55 | 3850次浏览

回顾并详细说明一下在在之前章节中的中使用的@Controller@RestController@RequestMapping注解。如果您对Spring MVC不熟悉并且还没有尝试过快速入门案例,建议先看一下之前的内容。

       下面我们尝试使用Spring MVC来实现一组对User对象操作的RESTful API,配合注释详细说明在Spring MVC中如何映射HTTP请求、如何传参、如何编写单元测试


* RESTful API具体设计如下:*

请求类型URL功能说明
GET/users查询用户列表
POST/users创建一个用户
GET/users/id根据id查询一个用户
PUT/users/id根据id更新一个用户
DELETE/users/id根据id删除一个用户


User实体定义

public class User {
   privatelongid;
   private String name;
   private Integer age;
   // 省略setter和getter
}


实现对User对象的操作接口:

package com.kfit.controller;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.RestController;
import com.kfit.demo.User;
 
@RestController
@RequestMapping(value="/users")// 通过这里配置使下面的映射都在/users下  
public class UserController {
   
    //这里为了方便测试,直接将数据存储在map中,实际请从数据库获取.
    private static Map<Long,User> users = Collections.synchronizedMap(new HashMap<Long,User>());
   
    /**
     * 返回所有的用户.
     * @return
     */
    @RequestMapping(value="", method=RequestMethod.GET)
    public List<User> getUserList() {
        // 处理"/users/"的GET请求,用来获取用户列表
        // 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
        List<User> r = new ArrayList<User>(users.values());
        returnr;
    }
   
    @RequestMapping(value="/{id}", method=RequestMethod.GET)
    public User getUser(@PathVariable Long id) {
        // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
        // url中的id可通过@PathVariable绑定到函数的参数中
        returnusers.get(id);
    }
   
    /**
     * post 保存用户.
     * @param user
     * @return
     */
    @RequestMapping(value = "",method=RequestMethod.POST)
    public String postUser(User user){
        // 处理"/users/"的POST请求,用来创建User
        //@ModelAttribute User user
        // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
        users.put(user.getId(), user);
        return"success";
    }
   
    /**
     * 使用put 进行更新用户.
     * @param id
     * @param user
     * @return
     */
    @RequestMapping(value="/{id}",method=RequestMethod.PUT)
    public String putUser(@PathVariable Long id,User user){
        // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
         User u = users.get(id);
         u.setName(user.getName());
         u.setAge(user.getAge());
         users.put(id, u);
        return"success";
    }
   
    /**
     * 使用delete删除用户.
     * @param id
     * @return
     */
    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id) {
        // 处理"/users/{id}"的DELETE请求,用来删除User
        // url中的id可通过@PathVariable绑定到函数的参数中
        users.remove(id);
        return"success";
    }
   
}

下面针对该Controller编写测试用例验证正确性,具体如下。当然也可以通过浏览器插件等进行请求提交验证:

package com.kfit.demo;
 
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.RequestBuilder;
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 com.kfit.controller.UserController;
 
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=MockServletContext.class)//MockServletContext.class
@WebAppConfiguration
public class UserControllerTest extends MockMvcResultMatchers{
   
    //模拟mvc对象类.
    private MockMvc mvc;
   
    @Before
    public void setup(){
       /*
        * MockMvcBuilders使用构建MockMvc对象.
        */
       mvc = MockMvcBuilders.standaloneSetup(new UserController()).build();
    }
   
    @Test
    public void testUserController() throws Exception{
       RequestBuilder request = null;
       //1. get 以下user列表,应该为空》
   
       //1、构建一个get请求.
       request = MockMvcRequestBuilders.get("/users");
       mvc.perform(request)
           .andExpect(status().isOk())
           .andExpect(content().string("[]"))
           ;
       System.out.println("UserControllerTest.testUserController().get");
      
       // 2、post提交一个user
       request = MockMvcRequestBuilders.post("/users")
                                   .param("id","1")
                                   .param("name","林彪")
                                   .param("age","20")
              ;
      
      
        mvc.perform(request).andExpect(status().isOk()).andExpect(content().string("success"));
 
       // 3、get获取user列表,应该有刚才插入的数据
       request = MockMvcRequestBuilders.get("/users");
    mvc.perform(request).andExpect(status().isOk()).andExpect(content().string("[{\"id\":1,\"name\":\"林峰\",\"age\":20}]"));
      
      
       // 4、put修改id为1的user
        request = MockMvcRequestBuilders.put("/users/1")
                .param("name", "林则徐")
                .param("age", "30");
        mvc.perform(request)
                .andExpect(content().string("success"));
       
        // 5、get一个id为1的user
        request = MockMvcRequestBuilders.get("/users/1");
        mvc.perform(request)
                .andExpect(content().string("{\"id\":1,\"name\":\"林则徐\",\"age\":30}"));
      
       
       
     // 6、del删除id为1的user
        request = MockMvcRequestBuilders.delete("/users/1");
        mvc.perform(request)
                .andExpect(content().string("success"));
 
        // 7、get查一下user列表,应该为空
        request = MockMvcRequestBuilders.get("/users");
        mvc.perform(request)
                .andExpect(status().isOk())
                .andExpect(content().string("[]"));
       
    }
   
}

至此,我们通过引入web模块(没有做其他的任何配置),就可以轻松利用Spring MVC的功能,以非常简洁的代码完成了对User对象的RESTful API的创建以及单元测试的编写。


小说《我是全球混乱的源头》

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程


上一篇:spring boot 发送邮件 下一篇:mongodb php
^