javax.validation.Valid的@Vaild不起作用。没有异常发生

时间:2019-05-24 20:32:38

标签: spring bean-validation spring-validator

我使用@Valid注释,但不起作用。也不例外。  我添加了所有需要的Maven存储库,但resuls相同。

这是我的POJO类(Offer.java):

package com.geno.springmvctut.dao;

import javax.validation.constraints.Size;

public class Offer {

private int id;

@Size(min = 5, max = 100, message = "@Valid works!")
private String name;

private String email;
private String text;

public Offer() { }

public Offer(String name, String email, String text) {
    this.name = name;
    this.email = email;
    this.text = text;
}

public Offer(int id, String name, String email, String text) {
    this.id = id;
    this.name = name;
    this.email = email;
    this.text = text;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getText() {
    return text;
}

public void setText(String text) {
    this.text = text;
}


}

和OffersController.java:

package com.geno.springmvctut.controller;

import com.geno.springmvctut.dao.Offer;
import com.geno.springmvctut.service.OffersService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import java.util.List;


@Controller
@Component
public class OffersController {

private OffersService offersService;

public OffersService getOffersService() {
    return offersService;
}

@Autowired
public void setOffersService(OffersService offersService) {
    this.offersService = offersService;
}

@RequestMapping("/createOffer")
public String createOffer(){
    return "createOffer";
}

@RequestMapping(value = "/doCreate", method = RequestMethod.POST)
public String doCreate(Model model, @Valid Offer offer, BindingResult result){

    if(result.hasErrors()){

        System.out.println("Validation failed");
        List<ObjectError> errors = result.getAllErrors();

        for (ObjectError error : errors){
            System.out.println(error);
        }
    }
    else{
        System.out.println("Successful validation");
    }
    return "offerCreated";
}
}
该代码的

语法正确,但在逻辑上不起作用。结果始终是

  

成功验证

无论我做什么...所以有人知道如何解决吗?谁能帮我? 谢谢。

0 个答案:

没有答案