我有一个Spring Boot应用程序,在这里我只是发送GET请求以从预先填充的列表中获取一些数据。
该列表存在于控制器类中。当我点击URL时,我不断收到404错误。
学生.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]
最佳答案
您的端点是错误的。将@GetMapping(path =“ {studentId}”)更改为@GetMapping(“ / {studentId}”)
@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("/{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"));
}
}