在拦截器中获取控制器参数

问题描述 投票:2回答:1

我正在创建一个验证库,我想在控制器之前验证请求。我可以获得我想在拦截器中验证的控制器参数真的很好。

目前我可以获得有关控制器参数的所有信息,但我找不到获取参数内部实例的方法。这就是我现在所拥有的:

public class ValidationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            for (MethodParameter param: method.getMethodParameters()) {
                // Check if the parameter has the right annotations.
                if (param.hasParameterAnnotation(RequestBody.class) && param.hasParameterAnnotation(Valid.class)) {
                    // Here I wan't to get the object that is in the parameter so I can validate it.
                }
            }
        }

        return true;
    }
}

示例控制器方法:

@RequestMapping(value = "register", method = RequestMethod.POST)
public Response register(@Valid @RequestBody RegisterRequest request) {
    // return response and stuff.
}

RegisterRequest:

public class RegisterRequest {
    @JsonProperty("email")
    public String email;

    @JsonProperty("name")
    public String name;

    @JsonProperty("password")
    public String password;

    @JsonProperty("password_confirmation")
    public String passwordConfirmation;
}

有没有一种从拦截器访问控制器参数的简单方法?

java spring interceptor request-validation
1个回答
0
投票

不确定你是否还在寻找答案,但我认为你可以使用getPart()getParts()方法来做到这一点。所以在上面的例子中,你可以这样做

Collection<javax.servlet.http.Part> parts = request.getParts();
    Iterator<javax.servlet.http.Part> it = parts.iterator();
    while(it.hasNext()){
        javax.servlet.http.Part p = it.next();
        if(p.getSubmittedFileName() != null)
            fileName = p.getSubmittedFileName();
    }

上面只是一个例子,我试图获取我作为MultiPartFile对象上传的文件的名称。在请求选项中查看您想要获得的参数值。

© www.soinside.com 2019 - 2024. All rights reserved.