gpt4 book ai didi

java - spring 4 枚举作为 Controller 参数

转载 作者:行者123 更新时间:2023-12-05 07:51:27 24 4
gpt4 key购买 nike

稍后编辑

我描述的案例工作正常。当我在 Controller 的方法上有这样的东西时,问题就出现了:

@RestController 
public class MyController {
@RequestMapping(...)
public void myMethod(@RequestBody MyForm myform) { ... }
}

public class MyForm {
private X x;
//setters and getters
}

原因

Given RequestBody, Spring will use an HttpMessageConverter to deserialize your request body into an instance of your given type. In this case, it will use MappingJackson2HttpMessageConverter for the JSON. This converter does not involve your PropertyEditorSupport at all.

还有其他选择吗?在这种情况下,我需要使用 @RequestBody 或找到将 X 放入 myform 的方法。


我想将枚举作为参数放入 REST Controller 的方法中。

这就是我到目前为止所得到的。

枚举:

public enum X {
A("A"),B("B"),C("C");
... methods and constructors ...
}

Controller :

@RestController 
public class MyController {
@RequestMapping(...)
public void myMethod(@PathVariable("x") X x) { ... }
}

配置:

@ControllerAdvice
public class GlobalControllerConfig {
@InitBinder
public void registerCustomEditors(WebDataBinder binder, WebRequest request) {
binder.registerCustomEditor(X.class, new XPropertyEditor());
}
}

属性编辑器:

public class XPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
try {
setValue(X.findByName(text));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Custom binding failed. Input type: String. Expected type of value to be set: X", e);
}
}

@Override
public String getAsText() {
return ((X)getValue()).getName();
}
}

我在我的 @ControllerAdvice 中放置了一个断点,每次向我的任何 Controller 发出请求时,它都会通过该绑定(bind)。这让我认为绑定(bind)是正确的。

当我向我的方法发送请求时,我得到了这个,但我不明白为什么:

org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Can not construct instance of ...X from String value 'A': value not one of declared Enum instance names: [A, B, C]

有什么建议吗?

最佳答案

尝试将@RequestVariable 更改为@RequestParameter。

我会像这样更改 setAsText 方法行:

@Override
public void setAsText(String text) {
try {
String upperText = text.toUpperCase();
X xResult = X.valueOf(upperText);
setValue(xResult);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Custom binding failed. Input type: String. Expected type of value to be set: X", e);
}
}

关于java - spring 4 枚举作为 Controller 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35032322/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com