java - spring 4 枚举作为 Controller 参数

标签 java spring enums

稍后编辑

我描述的案例工作正常。当我在 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/

相关文章:

java - Cucumber 和 Spring boot 集成有错误

java - 更改 JSF h :selectManyCheckbox on event 的选定项目

spring - SFTP上传文件权限被拒绝

java - 在 switch case 中使用枚举的序号而不是使用枚举有什么重要的理由吗?

java - 在 Intellij IDEA 的编辑器选项卡中更改组件

java - Gson toJson 方法在打印字符串时包含转义字符

java - 在spring boot中 Autowiring 一个bean,它在主java包中为空,但在测试包中可以工作

java - JPA + hibernate + MySQL : How to propagate a schema into the connection?

enums - 枚举值作为 Haxe 中的参数默认值

java - 命名枚举类型