【发布时间】:2016-09-19 03:37:23
【问题描述】:
我开始学习 Spring Boot。我正在努力寻找具有多个 RestController 的示例,这向我表明我可能做错了什么。我正在尝试一个非常简单的示例:目标是进行如下调用:
localhost:8080/
localhost:8080/employees/bob
localhost:8080/departments
我只能让 localhost:8080/ 显示。其他调用返回响应:此应用程序没有显式映射 /error,因此您将其视为后备。
com.demo.departments
Department.java
DepartmentController.java
com.demo.employees
Employee.java
EmployeeController.java
com.demo
BootDemoApplication.java
代码:
package com.demo.departments
@RestController
@RequestMapping("/departments")
public class DepartmentController {
@RequestMapping("")
public String get(){
return "test..";
}
@RequestMapping("/list")
public List<Department> getDepartments(){
return null;
}
}
--------------------------------------------------------------------
package com.demo.employees
@RestController
@RequestMapping("/employees")
public class EmployeeController {
Employee e =new Employee();
@RequestMapping(value = "/{name}", method = RequestMethod.GET, produces = "application/json")
public Employee getEmployeeInJSON(@PathVariable String name) {
e.setName(name);
e.setEmail("employee1@genuitec.com");
return e;
}
}
-----------------------------------------------------------------------
package com.demo
@RestController
@SpringBootApplication
public class BootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BootDemoApplication.class, args);
}
@RequestMapping("/")
String home(){
return "<html> This is the home page for Boot Demo.</html>";
}
【问题讨论】:
-
我认为您不需要在顶级控制器映射上使用前面的“/”。
-
我试过了,没啥影响。
-
这应该可以工作(经过测试)。不过,您没有为
http://localhost:8080/提供任何控制器,所以可能是错误所在。 -
您正在返回 JSON,但没有请求它(浏览器需要 HTML),因此找不到处理请求的方法。
-
是的,员工是 POJO。它没有调用调试器中其他 2 个类中的任何代码。它抱怨的是映射,而不是结果。
标签: java spring-mvc model-view-controller gradle spring-boot