简体   繁体   English

学习 SpringBoot(Java、Hibernate、PostgreSql、JSON)时遇到这个问题/错误

[英]Encountered this problem/error while learning SpringBoot (Java, Hibernate, PostgreSql, JSON)

I'm currently learning SpringBoot using Hibernate and PostgreSql.我目前正在使用 Hibernate 和 PostgreSql 学习 SpringBoot。 I recently encountered this problem when trying to run my POST request.我最近在尝试运行我的 POST 请求时遇到了这个问题。 Any help would be greatly appreciated!任何帮助将不胜感激!

{
  "timestamp": "2022-05-26T05:12:32.040+00:00",
  "status": 405,
  "error": "Method Not Allowed",
  "path": "/api/v1/student"
}

Process finished with exit code 130 (interrupted by signal 2: SIGINT)进程以退出代码 130 结束(被信号 2:SIGINT 中断)

2022-05-26 01:00:29.650 WARN 68743 --- [nio-8080-exec-1] .wsmsDefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported] 2022-05-26 01:00:29.650 WARN 68743 --- [nio-8080-exec-1] .wsmsDefaultHandlerExceptionResolver:已解决 [org.springframework.web.HttpRequestMethodNotSupportedException:不支持请求方法“POST”]

JSON: JSON:

POST http://localhost:8080/api/v1/student
Content-Type: application/json

{
  "name": "Bilal",
  "email": "bilal.ahmed@gmail.com",
  "dob": "1995-12-17"
}

Student.java学生.java

package com.example.demo.student;

import javax.persistence.*;
import java.time.LocalDate;
import java.time.Period;

@Entity
@Table
public class Student {
    @Id
    @SequenceGenerator(name = "student_sequence", sequenceName = "student_sequence", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "student_sequence")
    private Long id;
    private String name;
    private String email;
    private LocalDate dob;
    @Transient
    private Integer age;

    public Student() {
    }

    public Student(Long id, String name, String email, LocalDate dob) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.dob = dob;
    }

    public Student(String name, String email, LocalDate dob) {
        this.name = name;
        this.email = email;
        this.dob = dob;
    }

    public Long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

    public LocalDate getDob() {
        return dob;
    }

    public Integer getAge() {
        return Period.between(this.dob, LocalDate.now()).getYears();
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", dob=" + dob +
                ", age=" + age +
                '}';
    }
} 

StudentConfig.java StudentConfig.java

package com.example.demo.student;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.util.List;

import static java.time.Month.*;

@Configuration
public class StudentConfig {

    @Bean
    CommandLineRunner commandLineRunner(StudentRepository repository) {
        return args -> {
            Student mariam = new Student("Mariam", "mariam.jamal@gmail.com", LocalDate.of(2000, JANUARY, 5));
            Student alex = new Student("Alex", "alex@gmail.com", LocalDate.of(2004, JANUARY, 5));
            repository.saveAll(List.of(mariam, alex));
        };
    }
}

StudentController.java StudentController.java

package com.example.demo.student;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("api/v1/student")
public class StudentController {

    private final StudentService studentService;

    @Autowired
    public StudentController(StudentService studentService) {
        this.studentService = studentService;
    }

    @GetMapping
    public List<Student> getStudents() {
        return studentService.getStudents();
    }

    public void registerNewStudent(@RequestBody Student student) {
        studentService.addNewStudent(student);
    }
}

StudentRepository.java StudentRepository.java

package com.example.demo.student;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {

}

StudentService.java学生服务.java

package com.example.demo.student;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Service
public class StudentService {

    private final StudentRepository studentRepository;

    @Autowired
    public StudentService(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    public List<Student> getStudents() {
        return studentRepository.findAll();
    }

    @PostMapping
    public void addNewStudent(Student student) {
        System.out.println(student);
    }
}

So I added PostMapping to the controller and now I get when I run the POST request for the payload.所以我将 PostMapping 添加到控制器中,现在我在运行有效负载的 POST 请求时得到了。 Any idea?任何想法?

EDIT: NEVERMIND I GOT IT TO WORK THANK YOU!编辑:没关系,我可以工作,谢谢!

Actually you don't have any @PostMapping in your controller so when spring is routing your request it only finds the @GetMapping at the requested path and it's why it throws a 405 error.实际上,您的控制器中没有任何 @PostMapping ,因此当 spring 路由您的请求时,它只会在请求的路径中找到 @GetMapping ,这就是它引发 405 错误的原因。

All the Request Mappings should be in a controller, not in a service .所有请求映射都应该在控制器中,而不是在服务中。 You can make many differents controllers if you want.如果需要,您可以制作许多不同的控制器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Java中使用PrintWriter时遇到的问题 - Problem encountered while using PrintWriter in Java 使用Hibernate保存Servlet中处理的数据时遇到错误 - Error encountered while using Hibernate to save data processed in Servlets springboot中使用hibernate拦截器的问题 - Problem of using hibernate interceptor in springboot java.lang.ClassCastException:类模型 - 在主题中将 JSON 对象作为消息发送时,springboot kafka 集成出错 - java.lang.ClassCastException: class model - Error in springboot kafka integration while sending JSON object as message in topic Springboot Hibernate &amp; JPA 和 Native Queries (Group by PostgreSQL date_trunc) 可分页问题 - Springboot Hibernate & JPA and Native Queries (Group by PostgreSQL date_trunc) pageable problem org.postgresql.util.PSQLException:错误:关系“用户”不存在 - SpringBoot,Hibernate,Postgresql - org.postgresql.util.PSQLException: ERROR: relation "users" does not exist - SpringBoot, Hibernate, Postgresql 通过Hibernate在PostgreSQL中保存数据时如何解决“错误:遇到无效的字节序标志值。” - How to fix “ERROR: Invalid endian flag value encountered.” during saving data in PostgreSQL through Hibernate Hibernate3,PostgreSQL 8.3和Java 5的“没有合适的驱动程序”问题 - “No suitable driver” problem with Hibernate3, PostgreSQL 8.3 and Java 5 尝试JCov Java Coverage Utility时遇到错误 - Encountered error while trying JCov java coverage utility How to save json Object in postgresql using Hibernate in java? - How to save json Object in postgresql using Hibernate in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM