【问题标题】:Spring GET and PATCH requestSpring GET 和 PATCH 请求
【发布时间】:2017-02-02 13:32:40
【问题描述】:

我的 Spring Boot REST 控制器中有 2 种方法

这是我的 REST 控制器代码

@RestController
public class MainRestController {

@RequestMapping(value = "/",method=RequestMethod.POST)
public String startMigration(){
        return "POSt";
}

@RequestMapping(value = "/",method=RequestMethod.PATCH)
public String PUT(){
        return "PUT";
}

/*
 * If i commnet this method and un comment following method it will run
 * */
@RequestMapping(value = "/{name}",method=RequestMethod.PUT)
public String PATCH(@PathVariable String name){
        return "PATCH";
}

/*@RequestMapping(value = "/",method=RequestMethod.PATCH)
public String PATCH(){
        return "PATCH";
}*/

@RequestMapping(value = "/",method=RequestMethod.DELETE)
public String DELETE(){
        return "DELETE";
}
}

这是我的控制器代码

@Controller
public class MainController {

@RequestMapping(value = "/",method=RequestMethod.GET)
public String getMainPage(){
    return "index.html";
}
}

现在的问题是当我点击 PATCH 请求时 http://localhost:8080/ 它返回

{
"timestamp": 1486041782895,
"status": 405,
"error": "Method Not Allowed",
"exception":"org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'PATCH' not supported",
"path": "/"
}

当我点击 GET 请求 http://localhost:8080/ 它返回

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Thu Feb 02 19:00:18 IST 2017
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported 

谁能告诉我原因?

【问题讨论】:

  • 您能否添加一个展示 SB 应用程序的示例要点?
  • 我已经添加了有问题的两个类代码

标签: spring-boot spring-restcontroller


【解决方案1】:

现在的问题是当我点击 PATCH 请求 http://localhost:8080/ 它返回

{
"timestamp": 1486041782895,
"status": 405,
"error": "Method Not Allowed",
"exception":"org.springframework.web.HttpRequestMethodNotSupportedException",
"message": "Request method 'PATCH' not supported",
"path": "/"
}

发生此错误是因为您声明了一个需要在方法中包含 PathVariable 的方法。

如果您希望它在不传递变量的情况下工作,您应该执行以下操作:

@RequestMapping(method=RequestMethod.PATCH)
public @ResponseBody String patch(@RequestParam(name = "name", required = false) String name){
    return "ANOTHER PATCH";
}

所以这个 PATCH 请求 http://localhost:8080/ 应该返回“ANOTHER PATCH”

这是你的问题吗?

【讨论】:

  • 我的 GET 请求问题,当我评论我的 PATCH 方法 GET 开始工作时
  • 我不是专家,但您可能使用 Controller 而不是 RestController 编写了这个类。在 RestController 注解中,封装了 ResponseBody 方法。使用 Controller 时,需要使用 ResponseBody 注解(在类或方法中),它将根据外部客户端的能力和类路径上可用的库自动序列化返回值。或许有专家可以更好地向我们解释原因。
  • 是的,我有 1 个控制器,其中我为 UI(html) 编写了 GET,还有一个用于 Web 服务的 REST 控制器,其中包含 PATCH 方法。当我使用 requestmapping 提供别名时,它可以正常工作,但 m 没有提供任何别名,仅使用“/”,然后它不工作
猜你喜欢
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多