简体   繁体   中英

Validate @RequestParam to be in a list of enum

I want to limit the user of Spring MVC to access only certain values of the enum, I need to throw constraint exception when the requested param contains the restricted value.

Enum Example:

public enum EnumActionValues {

  WAIT,
  OFFLINE,
  LOGGED_IN,
  LOGGED_OUT,
  OTHERS,
  //
  ; 
  public List<EnumActionValues> getManuallyAllowedActions() {
    return Arrays.asList(
        WAIT,
        OFFLINE,
        OTHERS
    );
  }
}

In the above enum I want to webrequest to the Controller should contain only getManuallyAllowedActions , the LOGGED_IN and LOGGED_OUT shouldn't be allowed by user, which will be used internally.

Is there any direct annotations to be used with @Valid/@Validated .

You can have a custom annotation and a validator that goes with it.

Your annotation could look like this:

@Documented
@Constraint(validatedBy = YourConstraintValidator.class)
@Target( { ElementType.FIELD } )
@Retention(RetentionPolicy.RUNTIME)
public @interface YourConstraint
{
    String message() default "Invalid enum";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

And your validator would be:

public class YourConstraintValidator implements ConstraintValidator<YourConstraint, EnumActionValues> {
    @Override
    public void initialize(YourConstraint constraint) {
    }

    @Override
    public boolean isValid(EnumActionValues obj, ConstraintValidatorContext context) {
        return obj == null || obj.getManuallyAllowedActions().contains(obj);
    }
}

This validator allows for the enum to be null so it will still work in case the enum is null in the request.

Note that you will have to use @ModelAttribute annotation instead of @RequestParam for this to work.

I think your requirement here is very specific and you probably have to write the check yourself. Something like this should do the trick:

public ResponseEntity someEndpoint(final EnumActionValues aAction) {

  if ((aAction != null) && !EnumActionValues.getManuallyAllowedActions().contains(aAction)) {
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(null);
  }

  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM