2016-02-15 82 views
6

如何在春季驗證我的路徑變量。我想驗證id字段,因爲其唯一單場我不想要移動到一個POJO@PathVariable Spring 4中的驗證

@RestController 
public class MyController { 
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT) 
    public ResponseEntity method_name(@PathVariable String id) { 
     /// Some code 
    } 
} 

我試圖做添加驗證到PATH變量,但它仍然沒有工作

@RestController 
    @Validated 
public class MyController { 
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT) 
    public ResponseEntity method_name(
      @Valid 
      @Nonnull 
      @Size(max = 2, min = 1, message = "name should have between 1 and 10 characters") 
      @PathVariable String id) { 
    /// Some code 
    } 
} 
+0

在你的代碼中沒有路徑變量,至少不在你的URL中,所以不知道什麼需要驗證... –

+0

對不起,我錯過了它w hile在這裏複製和粘貼代碼 –

+0

你可以嘗試簡單if循環method_name方法if(id == null || id.length()<1 || id.length()> 2){String message =「name應該有1到10個字符」; }如果循環結果爲真,您可以按照您的要求返回ResponseEntity, –

回答

12

你需要在Spring配置文件來創建一個bean:

@Bean 
    public MethodValidationPostProcessor methodValidationPostProcessor() { 
     return new MethodValidationPostProcessor(); 
    } 

你應該離開你的控制器上的@Validated註釋。

而且你需要一個exceptionHandler的在MyController類來處理ConstraintViolationException

@ExceptionHandler(value = { ConstraintViolationException.class }) 
    @ResponseStatus(value = HttpStatus.BAD_REQUEST) 
    public String handleResourceNotFoundException(ConstraintViolationException e) { 
     Set<ConstraintViolation<?>> violations = e.getConstraintViolations(); 
     StringBuilder strBuilder = new StringBuilder(); 
     for (ConstraintViolation<?> violation : violations) { 
       strBuilder.append(violation.getMessage() + "\n"); 
     } 
     return strBuilder.toString(); 
    } 

這些變化後,你應該看到你的消息時驗證命中。

P.S .:我剛剛用你的@Size驗證過。

+0

我試過你的解決方案,但它似乎並沒有工作。唯一的區別是我有GET方法。那是分開處理的嗎? –

+0

@NickDiv不應該是一樣的。什麼不適合你?也許你應該提出一個問題,並在這裏評論它的鏈接。 – Patrick

+0

@Patrick:你能否提供完整的源代碼,我試過了,但它仍然無法驗證PathVariable – nguyenngoc101

0

我認爲它的@RequestMapping("/")一個問題,所以 添加@RequestMapping("/")給你休息類,然後使用@pathVariable

@RestController 
@RequestMapping("/xyz") 
public class MyController { 

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT) 
    public ResponseEntity method_name(@PathVariable String id) { 
     /// Some code 
    } 
} 
0

要歸檔這個目標我已經應用此解決方法得到的響應消息相當於一個真正的Validator

@GetMapping("/check/email/{email:" + Constants.LOGIN_REGEX + "}") 
@Timed 
public ResponseEntity isValidEmail(@Email @PathVariable(value = "email") String email) { 
    return userService.getUserByEmail(email).map(user -> { 
     Problem problem = Problem.builder() 
      .withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE) 
      .withTitle("Method argument not valid") 
      .withStatus(Status.BAD_REQUEST) 
      .with("message", ErrorConstants.ERR_VALIDATION) 
      .with("fieldErrors", Arrays.asList(new FieldErrorVM("", "isValidEmail.email", "not unique"))) 
      .build(); 
     return new ResponseEntity(problem, HttpStatus.BAD_REQUEST); 
    }).orElse(
     new ResponseEntity(new UtilsValidatorResponse(EMAIL_VALIDA), HttpStatus.OK) 
    ); 
}