如何使用RestTemplate从客户端将表单数据发布到服务器?

时间:2020-07-29 09:16:15

标签: java json spring-boot jsp

对于客户端,我使用了tomcat 8080端口,对于服务器端,我使用了tomcat 8081端口。我只是尝试使用RestTemplate将Form数据发布到服务器端。有什么具体方法可以做到吗?

我试图做到这一点,

   { @RequestMapping(value="/addBook")
   public String addBook(Book book){
    
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    ResponseEntity<Book> response = restTemplate.postForEntity(
              "http://localhost:8081/api/addbook", book, Book.class);                
    System.out.println(response.getBody());
    return "Home";}

这是我的表格

        <h1>Form</h1>
        <form action="addBook">
            <input type="text" name="name"><br>
            <input type="text" name="author"><br>
             <input type="text" name="stock"><br>
             <input type="submit" ><br>
        </form>

这是我的Book课,

package com.example.libraryfrontend.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties(ignoreUnknown = true)
public class Book {
private String name;
private String author;
private Integer stock;

public String getName() {
    return name;
}

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

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public Integer getStock() {
    return stock;
}

public void setStock(Integer stock) {
    this.stock = stock;
}}

这是我遇到的错误,


> Error while extracting response for type [class com.example.libraryfrontend.entity.Book] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'Book': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Book': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false') at [Source: (PushbackInputStream); line: 1, column: 6]
org.springframework.web.client.RestClientException: Error while extracting response for type [class com.example.libraryfrontend.entity.Book] and content type [application/json;charset=UTF-8]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'Book': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'Book': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')...

有人可以帮我吗,或者有什么特殊的方法可以将表格数据发送到保存方?

0 个答案:

没有答案