简体   繁体   English

spring请求参数绑定错误

[英]spring request parameters binding error

@RequestMapping("/query")
@ResponseBody
public ResponseEntity<Content> getByQuery(HttpServletRequest request, ContentQuery query) {
    // Handle request.
}

This code is going to function as an http wrapper of the ContentQuery object so that i can query content with http-requests from javascript. 此代码将作为ContentQuery对象的http包装器运行,以便我可以使用来自javascript的http请求查询内容。 The automatic binding in Spring binds request parameters to the ContentQuery object. Spring中的自动绑定将请求参数绑定到ContentQuery对象。

The problem is that if someone puts an unknown parameter key in the request, the ContentQuery object is stil instantiated, and i don't know how to check if i get unexpected params. 问题是,如果有人在请求中放入一个未知的参数键,则ContentQuery对象将被实例化,并且我不知道如何检查我是否得到了意外的参数。

Is there any way to handle this? 有办法处理这个吗?

then write your own validator and run it in your controller - docs.spring.io/spring/docs/current/spring-framework-reference/… . 然后编写自己的验证器并在控制器中运行它 - docs.spring.io/spring/docs/current/spring-framework-reference/... Then you can return ResponseEntity with any status you want – freakman 然后你可以用你想要的任何状态返回ResponseEntity - freakman

Thank you for the hint. 谢谢你的提示。 Haven't used the Validator interface before, but it looks like a clean solution. 之前没有使用过Validator接口,但它看起来像一个干净的解决方案。

Controller: 控制器:

@Autowired
private ContentQueryValidator validator;

@RequestMapping("/query")
@ResponseBody
public ResponseEntity<List<Content>> getByQuery(
        HttpServletRequest request, ContentQuery query, BindingResult result) {
    validator.validate(query, result);
    if(result.hasErrors()){
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    // No errors. Fetch content from service using query object.
}

And the validator: 验证者:

@Component
public class ContentQueryValidator implements Validator{
    @Override
    public boolean supports(Class<?> aClass) {
        return ContentQuery.class.equals(aClass);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ContentQuery query = (ContentQuery) obj;

        List<Integer> contentTemplate = query.getContentTemplate();
        List<Integer> displayTemplate = query.getDisplayTemplate();

        if(contentTemplate == null && displayTemplate == null){
            errors.reject("No query provided");
        }
        // More validation here..
    }
}

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

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