我正在使用弹簧启动和验证。当名称的值不存在时,将显示 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
}
}
}