I think I know where your question is headed. And since this question is the one that pop ups in google's search main results, I can give a plain answer on what the @Valid annotation does.
I'll present 3 scenarios on how I've used @Valid
Model:
public class Employee{
private String name;
@NotNull(message="cannot be null")
@Size(min=1, message="cannot be blank")
private String lastName;
//Getters and Setters for both fields.
//...
}
JSP:
...
<form:form action="processForm" modelAttribute="employee">
<form:input type="text" path="name"/>
<br>
<form:input type="text" path="lastName"/>
<form:errors path="lastName"/>
<input type="submit" value="Submit"/>
</form:form>
...
Controller for scenario 1:
@RequestMapping("processForm")
public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
return "employee-confirmation-page";
}
In this scenario, after submitting your form with an empty lastName field, you'll get an error page since you're applying validation rules but you're not handling it whatsoever.
Example of said error:
Exception page
Controller for scenario 2:
@RequestMapping("processForm")
public String processFormData(@Valid @ModelAttribute("employee") Employee employee,
BindingResult bindingResult){
return bindingResult.hasErrors() ? "employee-form" : "employee-confirmation-page";
}
In this scenario, you're passing all the results from that validation to the bindingResult, so it's up to you to decide what to do with the validation results of that form.
Controller for scenario 3:
@RequestMapping("processForm")
public String processFormData(@Valid @ModelAttribute("employee") Employee employee){
return "employee-confirmation-page";
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Map<String, String> invalidFormProcessor(MethodArgumentNotValidException ex){
//Your mapping of the errors...etc
}
In this scenario you're still not handling the errors like in the first scenario, but you pass that to another method that will take care of the exception that @Valid triggers when processing the form model. Check this see what to do with the mapping and all that.
To sum up: @Valid on its own with do nothing more that trigger the validation of validation JSR 303 annotated fields (@NotNull, @Email, @Size, etc...), you still need to specify a strategy of what to do with the results of said validation.
Hope I was able to clear something for people that might stumble with this.
ScriptFile
class has some constraints defined for the class data members like@NotNull
,@NotEmpty
, etc. and@Valid
instructs the framework (spring in our case) to check these constraints against the parameter supplied when someone calls your method. In this case, if the validation fails, the server responds with anHTTP 400 Bad Request
status code. – Lauraine