Darshan.R
Darshan.R

Reputation: 63

Validation in Spring MVC

how to get the request object in the validator class, as i need to validate the contents ie the parameters present in the request object.

Upvotes: 6

Views: 9947

Answers (5)

monkeyk
monkeyk

Reputation: 1

I also have the same issue when i use spring validator validate captcha. In the validator implementor, i want to get the correct-captcha from HttpSession(from HttpServletRequest get HttpSession).

Not found any good codes for get it in validator, so bad!!!

There are some compromise proposal as follow:

  1. In the binding form DTO add an additional field (call: correctCaptcha), in the Controller method set the field value from HttpSession , then you can validate in the validator

    public class UserRegisterDto {
        private String correctCaptcha;
        //getter,setter
    }
    
  2. Add the HttpServletRequest reference in the binding form DTO, then can use it in the validator.

    public class UserRegisterDto {
        private HttpServletRequest request;
        //getter ,setter
    }
    
    @RequestMapping(value = "register.hb", method = RequestMethod.POST)
    public String submitRegister(@ModelAttribute("formDto") @Valid UserRegisterDto formDto, HttpServletRequest request,BindingResult result) {
        formDto.setRequest(request);
        if (result.hasErrors()) {
            return "user_register";
        }
    }
    

Upvotes: 0

Smith
Smith

Reputation: 1469

You could easily add another method with HttpServletRequest parameter.

 public void validateReq(Object target, Errors errors,HttpServletRequest request) {

       // do your validation here
}

Note that you are not overriding a method here

Upvotes: 0

Ralph
Ralph

Reputation: 120761

You have two choices:

  • JSR 303 (Bean Validation) Validators
  • Spring Validators

For JSR 303 you need Spring 3.0 and must annotate your Model class with JSR 303 Annotations, and write an @Valid in front of you parameter in the Web Controller Handler Method. (like Willie Wheeler show in his answer). Additionaly you must enable this functionality in the configuration:

<!-- JSR-303 support will be detected on classpath and enabled automatically -->
<mvc:annotation-driven/>

For Spring Validators, you need to write your Validator (see Jigar Joshi's answer) that implements the org.springframework.validation.Validator Interface. The you must register your Validator in the Controller. In Spring 3.0 you can do this in a @InitBinder annotated Method, by using WebDataBinder.setValidator (setValidator it is a method of the super class DataBinder)

Example (from the spring docu)
@Controller
public class MyController {

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new FooValidator());
    }

    @RequestMapping("/foo", method=RequestMethod.POST)
    public void processFoo(@Valid Foo foo) { ... }
}

For more details, have a look at the Spring reference, Chapter 5.7.4 Spring MVC 3 Validation.

BTW: in Spring 2 there was someting like a setValidator property in the SimpleFormController.

Upvotes: 11

Jigar Joshi
Jigar Joshi

Reputation: 240860

Using simple validator (your custom validator) You don't need request object to get param there in Validator. You can directly have it from.

For example : This will check field from request with name name and age

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.rejectIfEmpty(e, "name", "name.empty");
        Person p = (Person) obj;
        if (p.getAge() < 0) {
            e.rejectValue("age", "negativevalue");
        } else if (p.getAge() > 110) {
            e.rejectValue("age", "too.darn.old");
        }
    }
}

Also See

Upvotes: 4

user41871
user41871

Reputation:

Not 100% sure I'm following your question correctly, but with Spring MVC, you pass the object into the method and annotate it (at least with Spring 3), like so:

@RequestMethod(value = "/accounts/new", method = RequestMethod.POST)
public String postAccount(@ModelAttribute @Valid Account account, BindingResult result) {
    if (result.hasErrors()) {
        return "accounts/accountForm";
    }

    accountDao.save(account);
}

The relevant annotation here is @Valid, which is part of JSR-303. Include the BindingResult param as well so you have a way to check for errors, as illustrated above.

Upvotes: 1

Related Questions