1. 程式人生 > >常規的利用Curl傳送json資料到後臺SpringBoot+MongoDB測試CRUD

常規的利用Curl傳送json資料到後臺SpringBoot+MongoDB測試CRUD

web後端的開發涉及很多很多技術,要相互配合好需要不斷的練習。本文要做的事情是實現一個伺服器端程式,運用SpringBoot技術,結合MongoDB資料庫。然後用剛學的curl命令傳送json資料來測試資料庫的CRUD功能。

首先是新建一個工程並建立pom檔案

<?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> <groupId>com.hunter</groupId> <artifactId>SpringBootMongo</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging>
<name>SpringBootMongo</name> <description>Demo project for Spring Boot</description> <!-- lookup parent from repository --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId
>
<version>1.1.6.RELEASE</version> <relativePath/> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-ws</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <start-class>com.hunter.Application</start-class> <java.version>1.7</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

maven會幫助開發者進行依賴管理。然後開發者就可以專注於功能模組的開發。

在src/main/java/下新建目錄com/hunter/,放入java檔案

Application.java

package com.hunter;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
    }
}

在com/hunter/employee目錄下面新建三個檔案
Employee.java

package com.hunter.employee;

import org.springframework.data.annotation.Id;

public class Employee {

    @Id
    private String id;

    private String name;
    private String title;

    public Employee(){};
    public Employee(String id, String name, String title){
        super();
        this.id=id;
        this.name=name;
        this.title=title;
    }

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

EmployeeController.java

package com.hunter.employee;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    EmployeeRepository repository;

    //create
    @RequestMapping(value = "", method = RequestMethod.PUT)
    public Employee createEmployee(@RequestBody Employee employee){
        return repository.save(employee);
    }

    //read
    @RequestMapping(value = "",method = RequestMethod.GET)
    public List<Employee> readEmployee(@RequestParam(required = false) String name,
                                       @RequestParam(required = false) String title) {
        if (name != null) {
            return repository.findByName(name);
        } else if (title != null) {
            return repository.findByTitle(title);
        } else {
            return repository.findAll();
        }
    }

    //update
    @RequestMapping(value = "/{id}", method = RequestMethod.POST)
    public Employee updateEmployee(@PathVariable String id, @RequestBody Employee employee){

        Employee em = repository.findById(id);
        Employee newEm = new Employee(em.getId(),employee.getName(),employee.getTitle());
        return repository.save(newEm);
    }

    //delete
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public void deleteEmployee(@PathVariable String id) {

        repository.delete(id);
    }
}

EmployeeRepository.java

package com.hunter.employee;

import org.springframework.data.mongodb.repository.MongoRepository;
import java.util.List;


public interface EmployeeRepository extends MongoRepository<Employee, String> {
    public List<Employee> findByName(String name);
    public List<Employee> findByTitle(String title);

    public Employee findById(String id);
}

構建工程進行測試

一般我們都傾向於用ide去搭建工程以及測試,畢竟命令列做不到斷點檢查。
在終端cd到pom所在目錄,可以直接用maven命令建立IDEA的工程
$ mvn idea:idea
然後就可以使用IntellijIDEA工作了。


接下來測試這個程式:
1. 開啟MongoDB的介面。
$ mongod —dbpath ~/MongoDBPath
2. 執行程式
3. 終端輸入
$ curl http://localhost:8080/employee
會返回空資料
[]
因為現在資料庫什麼都沒有。

$ curl -v -i -H "Accept: application/json" -H "Content-Type: application/json" -X PUT -d '{"id":1,"name":"charlie","title":"here"}' http://localhost:8080/employee/

傳送一個json資料包到伺服器,如果執行正常,資料庫已經寫入一條記錄了

$ curl -v -i -X GET http://localhost:8080/employee
此時再次查詢,就已經會返回一條關於charlie的資料了

$ curl -v -i -X POST -H "Accept: application/json" -H "Content-Type: application/json" -d '{"id":1,"name":"jane","title":"leader"}' http://localhost:8080/employee/1

$ curl -v -i -X DELETE http://localhost:8080/employee/1
刪除id為1的資料,也就是charlie沒了。

強調,千萬要注意引號的正確性。。。有時候,由於文字編輯工具的原因,引號會有誤,也有可能造成curl命令錯誤。例如印象筆記就會把雙引號變成另一種型別。。坑。。