Spring Boot 技术探索

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".

20、Spring Boot之RESTful Web服务的构建

平台环境:

名称

版本号

Mac OS X

10.14.6

JDK

1.8.0_201

Apache Maven

3.6.0

IntelliJ IDEA

2019.1 (Ultimate Edition)

Spring Boot

2.1.8.RELEASE

 

  两篇背景知识文章:

  理解RESTful架构:http://www.ruanyifeng.com/blog/2011/09/restful.html

  RESTful API 最佳实践:http://www.ruanyifeng.com/blog/2018/10/restful-api-best-practices.html

 

  通过背景知识了解到,RESTful一种规范。只要符合规范,用什么方式来实现都可以。这里使用Spring Boot来实现一组符合RESTful规范的URI。

 

Demo:

  这里假想一个微博程序,需要设计一套客户端app与服务器端通讯的API,参考RESTful规范设计如下。

请求方式

URI

用途

GET

/Blogs

获取blog列表

POST

/Blog

发布一条blog

PUT

/Blog

修改一条blog

PATCH

/Blog/Content

修改一条blog的内容

GET

/Blog/{id}

获取一条blog

DELETE

/Blog/{id}

删除一条blog

新建工程,pom.xml增加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

 

新建model类Blog

package com.example.demo.model;


public class Blog
{
    private Long id;
    private String Title;
    private String Content;


    public Long getId()
    {
        return id;
    }


    public void setId(Long id)
    {
        this.id = id;
    }


    public String getTitle()
    {
        return Title;
    }


    public void setTitle(String title)
    {
        Title = title;
    }


    public String getContent()
    {
        return Content;
    }


    public void setContent(String content)
    {
        Content = content;
    }


    public Blog(Long id, String title, String content)
    {
        this.setId(id);
        this.setTitle(title);
        this.setContent(content);
    }
}

 

新建控制类DemoController

package com.example.demo.controller;




import com.example.demo.model.Blog;
import org.springframework.web.bind.annotation.*;


import java.util.ArrayList;
import java.util.List;


@RestController
public class DemoController
{
    // 获取blog列表
    @GetMapping("Blogs")
    public List<Blog> Blogs()
    {
        System.out.println("select id, Title, Content from blogs");
        List<Blog> blogs = new ArrayList<>();
        blogs.add(new Blog(1L, "title1", "content1"));
        blogs.add(new Blog(2L, "title2", "content2"));
        return blogs;
    }


    // 发布一条blog
    @PostMapping("/Blog")
    public Blog create(Blog blog)
    {
        System.out.println("insert into blogs(id, Title, Content) values(" + blog.getId() + ",'" + blog.getTitle() + "','" + blog.getContent() + "')");
        return blog;
    }


    // 修改一条blog
    @PutMapping("/Blog")
    public Blog update(Blog blog)
    {
        System.out.println("update blogs set id=" + blog.getId() + ",Title='" + blog.getTitle() + "',Content='" + blog.getContent() + "' where id=" + blog.getId());
        return blog;
    }


    // 修改一条blog的内容
    @PatchMapping("/Blog/Content")
    public Blog patch(Blog blog)
    {
        System.out.println("update blogs set Content='" + blog.getContent() + "' where id=" + blog.getId());
        return blog;
    }


    // 获取一条blog
    @GetMapping("/Blog/{id}")
    public Blog get(@PathVariable Long id)
    {
        System.out.println("select id, Title, Content from blogs where id=" + id);
        Blog Blog = new Blog(id, "titleXXX", "contentXXX");
        return Blog;
    }


    // 删除一条blog
    @DeleteMapping("/Blog/{id}")
    public void delete(@PathVariable("id") Long id)
    {
        System.out.println("delete from blogs where id=" + id);
    }
}

 

接下来是测试过程

新建测试类DemoControllerTest

package com.example.demo;


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.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.setup.MockMvcBuilders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.context.WebApplicationContext;


@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoControllerTest
{
    @Autowired
    private WebApplicationContext wac;


    private MockMvc mockMvc;


    @Before
    public void setup()
    {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }


    @Test
    public void testBlogs() throws Exception
    {
        String mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/Blogs")).andReturn().getResponse().getContentAsString();
        System.out.println("Result === " + mvcResult);
    }


    @Test
    public void testCreate() throws Exception
    {
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("Title", "title11");
        params.add("Content", "content22");
        String mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/Blog").params(params)).andReturn().getResponse().getContentAsString();
        System.out.println("Result === " + mvcResult);
    }


    @Test
    public void testUpdate() throws Exception
    {
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("id", "11");
        params.add("Title", "title11");
        params.add("Content", "content22");
        String mvcResult = mockMvc.perform(MockMvcRequestBuilders.put("/Blog").params(params)).andReturn().getResponse().getContentAsString();
        System.out.println("Result === " + mvcResult);
    }


    @Test
    public void testPatch() throws Exception
    {
        final MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("id", "11");
        params.add("Content", "content22");
        String mvcResult = mockMvc.perform(MockMvcRequestBuilders.patch("/Blog/Content").params(params)).andReturn().getResponse().getContentAsString();
        System.out.println("Result === " + mvcResult);
    }


    @Test
    public void testGet() throws Exception
    {
        String mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/Blog/66")).andReturn().getResponse().getContentAsString();
        System.out.println("Result === " + mvcResult);
    }


    @Test
    public void testDelete() throws Exception
    {
        String mvcResult = mockMvc.perform(MockMvcRequestBuilders.delete("/Blog/99")).andReturn().getResponse().getContentAsString();
        System.out.println("Result === " + mvcResult);
    }
}

 

 

Bootstrap Thumbnail Second
MySQL

MySQL is the world's most popular open source database.

GO

Bootstrap Thumbnail Third
算法基础

本书介绍了什么是计算机算法,如何描述它们,以及如何来评估它们。

GO