提问者:小点点

在springboot 2.3.1版本中,服务器端验证似乎不起作用


我有一个POJO类和它的API方法。 我想验证用户字段输入,但它似乎不工作。 我在POJO类中使用了@Size()注释,但它没有工作。 下面是我的逻辑结构的片段。

POJO类

@Entity
public class Address {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long addressId;

    @NotNull
    @Size(min=10, max=100, message="Please enter between {min}-{max} characters")
    private String addressLine;

API类方法

@PostMapping(value="/add", produces = MediaType.APPLICATION_JSON_VALUE, consumes=MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String addAddress( @RequestBody @Valid Address address, BindingResult result)
    {
        if(result.hasErrors()) {
            return ErrorUtils.customErrors(result.getAllErrors());
        } else {
            return addressService.addAddress(address);
        }
    }

我正在为addAddress(/add)方法创建JSON请求,并在UI表单中提示错误。 我的JSON响应处理程序位于jquery验证器中,如下所示。

function saveRequestedData(frm, data, type) {
    $.ajax({
        contentType:"application/json; charset=utf-8",
        type:frm.attr("method"),
        url:frm.attr("action"),
        dataType:'json',
        data:JSON.stringify(data),
        success:function(data) {
            if(data.status == "success") {
            alert(data.message);
            toastr.success(data.message, data.title, {
                closeButton:true
            });
            fetchList(type);
            }
            else {
                toastr.error(data.message, data.title, {
                    allowHtml:true,
                    closeButton:true
                });
            }
        }
    });
}   

似乎只有@NotNull能起作用,而@Size和@Valid Annotation不能起作用。 根据spring boot发布说明,从2.3.0版开始,spring boot Web和WebFlux启动程序不再依赖于验证启动程序,因此我在pom.xml中手动添加了spring-boot-starter-validation。 但似乎什么都不管用。


共1个答案

匿名用户

您可以使用下面的代码作为参考。

@Validated
@RestController
public AddressController{

@Autowired
private AddressService addressService;

@PostMapping(value="/add", produces = MediaType.APPLICATION_JSON_VALUE, consumes=MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String addAddress( @RequestBody @Valid Address address, BindingResult result){
        if(result.hasErrors()) {
            return ErrorUtils.customErrors(result.getAllErrors());
        } else {
            return addressService.addAddress(address);
        }
    }
 }