简体   繁体   English

可以通过在Spring Boot中进行依赖注入来完成请求验证吗?

[英]Can Request validation be done by dependency injection in spring boot?

== Background == ==背景==
I'm used to the dependency injections available in Laravel, where you can make a class that extends the request-class, and put all the validation in it, and then re use it in multiple controller methods. 我习惯了Laravel中提供的依赖项注入,您可以在其中创建一个扩展请求类的类,并将所有验证放入其中,然后在多个控制器方法中重新使用它。

== Current code === ==当前代码===
I'm currently trying to do a project in Java Spring Boot, and my controller methods now looks like this: 我目前正在尝试用Java Spring Boot做一个项目,现在我的控制器方法如下所示:

    @RequestMapping("/list")
    @ResponseBody
    public DTResponse<Name> list(
            @RequestParam(defaultValue = "0") int draw,
            @RequestParam(defaultValue = "0") int start,
            @RequestParam(defaultValue = "0") int length,
            @RequestParam(name="search[value]", defaultValue = "") String search,
            @RequestParam(name="columns[0][search][value]", defaultValue = "") String firstname,
            @RequestParam(name="columns[1][search][value]", defaultValue = "") String lastname,
            @RequestParam(name="order[0][column]", defaultValue = "0") int sortColumn,
            @RequestParam(name="order[0][dir]", defaultValue = "asc") String sortOrder,
            @CookieValue String language,
            HttpServletResponse response,
            HttpServletRequest request
    )

And forward most of them to a validation function. 并将它们中的大多数转发给验证功能。

== Future == ==未来==
I'd like to replace most of thus rows with a class, that can do the validation, and abstract away some of the request parameters in to methods, so they easy can be reused on multiple methods. 我想用一个类来替换大多数这样的行,该类可以进行验证,并将一些请求参数抽象到方法中,以便可以轻松地在多个方法上重用它们。

== Question == ==问题==
How do I write a class, that can be injected in the controller methods, and run validation, and have helper methods that can parse the request params? 我如何编写一个类,该类可以注入控制器方法中并运行验证,并具有可以解析请求参数的辅助方法?

== Alternativ == ==替代==
Can I build a static function, that can get the injected request params, http-servlets and cookie? 我可以构建一个静态函数来获取注入的请求参数,http-servlet和cookie吗?

To add to @Antoniossss' answer... 要添加到@Antoniossss的答案...

The @Valid annotation is the way to go here. @Valid批注是转到此处的方法。

Here is a small example. 这是一个小例子。

@ModelAttribute("command")
public DTRequest setupCommand() {

    return new DTRequest;
}

@RequestMapping(value = "/list")
@ResponseBody
public DTResponse<Name> list(@ModelAttribute("command") @Valid DTRequest request, BindingResult bindingResult, RedirectAttributes redirectAttributes) {

    DTResponse<Name> response;

    if (bindingResult.hasErrors()) {

        // Do something here to let the client know that something went wrong.
        // You can throw and exception and catch it one way or another...

    } else {

        // Do your real work here...
    }

    return response;
}

Your command object could look like the following. 您的命令对象可能如下所示。

NOTE 注意

I STRONGLY suggest using string for all you incoming values because if the value submitted by the client doesn't match the expected type (int, float, boolean, etc...), spring will throw an exception that you have little control over and that exception can be quite cryptic. 强烈建议对您所有传入的值使用字符串,因为如果客户端提交的值与预期的类型(int,float,boolean等)不匹配,spring将抛出一个异常,您无法控制和该异常可能非常隐秘。

The default type that all values can come in as is String and therefore recommend using that as the lowest common denominator and then checking to see if the entered value can be cast to the desired type, in this case, int/integer. 所有值都可以输入的默认类型为String,因此建议将其用作最低公分母,然后检查是否可以将输入的值强制转换为所需类型,在这种情况下为int / integer。

public class DTRequest {

    @Digits
    private String draw = "0";

    @Digits
    private String start = "0";

    @Digits
    private String length = "0";

    // etc... per field.

    // Setters and getters...
    public void setDraw(String draw) {
        this.draw = draw;
    }

    public String getDraw() {
        return this.draw;
    }

    public int getDrawAsInt() {
        return Integer.valueOf(this.draw);
    }

    // etc... per setters and getters...
}

Yes, you can simply use @Valid annotation on arguments to invoke either built-in or custom validations. 是的,您只需在参数上使用@Valid批注即可调用内置或自定义验证。 Check the official documentation 查看官方文件

https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/validation.html https://docs.spring.io/spring/docs/4.1.x/spring-framework-reference/html/validation.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM