SpringBoot Restful Demo

来源:https://howtodoinjava.com/spring-boot2/rest-api-example/

获取

https://start.spring.io/

更新 build.gradle (maven 类似):

dependencies {
	...
	implementation 'org.springframework.boot:spring-boot-starter-web'
	...
}

Controlle

EmployeeController.java

package cn.org.yanwen.springbootemployeedemo.controller;
 
import java.net.URI;
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;;
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 cn.org.yanwen.springbootemployeedemo.dao.EmployeeDAO;
import cn.org.yanwen.springbootemployeedemo.model.Employee;
import cn.org.yanwen.springbootemployeedemo.model.Employees;
 
@RestController
@RequestMapping(path = "/employees")
public class EmployeeController
{
    @Autowired
    private EmployeeDAO employeeDao;
     
    @GetMapping(path="/", produces = "application/json")
    public Employees getEmployees()
    {
        return employeeDao.getAllEmployees();
    }
     
    @PostMapping(path= "/", consumes = "application/json", produces = "application/json")
    public ResponseEntity<Object> addEmployee(@RequestBody Employee employee)
    {
        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();
    }

    @PutMapping(path= "/{id}/", consumes = "application/json", produces = "application/json")
    public ResponseEntity<Object> updateEmployee(@PathVariable("id") int id, @RequestBody Employee employee)
    {
        List<Employee> employeeList = employeeDao.getAllEmployees().getEmployeeList();

        // No found
        if (id > employeeList.size()) return new ResponseEntity<>("Bad id", HttpStatus.BAD_REQUEST);

        // FIXME: get employee by id
        Employee oldEmployee = employeeList.get(id - 1);
        if (employee.getName() != null) oldEmployee.setName(employee.getName());
        if (employee.getAge() > 18) oldEmployee.setAge(employee.getAge());
        if (employee.getGender() != null) oldEmployee.setGender(employee.getGender());
         
        return new ResponseEntity<>(employee, HttpStatus.OK);
    }

    @DeleteMapping(path= "/{id}/", produces = "application/json")
    public ResponseEntity<Object> updateEmployee(@PathVariable("id") int id)
    {
        List<Employee> employeeList = employeeDao.getAllEmployees().getEmployeeList();

        // No found
        if (id > employeeList.size()) return new ResponseEntity<>("Bad id", HttpStatus.BAD_REQUEST);

        employeeList.remove(id - 1);
         
        return new ResponseEntity<>("Deleted", HttpStatus.OK);        
    }
}

Model

Employee.java

package cn.org.yanwen.springbootemployeedemo.model;
 
public class Employee {
 
    public Employee() {
 
    }
 
    public Employee(Integer id, String name, short age, String gender) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
  
    private Integer id;
    private String name;
    private short age;
    private String gender;
 
    // Getters and setters
    /**
     * @return the id
     */
    public Integer getId() {
      return id;
    }

    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
      this.id = id;
    }

    /**
     * @return the name
     */
    public String getName() {
      return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
      this.name = name;
    }

    /**
     * @return the age
     */
    public short getAge() {
      return age;
    }

    /**
     * @param age the age to set
     */
    public void setAge(short age) {
      this.age = age;
    }

    /**
     * @return the gender
     */
    public String getGender() {
      return gender;
    }

    /**
     * @param gender the gender to set
     */
    public void setGender(String gender) {
      this.gender = gender;
    }
 
    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name +
               ", age=" + String.valueOf(age) + ", gender=" + gender + "]";
    }
}

Employees.java

package cn.org.yanwen.springbootemployeedemo.model;
 
import java.util.ArrayList;
import java.util.List;
 
public class Employees
{
    private List<Employee> employeeList;
     
    public List<Employee> getEmployeeList() {
        if(employeeList == null) {
            employeeList = new ArrayList<>();
        }
        return employeeList;
    }
  
    public void setEmployeeList(List<Employee> employeeList) {
        this.employeeList = employeeList;
    }
}

FakeD

EmployeeDAO.java

package cn.org.yanwen.springbootemployeedemo.dao;
 
import org.springframework.stereotype.Repository;
 
import cn.org.yanwen.springbootemployeedemo.model.Employee;
import cn.org.yanwen.springbootemployeedemo.model.Employees;
 
@Repository
public class EmployeeDAO
{
    private static Employees list = new Employees();
     
    static
    {
        list.getEmployeeList().add(new Employee(1, "小明", (short)19, "男"));
        list.getEmployeeList().add(new Employee(2, "小红", (short)19, "男"));
        list.getEmployeeList().add(new Employee(3, "小智", (short)15, "女"));
        list.getEmployeeList().add(new Employee(4, "小刚", (short)16, "男"));
        list.getEmployeeList().add(new Employee(5, "小霞", (short)15, "女"));
    }
     
    public Employees getAllEmployees()
    {
        return list;
    }
     
    public void addEmployee(Employee employee) {
        list.getEmployeeList().add(employee);
    }
}

Main

package cn.org.yanwen.springbootemployeedemo;

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

@SpringBootApplication
public class SpringbootEmployeeDemoApplication {

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

作者: YanWen

Web 开发者

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s