📜  如何使用Java Spring Boot创建REST API

📅  最后修改于: 2021-04-16 05:51:51             🧑  作者: Mango

代表性状态转移(REST)是一种软件体系结构样式,它定义了一组用于创建Web服务的约束。符合REST体系结构样式的Web服务(称为RESTful Web服务)在Internet上的计算机系统之间提供互操作性。 RESTful Web服务允许请求系统通过使用统一且预定义的无状态操作集来访问和操纵Web资源的文本表示。其他类型的Web服务(例如SOAP Web服务)公开其自己的任意操作集。

在本文中,我们将了解如何使用spring boot创建rest API。

Spring被广泛用于创建可扩展的应用程序。对于Web应用程序,Spring提供了Spring MVC,它是Spring广泛使用的模块,用于创建可伸缩的Web应用程序。但是,春季项目的主要缺点是配置确实很耗时,并且对于新开发人员而言可能有些不知所措。解决方案是Spring Boot。 Spring Boot建立在Spring的顶部,并包含spring的所有功能。在本文中,我们将创建一个REST API,以将员工添加到员工列表中并获取员工列表。为此,我们首先必须在任何一个IDE中创建一个简单的Spring Boot项目,然后执行以下步骤:

  1. 最初,我们需要定义员工实体。因此,定义了以下员工类别:
    package com.example.demo;
      
    // Creating an entity Employee
    public class Employee {
      
        public Employee() {}
      
        // Parameterized Constructor
        // to assign the values
        // to the properties of
        // the entity
         public Employee(
            Integer id, String firstName,
            String lastName, String email)
        {
      
            super();
      
            this.id = id;
      
            this.firstName = firstName;
      
            this.lastName = lastName;
      
            this.email = email;
      
               
        }
      
           private Integer id;
      
           private String firstName;
      
           private String lastName;
      
           private String email;
      
        // Overriding the toString method
        // to find all the values
        @Override
       public String toString()
        {
      
            return "Employee [id="
                + id + ", firstName="
                + firstName + ", lastName="
                + lastName + ", email="
                + email + "]";
      
               
        }
      
        // Getters and setters of
        // the properties
        public Integer getId()
        {
      
             return id;
        }
      
        public void setId(Integer id)
        {
      
             this.id = id;
        }
      
        public String getFirstName()
        {
      
             return firstName;
        }
      
        public void setFirstName(
            String firstName)
        {
      
             this.firstName = firstName;
        }
      
        public String getLastName()
        {
      
             return lastName;
        }
      
        public void setLastName(
            String lastName)
        {
      
             this.lastName = lastName;
        }
      
        public String getEmail()
        {
      
             return email;
        }
      
        public void setEmail(String email)
        {
      
             this.email = email;
        }
    }
    
  2. 现在,我们需要创建一个存储类来存储所有员工的列表:
    package com.example.demo;
      
    import java.util.ArrayList;
    import java.util.List;
      
    // Class to store the list of
    // all the employees in an
    // Array List
    public class Employees {
      
        private List employeeList;
      
        // Method to return the list
        // of employees
        public List getEmployeeList()
        {
      
            if (employeeList == null) {
      
                employeeList
                    = new ArrayList<>();
      
                       
            }
      
            return employeeList;
      
               
        }
      
        public void
        setEmployeeList(
            List employeeList)
        {
            this.employeeList
                = employeeList;
        }
    }
    
  3. 到现在为止,我们已经定义了实体employee并创建了一个存储类。现在,我们需要访问员工。因此,我们从创建存储类的对象的位置创建一个类来存储员工:
    package com.example.demo;
      
    import org.springframework
        .stereotype
        .Repository;
      
    // Importing the employees class to
    // use the defined properties
    // in this class
    import com.example.demo.Employees;
      
    @Repository
      
    // Class to create a list
    // of employees
    public class EmployeeDAO {
      
        private static Employees list
            = new Employees();
      
        // This static block is executed
        // before executing the main
        // block
        static
        {
      
            // Creating a few employees
            // and adding them to the list
            list.getEmployeeList().add(
                new Employee(
                    1,
                    "Prem",
                    "Tiwari",
                    "chapradreams@gmail.com"));
      
            list.getEmployeeList().add(
                new Employee(
                    2, "Vikash",
                    "Kumar",
                    "abc@gmail.com"));
      
            list.getEmployeeList().add(
                new Employee(
                    3, "Ritesh",
                    "Ojha",
                    "asdjf@gmail.com"));
      
               
        }
      
        // Method to return the list
        public Employees getAllEmployees()
        {
      
            return list;
        }
      
           
            // Method to add an employee
            // to the employees list
            public void
            addEmployee(Employee employee)
        {
            list.getEmployeeList()
                .add(employee);
               
        }
    }
    
  4. 最后,我们需要创建一个控制器类,它是REST API的实际实现。根据REST规则,数据库中的每个新条目都必须由POST方法调用,并且来自数据库的所有请求都必须使用GET方法来调用。以下代码中实现了相同的方法:
    package com.example.demo;
      
    import java.net.URI;
    import org.springframework.beans
        .factory.annotation.Autowired;
    import org.springframework.http
        .ResponseEntity;
    import org.springframework.web.bind
        .annotation.GetMapping;
    import org.springframework.web.bind
        .annotation.PostMapping;
    import org.springframework.web.bind
        .annotation.RequestBody;
    import org.springframework.web.bind
        .annotation.RequestMapping;
    import org.springframework.web.bind
        .annotation.RestController;
    import org.springframework.web.servlet
        .support.ServletUriComponentsBuilder;
      
    // Import the above-defined classes
    // to use the properties of those
    // classes
    import com.example.demo.Employees;
    import com.example.demo.EmployeeDAO;
    import com.example.demo.Employee;
      
    // Creating the REST controller
    @RestController
    @RequestMapping(path = "/employees")
    public class EmployeeController {
      
        @Autowired
       private EmployeeDAO employeeDao;
           
            // Implementing a GET method
            // to get the list of all
            // the employees
       @GetMapping(
            path = "/",
            produces = "application/json")
      
        public Employees getEmployees()
        {
      
            return employeeDao
                .getAllEmployees();
        }
      
           
            // Create a POST method
            // to add an employee
            // to the list
       @PostMapping(
            path = "/",
            consumes = "application/json",
            produces = "application/json")
      
        public ResponseEntity addEmployee(
            @RequestBody Employee employee)
        {
      
            // Creating an ID of an employee
            // from the number of employees
            Integer id
                = employeeDao
                      .getAllEmployees()
                      .getEmployeeList()
                      .size()
                  + 1;
      
            employee.setId(id);
      
            employeeDao
                .addEmployee(employee);
      
            URI location
                = ServletUriComponentsBuilder
                      .fromCurrentRequest()
                      .path("/{id}")
                      .buildAndExpand(
                          employee.getId())
                      .toUri();
      
                   return ResponseEntity
                .created(location)
                .build();
        }
    }
    
    
    
    
    
  5. 在项目中实现所有类之后,请以Spring Boot App的身份运行该项目。服务器开始运行后,我们可以通过浏览器或邮递员发送请求。我们可以通过进入以下URL来访问正在运行的应用程序:
    http://localhost:8080/employees/
    
  6. 输出:以下是运行上述项目时生成的输出:

    1. 执行GET请求时:
    2. 执行POST请求时:
    3. 在执行POST请求后再次点击GET请求: