java - Spring 的 @RequestParam 与 Enum

标签 java spring spring-boot spring-web

我有这个枚举:

public enum SortEnum {
    asc, desc;
}

我想用作休息请求的参数:

@RequestMapping(value = "/events", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Event> getEvents(@RequestParam(name = "sort", required = false) SortEnum sort) {

当我发送这些请求时它工作正常

/events 
/events?sort=asc
/events?sort=desc

但是当我发送时:

/events?sort=somethingElse

我在控制台中收到 500 响应和这条消息:

2016-09-29 17:20:51.600 DEBUG 5104 --- [  XNIO-2 task-6] com.myApp.aop.logging.LoggingAspect   : Enter: com.myApp.web.rest.errors.ExceptionTranslator.processRuntimeException() with argument[s] = [org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type [java.lang.String] to required type [com.myApp.common.SortEnum]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam com.myApp.common.SortEnum] for value 'somethingElse'; nested exception is java.lang.IllegalArgumentException: No enum constant com.myApp.common.SortEnum.somethingElse]
2016-09-29 17:20:51.600 DEBUG 5104 --- [  XNIO-2 task-6] com.myApp.aop.logging.LoggingAspect   : Exit: com.myApp.web.rest.errors.ExceptionTranslator.processRuntimeException() with result = <500 Internal Server Error,com.myApp.web.rest.errors.ErrorVM@1e3343c9,{}>
2016-09-29 17:20:51.601  WARN 5104 --- [  XNIO-2 task-6] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type [java.lang.String] to required type [com.myApp.common.SortEnum]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam com.myApp.common.SortEnum] for value 'somethingElse'; nested exception is java.lang.IllegalArgumentException: No enum constant com.myApp.common.SortEnum.somethingElse

有没有办法防止spring抛出这些异常并将枚举设置为null?

编辑

Strelok 接受的答案有效。但是,我决定处理 MethodArgumentTypeMismatchException。

@ControllerAdvice
public class ExceptionTranslator {

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    @ResponseBody
    public ResponseEntity<Object> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        Class<?> type = e.getRequiredType();
        String message;
        if(type.isEnum()){
            message = "The parameter " + e.getName() + " must have a value among : " + StringUtils.join(type.getEnumConstants(), ", ");
        }
        else{
            message = "The parameter " + e.getName() + " must be of type " + type.getTypeName();
        }
        return buildResponse(HttpStatus.UNPROCESSABLE_ENTITY, message);
    }

最佳答案

如果您使用的是 Spring Boot,this is the reason你不应该使用 WebMvcConfigurationSupport

最佳实践,你应该实现接口(interface)org.springframework.core.convert.converter.Converter,并带有注解@Component。然后 Spring Boot 会自动加载所有 Converter 的 bean。 Spring Boot code

@Component
public class GenderEnumConverter implements Converter<String, GenderEnum> {
    @Override
    public GenderEnum convert(String value) {
        return GenderEnum.of(Integer.valueOf(value));
    }
}

Demo Project

关于java - Spring 的 @RequestParam 与 Enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39774427/

相关文章:

Java,更改字体和文本颜色。

java - 如何在 GUI jButton 中添加监听器?

java - 错误请求 400

java - 在 Spring Boot 数据休息应用程序中获取 EntityManager

java - 删除剩余端点返回 410 Gone

java - 我怎么知道 onPause() 是因为方向改变而不是 back/home 而被调用?

java - 发布到 Spring Controller 给出 404 Bad Request

java - 如何使用 '@Qualifier'动态指定参数?

java - Spring JPA - 实体的 RESTful 部分更新和验证

java - Spring Batch 限制跨多个服务器的单个作业实例