简体   繁体   English

@RequestBody 空值(Spring boot 和 Vue JS)

[英]@RequestBody null values (Spring boot and Vue JS)

Hello everyone (first post here !)大家好(第一次在这里发帖!)

I have an issue with a simple web application that I'm developping.我正在开发的一个简单的 Web 应用程序有问题。

I created a rest service (POST) with spring boot, but when I try this service from the front end I cannot retrieve any values on my @RequestBody.我用 spring boot 创建了一个休息服务 (POST),但是当我从前端尝试这个服务时,我无法在我的 @RequestBody 上检索任何值。

The javascript that's calling the controller is the following调用控制器的 javascript 如下

bookStore.html书店.html

                //Submit shopping cart to the backend to be saved
            checkout : function() {
                //Place holder for the POST Request
                this.$http.post('/createOrder', {
                    'shopCart' : {'basket' : this.shoppingCart}
                });
                //END Post request
            }

OrderController.java订单控制器.java

    @RequestMapping(value = "/createOrder",
        method = RequestMethod.POST)
public String createOrder(@RequestBody ShoppingCart shopCart, Model model) {
    Order order = new Order();
    Float totalPrice = 0f;
    order.setCreationDate(new Date());
    List<String> bookIdList = new ArrayList<>();
    for (Book book : shopCart.getBasket()) {
        bookIdList.add(book.getId());
        totalPrice = totalPrice + book.getPrice();
    }
    order.setItemList(bookIdList);
    order.setTotalOrder(totalPrice);
    orderRepo.save(order);
    List<Order> orderList = orderRepo.findAll();
    model.addAttribute("addedOrder", order);
    model.addAttribute("orderList", orderList);
    return "orderList";
}

ShoppingCart.java购物车.java

public class ShoppingCart {
private List<Book> basket;

public List<Book> getBasket() {
    return basket;
}

public void setBasket(List<Book> basket) {
    this.basket = basket;
}

@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("BookList [shoppingCart=");
    builder.append(basket);
    builder.append("]");
    return builder.toString();
}

} }

Note that shoppingCart is defined as an array of object in VUE js.请注意,shoppingCart 在 VUE js 中被定义为一个对象数组。 When I set this value it looks like this当我设置这个值时,它看起来像这样

{"shoppingCart":[{"id":"5add48ed217c1823543f0610","name":"War and Peace","author":"Leo Tolstoy","price":25},{"id":"5add48ed217c1823543f060f","name":"Madame Bovary","author":"Gustave Flaubert","price":20}]}

The issue is that shopCart is always null.问题是 shopCart 始终为空。 Am I missing something ?我错过了什么吗? it seems to be a basic thing to do and it works fine with the RequestParam controller that I've done before这似乎是一件基本的事情,它与我以前做过的 RequestParam 控制器一起工作得很好

Just to give an update.只是为了提供更新。 I found a workaround on this.我找到了解决方法。

Instead of directly using the ShoppingCart object I'll pass a json String to the variable and use ObjectMapper to create my object.我不会直接使用 ShoppingCart 对象,而是将一个 json 字符串传递给变量并使用 ObjectMapper 创建我的对象。

    @RequestMapping(path = "/createOrderList", method = RequestMethod.POST)
public String createOrderList(@RequestBody String shopCart, Model model)
        throws JsonParseException, JsonMappingException, IOException {
    Order order = new Order();
    Float totalPrice = 0f;
    order.setCreationDate(new Date());
    List<String> bookIdList = new ArrayList<>();
    ObjectMapper mapper = new ObjectMapper();
    ShoppingCart shpCart = mapper.readValue(shopCart, ShoppingCart.class);
    for (Book book : shpCart.getBookList()) {
        bookIdList.add(book.getId());
        totalPrice = totalPrice + book.getPrice();
    }
    order.setItemList(bookIdList);
    order.setTotalOrder(totalPrice);
    orderRepo.save(order);
    model.addAttribute("orderList", orderRepo.findAll());
    model.addAttribute("bookList", bookRepo.findAll());
    model.addAttribute("addedOrder", order);
    return "bookStore";
}

On the fron end side the Javascript looks like that在前端,Javascript 看起来像这样

this.$http.post('/createOrderList', JSON.stringify({
            'bookList': this.shoppingCart
        }))

This works as expected这按预期工作

This is an old post, but this info might help someone.这是一篇旧帖子,但此信息可能对某人有所帮助。 The way it is done on the top with @RequestBody and mapping to the model should work with a @RestController, with the small exception that the response should not be a string but probably the model with updated values.在顶部使用@RequestBody 完成并映射到模型的方式应该与@RestController 一起使用,但有一个小例外,即响应不应是字符串,而可能是具有更新值的模型。

In my case, I had an issue where the @RequestBody was incorrectly imported from SwaggerUI instead of " import org.springframework.web.bind.annotation.RequestBody;"就我而言,我遇到了一个问题,即从 SwaggerUI 错误地导入了 @RequestBody,而不是“ import org.springframework.web.bind.annotation.RequestBody;” which gave me a hard to catch bug.这给了我一个难以捕捉的错误。

As long as the pojo is serializable it should have worked.只要 pojo 是可序列化的,它就应该可以工作。 Additionally, if you are sending the JSON from manually built strings, make sure that the naming conventions are followed on the casing of the properties.此外,如果您从手动构建的字符串发送 JSON,请确保在属性的大小写上遵循命名约定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM