【发布时间】:2018-03-18 04:03:02
【问题描述】:
我遇到了一个小问题,浪费了我很多时间...
出于演示目的,我使用 Eclipse New > Spring Starter Project 创建了一个简单的 SpringBoot 应用程序。
这是我的应用程序类:
package it.asirchia;
//All needed imports
@SpringBootApplication
public class Application {
public static HashMap<Long,Book> books = new HashMap<Long, Book>();
public static HashMap<Long,Editor> editors = new HashMap<Long, Editor>();
public static HashMap<Long,Person> authors = new HashMap<Long, Person>();
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
然后我创建了 EditorsApis 控制器:
package it.asirchia.apis;
//All needed imports
@RestController
@RequestMapping(value="/editors")
public class EditorsApis {
private static long counter = 0;
@RequestMapping(value="/", method=RequestMethod.GET)
public HashMap<Long, Editor> getAllEditor(){
return Application.editors;
}
@RequestMapping(value="/", method=RequestMethod.POST)
public void postNewEditor(@RequestBody Editor editor){
Application.editors.put(counter++, editor);
}
@RequestMapping(value="/{editorid}", method=RequestMethod.PUT)
public void updateEditor(@PathVariable long editorid,
@RequestBody Editor editor){
Application.editors.put(editorid, editor);
}
@RequestMapping(value="/{editorid}", method=RequestMethod.GET)
public Editor getEditor(@PathVariable long editorid){
return Application.editors.get(editorid);
}
@RequestMapping(value="/{editorid}", method=RequestMethod.DELETE)
public void deleteEditor(@PathVariable long editorid){
Application.editors.remove(editorid);
}
}
还有一个 AuthorsApis 和一个 BooksApis 控制器,它们与 EditorApis 控制器非常相似。
当然,我也创建了所有三个 Pojo: Editor.class、Person.class 和 Book.class
我已经启动了 Eclipse 嵌入式 Spring 运行时,我可以看到所有路径都已正确映射:
INFO [main] s.w.s.m.m.a.RequestMappingHandlerMapping 映射" {[/authors/],methods=[GET]}" 到公共 java.util.HashMap it.asirchia.apis.AuthorsApis.getAllAuthors()
对于我已实现的所有其他 Rest API,依此类推。 日志的最后三行是:
在阶段 0 启动 bean
Tomcat 在端口启动:8080 (http)
在 5.547 秒内启动应用程序(JVM 运行 6.169)
好的,对我来说,一切都已正确配置、启动并运行。但是当我尝试调用
GET /authors HTTP/1.1
Host: localhost:8080
我得到:
{
"timestamp": 1507286437765,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/authors"
}
ALL 我实现的 REST API 也是如此。 关于这个问题的原因的任何想法? 谢谢。
【问题讨论】:
-
尝试 localhost:8080/editors/ 或 localhost:8080/authors/ 。它应该工作
-
我试过了……不行
-
对不起@VelNaga 有了斜杠,它起作用了......谢谢
-
你能添加你的application.properties吗?
-
@Cyril 我的 application.properties 是空的。
标签: spring rest spring-boot controller