开发者

Validation in Spring MVC

开发者 https://www.devze.com 2023-03-01 07:01 出处:网络
We are using Spring MVC 3.0 in our web application. We are also using the validation framework of Spring MVC.

We are using Spring MVC 3.0 in our web application. We are also using the validation framework of Spring MVC.

While doing validation we need to create our validators for each entity we need to validate. For example if I have a Person entity, I will validate it using following PersonValidator.

public class PersonValidator implements Validator {
/**
 * This Validator validates just Person instances
 */
public boolean supports(Class clazz) {
    return Person.class.equals(clazz);
}

public void validate(Object obj, Errors e) {
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "firstName", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "field.required");
}
}

My question is, is it possible to have different validations for same entities for different methods.

@RequestMapping(method = RequestMethod.POST)
public String add(@Valid Person person, BindingResult result) {
    if (result.hasErrors()) {
        return "person/new";
    }
    personService.addPerson(person);
    return "redirect:/persons";
}

@RequestMapping(method = RequestMethod.POST)
public String update(@Valid Person person, BindingResult result) {
    if (result.hasErrors()) {
        return "person/edit";
    }
    personService.updatePerson(person);
    return "redirect:/persons";
}

I want to validate first name, last name and age while adding a new person but while updating I don't want age to be mandatory.

This is just a random situation, it can b开发者_开发知识库e any entity and any property.

How do we handle such situations?

Thanks.


You could drop the @Valid annotation and instead inside the method set a flag on your model object for insert vs update and then call the Validator directly (you can inject them into the controller).

Then inside the validator you can choose which validations are required for your current scenario.

0

精彩评论

暂无评论...
验证码 换一张
取 消