The following controller serves a simple html page showing all persons in a repository.
Problem: I'm using validation constraints on the get-query. And if the query was invalid (in my example: lastname
parameter is missing), then spring automatically throws an exception as response to the browser.
But I'd still want to render the persons.html
page, just showing the errors indead of the repository content.
Question: how could I achieve this? Because if the validation fails, the method below is not even accessed.
@Controller
@RequestMapping("/persons")
public class PersonController {
@GetMapping //note: GET, not POST
public String persons(Model model, @Valid PersonForm form) {
//on the persons.html page I want to show validation errors
model.addAttribute("persons", dao.findAll());
return "persons";
}
}
public class PersonForm {
private String firstname;
@NotBlank
private String lastname;
}
Sidenote: I'm using thymeleaf
as templating engine. But the same question would apply to jsp
or jsf
engine.
Adding BindingResult
should solve this problem as @obecker pointed. I saw your remark, it works for GetMapping
and @PostMapping
as well.
Please check this out:
@SpringBootApplication
public class So45616063Application {
public static void main(String[] args) {
SpringApplication.run(So45616063Application.class, args);
}
public static class PersonForm {
private String firstname;
@NotBlank
private String lastname;
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
@Override
public String toString() {
return firstname + " " + lastname;
}
}
@RestController
@RequestMapping("/")
public static class Home {
@GetMapping
public void get(@Valid PersonForm form, BindingResult bindingResult) {
System.out.println(form);
System.out.println(bindingResult);
}
}
}
Call:
curl -XGET 'localhost:8080?firstname=f&lastname=l'
Will produce output:
f l
org.springframework.validation.BeanPropertyBindingResult: 0 errors
Call:
curl -XGET 'localhost:8080?firstname=f'
Will produce:
f null
org.springframework.validation.BeanPropertyBindingResult: 1 errors