这是我的控制器:
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);
}
}
}
现在&#34; @RequestBody&#34;和&#34; Car&#34;无法解决。我是Java和Spring的新手,我在这里遵循了文档:http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-uri-templates
如何使用POST请求中发送的JSON数据?
答案 0 :(得分:1)
你有这样的控制器方法签名:
public void addVehicle(@RequestBody Car car, Vehicle vehicle) {
}
我假设 - (车辆车辆)几乎没有意义,因为你无法将两个dt传递给你的控制器方法 - 参考 - Spring MVC controller with multiple @RequestBody。如果是这种情况,那么您可以从方法签名中删除它。
然后,您可以将Car创建为JSON结构,并使用适合您的任何REST客户端将其传递给您的控制器。参考 - Using Postman to test REST persistence endpoints