Thymeleaf Spring Validation不显示

时间:2019-06-20 14:23:46

标签: spring-boot thymeleaf spring-validator

我正在尝试从Controller获取HTML上的错误消息,但我看不到该消息。

我打印了$ {#fields.hasErrors('name')},发现它给了我错误

我调试了代码,发现有错误

com.gurnah.controller.ProductController:产品大小必须在2到150之间

@RequestMapping(path = "/product")
public class ProductController {
    private static final Logger logger = LoggerFactory.getLogger(ProductController.class);
    @Autowired
    private ProductRepo productRepo;
        .....

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String save(@ModelAttribute @Valid Product product, Errors errors, Model model) {

        if (errors.hasErrors()) {
            model.addAttribute("product", new Product());
//          logger.info("Error Message " + bindingResult.getGlobalErrorCount());
            logger.info("Error Message " + errors.getFieldErrorCount());
            List<ObjectError> err = errors.getAllErrors();
            for (ObjectError e : err) {
                logger.info(e.getObjectName()  + e.getDefaultMessage());
            }
//          logger.info("Error Message " + bindingResult.getErrorCount());
            return "/prod/create";
        } else {
            productRepo.save(product);
            return "redirect:/product/list";
        }

    }

我的Pojo

@Entity
public class Product {

    @Id
    @Column(name = "ProdID", updatable = false, nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_generator")
    @SequenceGenerator(name="product_generator", sequenceName = "zseq_product", allocationSize=1)
    private int ProdID;

    @NotNull(message = "Field Product cannot be empty")
//  @NotEmpty(message = "Field Product cannot be empty")
    @Size(min = 2, max = 150)
    private String name;

    private String prodDesc;

我的HTML

<form th:object="${product}" th:action="@{/product/save}" method="post">
.....
    <div class="form-group" 
               th:classappend="${#fields.hasErrors('name')}? 'has-error'">
    <label th:for="name" class="col-form-label">Product Name:</label> 
    <input type="text" class="form-control" th:field="*{name}" />
    <span th:if="${#fields.hasErrors('name')}" 
          th:errors="*{name}" 
          th:class="help-block">Title Errors</span>
    </div>

0 个答案:

没有答案