【发布时间】:2020-06-01 09:49:17
【问题描述】:
我有一个 Spring Boot 应用程序,我只是发送一个 GET 请求以从预先填充的列表中获取一些数据。 该列表存在于控制器类中。当我点击 URL 时,我不断收到 404 错误。
Student.java
package com.SpringBootDemo.entities;
public class Student {
private Integer studentId;
private String studentName;
public Student(Integer studentId, String studentName) {
super();
this.studentId = studentId;
this.studentName = studentName;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
StudentController.java
package com.SpringBootDemo.controller;
import java.util.Arrays;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.SpringBootDemo.entities.Student;
@RestController
@RequestMapping("api/v1/students")
public class StudentController {
private static final List<Student> STUDENTS = Arrays.asList(
new Student(1,"ABC"),
new Student(2,"DEF"),
new Student(3,"HIJ"));
@GetMapping(path = "{studentId}")
public Student getStudentById(@PathVariable("studentId")Integer studentId)
{
System.out.println("inside the controller");
return STUDENTS.stream()
.filter(student -> studentId.equals(student.getStudentId()))
.findFirst()
.orElseThrow(()->new IllegalStateException("Student with id "+studentId+" doesn't exist"));
}
}
Application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/spring_project
spring.datasource.username=root
spring.datasource.password=Pblock@20
server.port = 8081
spring.jpa.show-sql=true
我的堆栈跟踪
020-06-01 15:07:29.879 INFO 21012 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 10ms. Found 0 JPA repository interfaces.
2020-06-01 15:07:30.275 INFO 21012 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8081 (http)
2020-06-01 15:07:30.281 INFO 21012 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-06-01 15:07:30.281 INFO 21012 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.35]
【问题讨论】:
-
那么您将 GET 请求发送到哪个 url?
-
404 仅表示您的应用程序未正确部署或您访问了错误的 URL。请仔细检查您的 URL 是否正确(上下文路径 + url)
-
假设服务在
local和端口8080中运行,您的端点应该类似于http://localhost:8080/api/v1/students/1 -
我的服务器端口是 8081,我正在访问
http://localhost:8081/api/v1/students/1 -
我创建了一个与您一样的端点,并且我能够通过您在 cmets 中提供的 URL 访问该路径!检查您的配置而不是 URL。
标签: java spring-boot rest get