ramostear.comramostear.com 谭朝红的技术分享博客

格言 编程是一门技术,也是一门艺术 !

使用Spring Boot构建RESTful 服务

使用Spring Boot构建RESTful 服务

Spring Boot(六) — 构建RESTful Web服务

Spring Boot能够轻松的构建起企业级的RESTful Web服务程序。在本章节中,我将通过一个简单的例子演示Spring Boot的这一能力。
为了构建RESTful Web服务,我们需要将Spring Boot Starter Web依赖添加到pom.xml配置文件中。

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

下面是完整的Maven pom.xml配置文件代码:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ramostear</groupId>
    <artifactId>restful-webservice</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>restful-webservice</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

说明:Lombok是一个java库,可以自动插入编辑器并构建工具,使用lombok注解可以自动生成getter、setter以及构造函数等方法,你可以到Lombok官网了解更多详细信息。

1. RestController

@RestController注解用于定义RESTful Web服务,它提供JSON、XML以及自定义的相应信息,其使用语法如下:

@RestController
public class UserController{
    //TODO ...
}

2. RequestMapping

@RequestMapping注解用于定义访问REST Endpoint的请求路径。@RequestMapping的使用语法如下:

@RequestMapping("/users")
public ResponseEntity<Object> getUsers(){
    //TODO ...
}

注:@RequestMapping注解默认的请求方法GET.

在接下来的内容当中,我们将使用@RequestMapping的组合注解来定义REST Endpoint方法的映射路径:

3. RequestBody

@RequestBody注解用于定义请求正文内容类型。其语法如下:

public ResponseEntity<Object> createUser(@RequestBody User user){
    //TODO ...
}

4. PathVariable

@PathVariable注解用于定义请求路径中的动态变量,请求路径中的动态变量使用花括号“{}”包裹起来。语法如下:

@PutMapping("/users/{id}")
public ResponseEntity<Obejct> updateUser(@PathVariable("id") long id,@RequestBody User user){
    //TODO ...
}

5. GET API

默认的HTTP请求方法是GET,GET方法不需要任何的Request Body。你可以发送任何的请求参数和路径变量来定义一个动态的URL。接下来,我将演示如何定义一个HTTP GET请求方法,用于获取所有的用户信息。

package com.ramostear.restful.webservice.controller;

import com.ramostear.restful.webservice.model.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ramostear
 * @create-time 2019/3/6 0006-3:14
 * @modify by :
 * @since:
 */
@RestController
public class UserServiceController {

    private static Map<Long,User> userRepository = new HashMap<>();

    @PostConstruct
    public void initUserRepository(){
        User admin = new User();
        admin.setId(1).setName("admin");
        userRepository.put(admin.getId(),admin);

        User editor = new User();
        editor.setId(2).setName("editor");
        userRepository.put(editor.getId(),editor);
    }

   @GetMapping("/users")
    public ResponseEntity<Object> getUser(){
        return new ResponseEntity<>(userRepository.values(), HttpStatus.OK);
    }

}

在这里,我使用了一个Hash Map来扮演用户存储库的角色,定义的请求路径是/users

6. POST API

HTTP POST请求用于创建新的资源,此方法包含了Request Body。下面我将演示如何定义HTTP POST方法来创建用户信息,并存储到用户存储库中。

package com.ramostear.restful.webservice.controller;

import com.ramostear.restful.webservice.model.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ramostear
 * @create-time 2019/3/6 0006-3:14
 * @modify by :
 * @since:
 */
@RestController
public class UserServiceController {

    private static Map<Long,User> userRepository = new HashMap<>();

    @PostConstruct
    public void initUserRepository(){
        User admin = new User();
        admin.setId(1).setName("admin");
        userRepository.put(admin.getId(),admin);

        User editor = new User();
        editor.setId(2).setName("editor");
        userRepository.put(editor.getId(),editor);
    }


    @PostMapping("/users")
    public ResponseEntity<Object> createUser(@RequestBody User user){
        userRepository.put(user.getId(),user);
        return new ResponseEntity<>("User is created successfully",HttpStatus.CREATED);
    }
}

7. PUT API

HTTP PUT请求用于更新存储库中现有的资源,此方法包含请求正文。接下来我将给出相关示例来演示如何定义一个HTTP PUT请求方法来更新用户信息。

package com.ramostear.restful.webservice.controller;

import com.ramostear.restful.webservice.model.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ramostear
 * @create-time 2019/3/6 0006-3:14
 * @modify by :
 * @since:
 */
@RestController
public class UserServiceController {

    private static Map<Long,User> userRepository = new HashMap<>();

