Forbidden field check

I am new to spring. I am currently creating a news manager form.

Here is an example of my news object:

class News { @NotNull long id; @NotNull long idAuthor; @Size(max=255) String content; } 

As you can see, I am using JSR303 annotation check with Spring. I want to confirm my "news editing form".

 @RequestMapping( value = "/edit" , method = RequestMethod.POST) public String editAction(@Valid @ModelAttribute News news, BindingResult result) { System.err.println(result.hasErrors()); ... return "editView"; } 

Define a valid field:

 //initBinder function : binder.setAllowedFields("content"); 

Well, I'm trying to check only the "content" field (a valid field is set on my insert) ... But spring always checks the entire field defined on my entity (so that "id" and "idAuthor" return an error)

How can I check a valid field (set in the initBinder function)?

+4
source share
1 answer

There are no good ways to do this.

JSR-303 offers two approaches for spot checking:

  • You can verify certain properties by calling validator.validateProperty(news, "content")
  • You can define validation groups:

     @Size(max=255, groups = {Default.class, WebValidation.class}) String content; 

    And confirm the specified group: validator.validate(news, WebValidation.class);

None of these approaches are directly supported by Spring MVC. You can authorize the JSR-303 Validator and call these methods manually, but they return Set<ConstraintViolation<?>> , and the code for placing these ConstraintViolation in the BindingResult is located deep inside the internal Spring elements and cannot be easily reused (see SpringValidatorAdapter ) .

There is a request for the support function for verification groups in the style of @Valid Valid - style ( SPR-6373 ) with version 3.1 fix.

Thus, in addition to creating a special DTO class, you do not have many options: you can use manual verification (without JSR-303), or you can copy-paste the code from SpringValidatorAdapter into your own utility method and manually call JSR-303 Validator methods.

+4
source

All Articles