如何为GET请求中的布尔参数创建自定义类型转换器?
例如,我希望GET请求中允许的值是"oui“和"non”,而不是"true“和"false”。我遵循了春季文献关于如何做到这一点的步骤,并尝试了以下步骤:
@RestController
public class ExampleController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor("oui", "non", true));
}
@GetMapping("/e")
ResponseEntity<String> showRequestParam(@RequestParam boolean flag) {
return new ResponseEntity<>(String.valueOf(flag), HttpStatus.OK);
}
}我也试过这个:
@RestController
public class DemoController {
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addCustomFormatter(new Formatter<Boolean>() {
@Override
public Boolean parse(String text, Locale locale) throws ParseException {
if ("oui".equalsIgnoreCase(text)) return true;
if ("non".equalsIgnoreCase(text)) return false;
throw new ParseException("Invalid boolean parameter value '" + text + "'; please specify oui or non", 0);
}
@Override
public String print(Boolean object, Locale locale) {
return String.valueOf(object);
}
}, Boolean.class);
}
@GetMapping("/r")
ResponseEntity<String> showRequestParam(@RequestParam(value = "param") boolean param) {
return new ResponseEntity<>(String.valueOf(param), HttpStatus.OK);
}
}这两样都不管用。当提供值"oui“时,我得到了带有以下消息的HTTP 400响应:
未能将“java.lang.String”类型的值转换为所需的类型“布尔”;嵌套异常是java.lang.IllegalArgumentException:无效的布尔值oui“
更新:
我现在也尝试使用转换器:
@Component
public class BooleanConverter implements Converter<String, Boolean> {
@Override
public Boolean convert(String text) {
if ("oui".equalsIgnoreCase(text)) return true;
if ("non".equalsIgnoreCase(text)) return false;
throw new IllegalArgumentException("Invalid boolean parameter value '" + text + "'; please specify oui or non");
}
}这种“类”是有效的,因为它现在接受“of”和“非”,但除了“真”和“假”之外,它也是这样做的。我如何才能让它接受“of”和“非”而不是“真”和“假”?
发布于 2022-11-22 17:54:05
在第一个例子中,您的requestParam是一个布尔值,但是绑定了一个BO。
我试过用这个代码
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor("oui", "non", true));
}
@GetMapping("/e")
ResponseEntity<String> showRequestParam(@RequestParam(value="flag") Boolean flag) {
return new ResponseEntity<>(String.valueOf(flag), HttpStatus.OK);
}而且是打印出来的
真的
当我调用localhost:8080/e?标志=oui时
发布于 2022-11-22 17:53:52
你不能把它映射到一个枚举吗?
enum BooleanInput {
oui(true),
non(false);
private boolean value;
BooleanInput(boolean value) {
this.value = value;
}
Boolean value() {
return this.value;
}
}在控制器里,
@GetMapping("/e")
ResponseEntity<String> showRequestParam(@RequestParam BooleanInput flag) {
return new ResponseEntity<>(flag.value(), HttpStatus.OK);
}https://stackoverflow.com/questions/74536442
复制相似问题