首页 文章

Spring @RequestParam,其值/名称为“status”

提问于
浏览
0

我正在运行一个Spring启动MVC应用程序,在我的控制器中我有一个@RequestParamter,其值为"status" . 当我通过RequestMapping命中此方法时(例如http://localhost:8080/pathToMethod?status=someStatus&otherParam=aThing&status=anotherStatus

@RequestMapping(method = RequestMethod.GET, value ="pathToMethod")
public responseType methodName(
@RequestParam(value = "otherParam", required = false) List<String> param, 
@RequestParam(value = "status", required = false) List<String> status, 
HttpServletRequest request, HttpServletResponse response){
    //code here 
}

它失败并出现以下错误:

对象'modelAndView'对字段'status'的字段错误:被拒绝的值[Soemthing];代码[typeMismatch.modelAndView.status,typeMismatch.status,typeMismatch.org.springframework.http.HttpStatus,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable:codes [modelAndView.status,status];参数[];默认消息[status]];默认消息[无法将类型[java.lang.String]的属性值转换为属性'status'所需的类型[org.springframework.http.HttpStatus];嵌套异常是org.springframework.core.convert.ConversionFailedException:无法将类型[java.lang.String]转换为类型[org.springframework.http.HttpStatus]以获取值'Soemthing';嵌套异常是java.lang.IllegalArgumentException:没有枚举常量org.springframework.http.HttpStatus.Soemthing]

有没有办法绕过Springs默认处理“status”参数,以便它不会自动尝试将其转换为HttpResponse?

Link to similar issue

2 回答

  • -1

    发生这种情况是因为您接受请求参数作为List但只传递String .

    检查以下可能的原因 .

    1.删除 List<String> 并使其成为 String

    2.使用请求参数的任何其他名称而不是 status ,因为 statusorg.springframework.http.HttpStatus 的默认关键字

  • 1

    使用Spring 4和Java 8,可以使用Optional的可选路径变量 .

    代码:

    @RequestMapping(value = {"/path", "/path/{status}")
    public String getResource(@PathVariable Optional<String> status) {
      if (status.isPresent()) {
        return service.processResource(status.get());
      } else {
        return service.processResource();
      }
    }
    

相关问题