2014-10-07 52 views
6

例子:爲什麼我不能在Spring MVC中使用ValidParam和RequestParam?

public String getStudentResult(@RequestParam(value = "regNo", required = true) String regNo, ModelMap model){ 

如何使用@Valid這裏的REGNO參數?

+0

你就是不行。 '@ Valid'僅適用於不是像'String'或'Integer'這樣的基本結構的對象。如果你想驗證你將不得不自己做。 – 2014-10-07 09:23:58

+0

https://jira.spring.io/browse/SPR-6380 – Bax 2016-03-12 00:11:20

回答

3

@Valid可以用來驗證bean。我沒有看到它在單個字符串參數上使用。還需要驗證器進行配置。

@Valid註釋是標準JSR-303 Bean驗證API的一部分,並且不是特定於Spring的構造。 Spring MVC將在綁定後驗證@Valid對象,因爲已經配置了適當的Validator。

參考:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html

+0

感謝您的回答。我是否可以知道如何驗證我的Spring MVC項目的單個String參數以在Sever端驗證? – user3705478 2014-10-07 06:48:10

+0

2)我的另一個問題是,我可以同時使用@ModelAttribute和@RequestParam(value =「regNo」,required = true)嗎? – user3705478 2014-10-07 07:16:25

1

一個辦法做到這一點是寫一個包裝器bean如下所示:

public class RegWrapperBean{ 

     @NotNull 
     String regNo ; 

     public String getRegNo(){ 
      return regNo ; 
     } 

     public void setRegNo(String str){ 
      this.regNo=str; 
     } 

} 

,你的處理方法將是這樣的:

@RequestMapping(value="/getStudentResult", method=RequestMethod.POST) 
    public String getStudentResult(@Valid @ModelAttribute RegWrapperBean bean, 
      BindingResult validationResult, Model model) { 
    } 

請參考這些回答herehere

希望有所幫助。

5

最後回答。我最近遇到這個問題並找到解決方案。你可以做到這一點如下, 首先註冊的MethodValidationPostProcessor一個bean:

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

然後添加@Validated到控制器的類型級別:

@RestController 
@Validated 
public class FooController { 
    @RequestMapping("/email") 
    public Map<String, Object> validate(@Email(message="請輸入合法的email地址") @RequestParam String email){ 
    Map<String, Object> result = new HashMap<String, Object>(); 
    result.put("email", email); 
    return result; 
    } 
} 

如果用戶請求一個無效的電子郵件地址,將會拋出ConstraintViolationException。你還可以用它捉:

@ControllerAdvice 
public class AmazonExceptionHandler { 

@ExceptionHandler(ConstraintViolationException.class) 
@ResponseBody 
@ResponseStatus(HttpStatus.BAD_REQUEST) 
public String handleValidationException(ConstraintViolationException e){ 
    for(ConstraintViolation<?> s:e.getConstraintViolations()){ 
     return s.getInvalidValue()+": "+s.getMessage(); 
    } 
    return "請求參數不合法"; 
} 

}

您可以檢查出我的演示here

+1

MethodValidationPostProcessor bean對我來說是缺少的難題。謝謝。 – 2016-07-21 04:24:04

相關問題