一尘不染

Springboot请求方法'POST'不受支持

spring-mvc

我刚刚开始学习用于REST API开发的Java Spring Boot。使用下面的代码,GET方法可以正常工作,但POST无法正常工作。

@RestController
@RequestMapping("/api/users")
public class UsersController {

    @Autowired
    private UserRepository userRepository;

    @RequestMapping(method = RequestMethod.GET)
    public List<User> getAll() {
        return userRepository.findAll();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String saveUser() {
        return "Saved";
    }

}

在Postman应用程序中使用Content-Typeas 测试了POST方法application/json

错误,

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

在日志中,我可以看到,

s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/users],methods=[POST]}" onto public java.lang.String com.betasquirrel.controller.UsersController.saveUser()
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/api/users],methods=[GET]}" onto public java.util.List<com.betasquirrel.model.User> com.betasquirrel.controller.UsersController.getAll()
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]

适用于Maven的Java和springboot版本,

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/> 
</parent>

<properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
     <java.version>1.8</java.version>
</properties>

阅读 1814

收藏
2020-06-01

共1个答案

一尘不染

最后,通过使用maven命令运行项目来解决该问题。

而不是使用IDE的运行按钮运行项目,而是转到IDE中的终端并执行命令

mvn spring-boot:run

由于它是一个REST实现,因此我现在可以访问它们,

GET /api/users/ or /api/users
POST /api/users/ or /api/users

像魅力一样工作!

2020-06-01