【问题标题】:How to validate Controller method argument in Spring with JSR validations?如何使用 JSR 验证在 Spring 中验证 Controller 方法参数?
【发布时间】:2014-08-13 21:14:34
【问题描述】:

我正在使用给定的代码验证我的表单字段。

//controller method
public String addBusiness(@Valid @ModelAttribute("myForm") MyForm myForm, ...)
{
   //logic will go here.
}

//form 
@Component
public class MyForm{
    @Pattern(regexp = "[0-9]{3,10}", message = "should be valid number")
    public String getZip_code()
    {
       return this.zip_code;
    }
}

现在我想用另一种控制器方法对zip_code 进行相同的验证,例如,

@RequestMapping(value = "${validation.url}", method = RequestMethod.GET)
@ResponseBody
public List<String> getCityList(@RequestParam(value = "zip_code", required = true) final String zip_code)
{
    //logic goes here
}

这怎么可能?

【问题讨论】:

    标签: java spring validation controller arguments


    【解决方案1】:

    不是。 @Valid 不适用于 @RequestParam 带注释的参数。您可以创建自定义HandlerMethodArgumentResolver 来执行此操作或在方法中自己进行验证。

    【讨论】:

    • 嗨@SotiriosDelimanolis 谢谢,如果可能的话,你能给我任何HandlerMethodArgumentResolver 的例子吗?
    • @VishalZanzrukia 这只是一个您实现和注册的接口。实现取决于用例。谷歌这门课,你会发现像this one这样的例子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-15
    • 1970-01-01
    • 2016-03-21
    • 2012-06-18
    相关资源
    最近更新 更多