使用 Spring 个 Rest 控制器

Using Spring Rest Controllers

我在尝试 post 我的数据库中的某些内容时使用 @RestController 遇到了一些问题。我的目标是尝试获得如下所示的结果:

{   

    "postID": "5",

    "content": "testcontent",

    "time": "13.00",

    "gender": "Man"

}

而 post 在 "localhost:port/posts" 中执行类似的操作(使用 Postman):

{  

    "content": "testcontent",

    "time": "13.00",

    "gender": "Man"
}

Post.java

package bananabackend;

public class Post {

private final long id;
private String content;
private String time;
private String gender;  


// Constructor

public Post(long id, String content, String time, String gender) {
    this.id = id;
    this.content = content;
    this.time = time;
    this.gender = gender;
}

// Getters

public String getContent() {
    return content;
}

public long getId() {
    return id;
}

public String getTime() {
    return time;
}

public String getGender() {
    return gender;
}

PostController.java

package bananabackend;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import bananabackend.Post;


@RestController
public class PostController {    

private final AtomicLong counter = new AtomicLong();

@RequestMapping(value="/posts", method = RequestMethod.POST)
public Post postInsert(@RequestParam String content, @RequestParam    String time, @RequestParam String gender) {
    return new Post(counter.incrementAndGet(), content, time, gender);
    }
}

PostRepository.java

package bananabackend;

import java.util.List;


import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;

@RepositoryRestResource(collectionResourceRel = "posts", path = "posts")
public interface PostRepository extends MongoRepository<Post, String> {


List<Post> findPostByContent(@Param("content") String content);

}

我收到这个错误:

{

    "timestamp": 1460717792270,

    "status": 400,

    "error": "Bad Request",

    "exception":  
    "org.springframework.web.bind.MissingServletRequestParameterException",

    "message": "Required String parameter 'content' is not present",

    "path": "/posts"
}

我想为每个 post 设置一个 ID,但它似乎不起作用。我正在尝试构建类似于本指南的代码:

https://spring.io/guides/gs/rest-service/

您正在尝试获取在请求正文中发送的请求参数。请求参数就是你在URL.

中发送的参数

而不是使用 @RequestParam ... 使用 @RequestBody Post post 例如:

@RequestMapping(value="/posts", method = RequestMethod.POST)
public Post postInsert(@RequestBody Post post) {
    return new Post(counter.incrementAndGet(), post.getContent(), post.getTime(), post.getGender());
}

此外,您还需要 Post class 中的默认构造函数。