提问者:小点点

无法使用JPararePository解析SpringMVC中的ResponseEntity


这是我的控制器:

package com.hodor.booking.controller;

import com.hodor.booking.jpa.domain.Vehicle;
import com.hodor.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.*;

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")

    @ResponseBody
    public Vehicle setVehicle(@RequestBody Vehicle vehicle) {
        log.debug("Inserting vehicle");

        if (vehicle.getLicensePlate() == null){
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

        return vehicleService.saveVehicle(vehicle);
    }
}

在上面的If-Guard中,我想要实现的是,如果vehicle对象没有LicensePlate成员,则发回相应的HTTP状态头冲突或其他东西。

我来自一个节点和Express后台,我被用来设置我的头,发送响应和完成它。然而,在这种情况下(JPA)它似乎不起作用。有什么想法吗?


共2个答案

匿名用户

另一种选择是利用spring的验证支持对POJO进行声明式添加验证。基本上,您可以向vehicle类添加注释,如:

public class Vehicle {
    @NotNull
    private LicensePlate licensePlate;

    // getters, setters
}

并将@valid注释添加到controller方法:

@ResponseBody
public Vehicle setVehicle(@RequestBody @Valid Vehicle vehicle) {
    log.debug("Inserting vehicle");
    return vehicleService.saveVehicle(vehicle);
}

如果验证失败,spring将返回400响应。

确保在类路径上有JSR-303/JSR-349bean验证实现,比如Hibernate验证器(它可以在没有Hibernate的ORM支持的情况下使用)。

更多信息见《spring参考文件》的验证一章。

匿名用户

你使用的是什么版本的spring MVC?在另一篇文章中,如何在返回字符串的spring MVC@ResponseBody方法中使用HTTP 400错误进行响应?。它说明spring MVC4.1和更高版本使用了不同的语法。