    @PostConstruct
    public void initUserRepository(){
        User admin = new User();
        admin.setId(1).setName("admin");
        userRepository.put(admin.getId(),admin);

        User editor = new User();
        editor.setId(2).setName("editor");
        userRepository.put(editor.getId(),editor);
    }

    @PutMapping("/users/{id}")
    public ResponseEntity<Object> updateUser(@PathVariable(name = "id") long id,@RequestBody User user){
        userRepository.remove(id);
        user.setId(id);
        userRepository.put(id,user);
        return new ResponseEntity<>("User is updated successfully",HttpStatus.OK);
    }

}

在此方法中,定义的请求路径是/users/{id} ,其中{id}是动态的路径变量,用来定义需要更新的用户ID。

8. DELETE API

HTTP DELETE请求用于删除存储库中现有的资源,此方法不包含任何请求正文。接下来我将给出相关示例来演示如何定义一个HTTP PUT请求方法来更新用户信息。

package com.ramostear.restful.webservice.controller;

import com.ramostear.restful.webservice.model.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ramostear
 * @create-time 2019/3/6 0006-3:14
 * @modify by :
 * @since:
 */
@RestController
public class UserServiceController {

    private static Map<Long,User> userRepository = new HashMap<>();

    @PostConstruct
    public void initUserRepository(){
        User admin = new User();
        admin.setId(1).setName("admin");
        userRepository.put(admin.getId(),admin);

        User editor = new User();
        editor.setId(2).setName("editor");
        userRepository.put(editor.getId(),editor);
    }


    @DeleteMapping("/users/{id}")
    public ResponseEntity<Object> delete(@PathVariable(name = "id") long id){
        userRepository.remove(id);
        return new ResponseEntity<>("User is deleted successfully",HttpStatus.OK);
    }

}

在此方法中,定义的请求路径是/users/{id} ,其中{id}是动态的路径变量,用来定义需要删除的用户ID。

9. 代码清单

9.1 Spring Boot应用程序主类 — RestfulWebserviceApplication.java

package com.ramostear.restful.webservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RestfulWebserviceApplication {

    public static void main(String[] args) {
        SpringApplication.run(RestfulWebserviceApplication.class, args);
    }

}

9.2 POJO类 — User.java

package com.ramostear.restful.webservice.model;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author ramostear
 * @create-time 2019/3/6 0006-3:12
 * @modify by :
 * @since:
 */
@Getter
@Setter
@NoArgsConstructor
public class User {
    private long id;
    private String name;

    public User setId(long id){
        this.id = id;
        return this;
    }

    public User setName(String name){
        this.name = name;
        return this;
    }
}

9.3 Rest Controller类 — UserServiceController.java

package com.ramostear.restful.webservice.controller;

import com.ramostear.restful.webservice.model.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ramostear
 * @create-time 2019/3/6 0006-3:14
 * @modify by :
 * @since:
 */
@RestController
public class UserServiceController {

    private static Map<Long,User> userRepository = new HashMap<>();

    @PostConstruct
    public void initUserRepository(){
        User admin = new User();
        admin.setId(1).setName("admin");
        userRepository.put(admin.getId(),admin);

        User editor = new User();
        editor.setId(2).setName("editor");
        userRepository.put(editor.getId(),editor);
    }

    @GetMapping("/users")
    public ResponseEntity<Object> getUser(){
        return new ResponseEntity<>(userRepository.values(), HttpStatus.OK);
    }

    @PostMapping("/users")
    public ResponseEntity<Object> createUser(@RequestBody User user){
        userRepository.put(user.getId(),user);
        return new ResponseEntity<>("User is created successfully",HttpStatus.CREATED);
    }

    @PutMapping("/users/{id}")
    public ResponseEntity<Object> updateUser(@PathVariable(name = "id") long id,@RequestBody User user){
        userRepository.remove(id);
        user.setId(id);
        userRepository.put(id,user);
        return new ResponseEntity<>("User is updated successfully",HttpStatus.OK);
    }

    @DeleteMapping("/users/{id}")
    public ResponseEntity<Object> delete(@PathVariable(name = "id") long id){
        userRepository.remove(id);
        return new ResponseEntity<>("User is deleted successfully",HttpStatus.OK);
    }

}

10. 测试

你可以选择命令行工具或者IDE来编译、打包并运行项目,这里我使用Intellij IDEA来运行项目,运行结果如下图所示:

接下来,我们将使用Postman应用程序来测试准备好的RESTful Web 服务接口:

  1. GET API : http://localhost:8080/users

  1. POST API : http://locahost:8080/users

  1. PUT API : http://locahost:8080/users/3

  1. DELETE API : http://localhost:8080/users/3

(转载本站文章请注明作者和出处:谭朝红-ramostear.com,未经允许请勿做任何商业用途)

发表评论