2010-11-18 73 views
4

我知道我可以驗證Spring中的表單,但是我可以將類似的驗證應用於URL參數嗎?例如,我有一個方法在我的控制器如下:Spring Framework驗證請求參數或路徑變量

public String edit(@PathVariable("system") String system, 
    @RequestParam(value="group") String group, 
    ModelMap model) throws DAOException { 

我可以驗證被稱爲的方法之前systemgroup值,以確保他們有一定的價值或滿足一定的正則表達式?

謝謝

+1

沒有時間提供完整的答案,所以只是一個評論:你不能用JSR-303做,直到他們添加方法擴展,但你可以用AOP來完成。 – GaryF 2010-11-18 17:00:27

回答

0

你也許能夠使用Spring Asserts。 Assert api(http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/Assert.html)針對指定參數運行提供的表達式,如果表達式等於false,則它會拋出一個異常。 (系統名稱「SystemAquals(」ValidSystemName「),」您必須提供有效的系統「);

它也包含了這些功能,查看參數不爲空或不爲空字符串等

0
  • 創建標誌着應驗證參數的註釋。該註釋需要的@RetentionElementType.PARAMETER@Target
  • 創建一個實現爲AspectJ方面的驗證器。
  • 使用此驗證程序將調用封裝到控制器。

樣本註釋:

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.PARAMETER) 
@Documented 
public @interface ValidSystemParameter { 
} 

樣本驗證:

@Aspect 
public class ValidSystemParameterValidator { 
    @Pointcut("TODO: write your pointcut expression") 
    public void controllerMethodWithValidSystemParameter(); 

    @Before(pointcut = "controllerMethodWithValidSystemParameter()") 
    public void validateSystemParameter(String systemParameter) { 
     // validate the parameter (throwing an exception) 
    } 
} 

要了解AspectJ切入點表達式語言請參見:http://www.eclipse.org/aspectj/doc/released/progguide/language-joinPoints.html

要了解在Spring的AspectJ集成見:http://static.springsource.org/spring/docs/current/spring-framework-reference/html/aop.html#aop-ataspectj

0

我可能會有點晚,但對於Spring 3.0,您可以選擇使用JSR-303驗證和@Valid註釋。還有一些更具體的註釋,如@DateTimeFormat@NumberFormat。更多細節在這裏:http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/validation.html#validation-mvc 當我看到它,你有兩個選擇:

  • 定義你的請求參數作爲對象和用戶JSR-303 驗證。
  • 使用上面提到的Assert API。

如果你只是想對單個值做一個簡單的驗證,我會用後者(這就是當我有簡單的int值來檢查最大值時所做的)。