Java 在 Spring 中,@RequestParameter 注释不接受默认值参数的布尔值,它仅适用于字符串 URL 请求参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21116902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:42:23  来源:igfitidea点击:

In Spring, @RequestParameter annotation not accepting boolean for defaultValue argument, it only works with string URL request parameters

javaspringspring-mvc

提问by Horse Voice

This question is related to Spring MVC method I have defined below:

这个问题与我在下面定义的 Spring MVC 方法有关:

The value for the writeToRead parameter should be true or false. I expect the enduser calling my service to append to the url: localhost:8080/index/someendpoint/sometypethe following request parameter: ?writeToRead=trueotherwise it should default to false if user doesn't append the parameter to the end of the url string. The problem is, the defaultValue=falsedoesn't seem to be acceptable in the @RequestParameterannotation. It looks like it only accepts string types rather than the boolean type I'm using. I could make defaultValue="false" but really, that's not a boolean. It's a string. How should I approach this? I can't use string alternatives (like "Y" or "N") to solve this problem because of method overloaded definition conflicts. How can I do this with booleans? Thank you in advance!

writeToRead 参数的值应为 true 或 false。我希望调用我的服务的最终用户附加到 url:localhost:8080/index/someendpoint/sometype以下请求参数:?writeToRead=true否则,如果用户没有将参数附加到 url 字符串的末尾,它应该默认为 false。问题是,注释defaultValue=false中的 似乎不可接受@RequestParameter。看起来它只接受字符串类型而不是我正在使用的布尔类型。我可以使 defaultValue="false" 但实际上,这不是布尔值。这是一个字符串。我应该如何处理这个问题?由于方法重载定义冲突,我无法使用字符串替代项(如“Y”或“N”)来解决此问题。我怎样才能用布尔值做到这一点?先感谢您!

@RequestMapping(value="/index/{endpoint}/{type}", method=RequestMethod.POST, consumes=kCompressed, produces=kProducesType)
@ResponseBody
public String indexData(@PathVariable(value="endpoint") String endpoint, @PathVariable(value="type") String type, 
                        @RequestParam(value="writeToRead", defaultValue=false) boolean writeToRead,                 
                        @RequestBody byte[] body, HttpServletRequest request) throws Exception {
    logger.debug("In indexData for endpoint " + endpoint);

    String bodyStr = decompress(body);
    return indexController.indexData(endpoint, type, bodyStr, writeToRead, getSecurityContextProvider(request));
}   

采纳答案by Sotirios Delimanolis

Declaring it as

将其声明为

@RequestParam(value="writeToRead", defaultValue="false")

is the appropriate thing to do. Request parameters are character strings, nothing else. You can parse them and give them the semantics you want or require (ex. booleans), but, at the base, they are just strings.

是正确的做法。请求参数是字符串,没有别的。您可以解析它们并为它们提供您想要或需要的语义(例如布尔值),但是,从根本上讲,它们只是字符串。