Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring框架验证请求参数或路径变量_Spring_Spring Mvc - Fatal编程技术网

Spring框架验证请求参数或路径变量

Spring框架验证请求参数或路径变量,spring,spring-mvc,Spring,Spring Mvc,我知道我可以在Spring中验证表单,但是我可以对URL参数应用类似的验证吗?例如,我的控制器中有一个方法,如下所示: public String edit(@PathVariable("system") String system, @RequestParam(value="group") String group, ModelMap model) throws DAOException { 在调用方法之前,我是否可以验证系统和组的值,以确保它们具有特定值或与特定正则表达式

我知道我可以在Spring中验证表单,但是我可以对URL参数应用类似的验证吗?例如,我的控制器中有一个方法,如下所示:

public String edit(@PathVariable("system") String system, 
    @RequestParam(value="group") String group,
    ModelMap model) throws DAOException {
在调用方法之前,我是否可以验证
系统
的值,以确保它们具有特定值或与特定正则表达式匹配


谢谢

您可以为此使用Spring断言。断言api(http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/util/Assert.html)针对指定参数运行提供的表达式,如果表达式等于false,则抛出异常

例: Assert.isTrue(system.equals(“ValidSystemName”),“必须提供有效的系统”)

它还包含检查参数是否为空或是否为空字符串等功能。

  • 创建标记应验证的参数的注释。此批注需要
    运行时的
    @Retention
    元素类型.参数的
    @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切入点表达式语言,请参阅:


要了解Spring中的AspectJ集成,请参见:

我可能有点晚了,但在Spring3.0中,您可以选择使用JSR-303验证和
@Valid
注释。还有一些更具体的注释,如
@DateTimeFormat
@NumberFormat
。详情如下: 在我看来,你有两个选择:

  • 将请求参数定义为对象和用户JSR-303 验证
  • 如上所述,使用断言api

如果您只想对单个值进行简单的验证,我会选择后者(这是我在使用简单int值检查max value时所做的)。

没有时间提供完整的答案,所以只需一条注释:在添加方法扩展之前,您无法使用JSR-303进行验证,但您可以使用AOP进行验证。