2012-11-23 110 views
0

我在我的控制器以下GET請求:春天驗證的乘法參數

@Controller 
public class TestController { 

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

    @RequestMapping(value = "/more/{fromLocation:.+}/to/{toLocation:.+}", method = RequestMethod.GET) 
    @ResponseBody 
    public void copyProfile(@PathVariable @Valid String fromLocation, @PathVariable String toLocation) { 
    ... 
    } 
} 

而且我有串fromLocation

public class ProfileTokenValidator implements Validator{ 

    @Override 
    public boolean supports(Class validatedClass) { 
     return String.class.equals(validatedClass); 
    } 

    @Override 
    public void validate(Object obj, Errors errors) { 
     String location = (String) obj; 

     if (location == null || location.length() == 0) { 
      errors.reject("destination.empty", "Destination should not be empty."); 
     } 
    } 

} 

,我需要提供驗證了該問題的簡單驗證如果fromLocation與toLocation相同。 請幫助建議或有什麼,有沒有什麼辦法來編寫驗證器,它將同時檢查兩個參數的Get請求? 謝謝。

塊引用

回答

0

這是一個壞主意。我換了另一種方式,並在控制器中創建了一個簡單的方法來驗證我的參數如果有什麼錯誤,它會拋出特殊的異常,由處理程序處理。這個處理程序在拋出之前返回400個狀態錯誤的請求和消息。所以它的行爲與自定義驗證器完全相同。有很大的幫助是從文章通過此鏈接http://doanduyhai.wordpress.com/2012/05/06/spring-mvc-part-v-exception-handling/

而下面是我的代碼:

@Controller 
public class TestController { 

    @RequestMapping(value = "/more/{fromLocation:.+}/to/{toLocation:.+}", method = RequestMethod.GET) 
    @ResponseBody 
    public void copyProfile(@PathVariable String fromLocation, @PathVariable String toLocation) { 
     validateParams(fromLocation, toLocation); 
     ... 
    } 

    private void validateParams(String fromLocation, String toLocation) { 
     if(fromLocation.equals(toLocation)) { 
      throw new BadParamsException("Bad request: locations should differ."); 
     } 
    } 

    @ExceptionHandler(BadParamsException.class) 
    @ResponseStatus(value = HttpStatus.BAD_REQUEST) 
    @ResponseBody 
    public String handleBadParamsException(BadParamsException ex) { 
     return ex.getMessage(); 
    } 

    @ResponseStatus(value = HttpStatus.BAD_REQUEST) 
    public static class BadParamsException extends RuntimeException { 
     public BadParamsException(String errorMessage) { 
      super(errorMessage); 
     } 
    } 
}