簡體   English   中英

使用Spring Rest控制器

[英]Using Spring Rest Controllers

嘗試在數據庫中發布某些內容時,使用@RestController遇到了一些麻煩。 我的目標是嘗試獲得如下所示的結果:

{   

    "postID": "5",

    "content": "testcontent",

    "time": "13.00",

    "gender": "Man"

}

在“ 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"
}

我想為發布的每個帖子設置一個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類中的默認構造函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM