【问题标题】:RequestMapping with POST and JSON in SpringMVC not running在 SpringMVC 中使用 POST 和 JSON 的 RequestMapping 未运行
【发布时间】:2016-08-30 01:20:55
【问题描述】:

这是我的控制器:

package com.hodor.booking.controller;

import com.audi.interview.booking.jpa.domain.Vehicle;
import com.audi.interview.booking.service.VehicleService;
import com.wordnik.swagger.annotations.Api;
import org.apache.commons.lang.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/v1/vehicles")
@Api(value = "vehicles", description = "Vehicle resource endpoint")
public class VehicleController {

    private static final Logger log = LoggerFactory.getLogger(VehicleController.class);

    @Autowired
    private VehicleService vehicleService;

    @RequestMapping(method = RequestMethod.GET)
    public List<Vehicle> index() {
        log.debug("Getting all vehicles");
        return vehicleService.findAll();
    }

    @RequestMapping(value= "/save",method = RequestMethod.POST, consumes="application/json")
        public void addVehicle(@RequestBody Car car, Vehicle vehicle) {
            log.debug("Inserting vehicle");
            Vehicle testVehicle1 = new Vehicle();
            testVehicle1.setLicensePlate("M-1234");
            testVehicle1.setModel("M5");
            testVehicle1.setColor("Grey");
            testVehicle1.setActive(true);
            testVehicle1.setVin("8765-4321");
            testVehicle1.setValidTill(DateUtils.addYears(new Date(), 1));
            vehicleService.saveVehicle(testVehicle1);
        }
    }
}

现在“@RequestBody”和“Car”无法解析。我是 Java 和 Spring 的新手,我在这里关注了文档:http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-uri-templates

如何使用 POST 请求中发送的 JSON 数据?

【问题讨论】:

  • RequestBody 和 Car 类没有导入。此外,方法之外的log.debug("Inserting vehicle"); 没有意义。另外,您期待汽车和车辆吗?

标签: java json spring spring-mvc


【解决方案1】:

你有这样的控制器方法签名:

public void addVehicle(@RequestBody Car car, Vehicle vehicle) {

}

我假设 - (车辆)几乎没有意义,因为你不能将两个 dto 传递给你的控制器方法 - 参考 - Spring MVC controller with multiple @RequestBody。如果是这样,那么您可能可以从您的方法签名中删除它。

然后,您可以将 Car 创建为 JSON 结构,并使用适合您的任何 REST 客户端将其传递给您的控制器。参考 - Using Postman to test REST persistence endpoints

【讨论】:

  • 是的,我只需要一件物品(车辆一件),谢谢!我也不得不像布鲁诺建议的那样import RequestBody
  • 很高兴它帮助了你!
猜你喜欢
  • 2012-10-24
  • 2015-02-10
  • 2023-03-30
  • 2023-03-25
  • 2018-12-27
  • 2016-03-09
  • 2021-06-12
  • 2017-05-09
  • 1970-01-01
相关资源
最近更新 更多