我刚刚开始学习用于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";
}
}
使用Content-Type
作为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>
答案 0 :(得分:0)
最后,通过使用maven命令运行项目解决了这个问题。
不是使用IDE的运行按钮运行项目,而是直接进入IDE中的终端并执行命令
mvn spring-boot:run
由于它是REST
实现,现在我可以访问这些,
GET /api/users/ or /api/users
POST /api/users/ or /api/users
像魅力一样工作!