【发布时间】:2018-11-13 16:49:31
【问题描述】:
我正在使用 Spring Boot 和验证。当名称的值不存在时,将显示 Whitelabel 错误页面。我想将它传递给带有自定义错误(例如缺少名称)的索引页面。
控制器类是:
package com.springs.springs.com.springs.springs.controller;
import com.springs.springs.hibernate.Employee;
import com.springs.springs.hibernate.EmployeeServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import javax.validation.Valid;
import java.util.List;
@Controller
@Validated
public class URLController {
@Autowired
EmployeeServiceImpl empService;
@GetMapping({"/", "/index"})
public String index1(Model model){
model.addAttribute("employee",new Employee());
return "index";
}
@PostMapping("/result")
public String result( @ModelAttribute @Valid Employee employee, BindingResult bindingResult){
List<FieldError> errors = bindingResult.getFieldErrors();
for (FieldError error : errors ) {
System.out.println (error.getObjectName() + " - " +error.getDefaultMessage());
}
System.out.print(employee.getName()== null); //use a logger instead
if(bindingResult.hasErrors()){
return "index";
}
else {
empService.save(employee);
return "result"; //may want to return a different page name for clarity
}
}
}
【问题讨论】:
-
你如何验证你的 Employee 类?
-
我正在使用@notempty 注解进行验证
-
@NotEmpty没有考虑null介绍。您需要一个额外的@NotNull。还要从班级中删除@Validated,那里不需要它。 -
我收到错误 javax.validation.ConstraintViolationException: result.employee.name: must not be empty
-
它工作得很好,但我想在 html 中添加自定义错误我该怎么做
标签: java spring spring-mvc spring-boot