405 Метод не разрешен: GET не разрешенJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 405 Метод не разрешен: GET не разрешен

Сообщение Anonymous »

Я создаю простое веб-приложение для бронирования автобусов на Java 21 для серверной части. Я продолжаю получать сообщение об ошибке 405. Метод не разрешен (GET не поддерживается). Это мой текущий код, и я тестирую его с помощью почтальона
АВТОБУСНЫЙ КОНТРОЛЛЕР

Код: Выделить всё

package com.example.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.DTO.BusDTO;
import com.example.Service.BusService;

@RestController
@RequestMapping("/api/buses")
public class BusController {

@Autowired
private BusService busService;

// GET: Retrieve all buses
@GetMapping
public ResponseEntity getAllBuses() {
List buses = busService.getAllBuses();
return ResponseEntity.ok(buses);
}

// GET: Retrieve a specific bus by ID
@GetMapping("/{id}")
public ResponseEntity getBusById(@PathVariable Long id) {
BusDTO bus = busService.getBusById(id);
if (bus != null) {
return ResponseEntity.ok(bus);
} else {
return ResponseEntity.notFound().build();
}
}

// POST: Add a new bus
@PostMapping
public ResponseEntity createBus(@RequestBody BusDTO busDTO) {
BusDTO createdBus = busService.addBus(busDTO);
return ResponseEntity.ok(createdBus);
}

// Optional Test Endpoint
@GetMapping("/test")
public ResponseEntity  testEndpoint() {
return ResponseEntity.ok("Test endpoint is working!");
}
}

BUS DTO

Код: Выделить всё

package com.example.DTO;

import com.fasterxml.jackson.annotation.JsonProperty;

import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.Size;

public class BusDTO {

private Long busNr;

@NotNull(message = "Model cannot be null")
@Size(max = 100, message = "Model name cannot exceed 100 characters")
@JsonProperty("modell")
private String modell;

@NotNull(message = "Availability status cannot be null")
@JsonProperty("bereit")
private Boolean bereit;

@NotNull(message = "Number of seats cannot be null")
@Positive(message = "Number of seats must be positive")
@JsonProperty("sitzAnz")
private Integer sitzAnz;

// Getters and Setters
public Long getBusNr() {
return busNr;
}

public void setBusNr(Long busNr) {
this.busNr = busNr;
}

public String getModell() {
return modell;
}

public void setModell(String modell) {
this.modell = modell;
}

public Boolean getBereit() {
return bereit;
}

public void setBereit(Boolean bereit) {
this.bereit = bereit;
}

public Integer getSitzAnz() {
return sitzAnz;
}

public void setSitzAnz(Integer sitzAnz) {
this.sitzAnz = sitzAnz;
}
}

АВТОБУСНЫЙ ОБЪЕКТ

Код: Выделить всё

package com.example.Entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;

@Entity
public class Bus {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long busNr;
private String modell;
private boolean bereit;
private int sitzAnz;

// Getters und Setters
public Long getBusNr() {
return busNr;
}

public void setBusNr(Long busNr) {
this.busNr = busNr;
}

public String getModell() {
return modell;
}

public void setModell(String modell) {
this.modell = modell;
}

public boolean isBereit() {
return bereit;
}

public void setBereit(boolean bereit) {
this.bereit = bereit;
}

public int getSitzAnz() {
return sitzAnz;
}

public void setSitzAnz(int sitzAnz) {
this.sitzAnz = sitzAnz;
}
}

АВТОБУСНЫЙ СЕРВИС

Код: Выделить всё

package com.example.Service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.DTO.BusDTO;
import com.example.Entity.Bus;
import com.example.repository.BusRepository;

@Service
public class BusService {

@Autowired
private BusRepository busRepository;

public BusDTO addBus(BusDTO busDTO) {
Bus bus = new Bus();
bus.setModell(busDTO.getModell());
bus.setBereit(busDTO.getBereit());
bus.setSitzAnz(busDTO.getSitzAnz());

bus = busRepository.save(bus);

BusDTO savedDTO = new BusDTO();
savedDTO.setBusNr(bus.getBusNr());
savedDTO.setModell(bus.getModell());
savedDTO.setBereit(bus.isBereit());
savedDTO.setSitzAnz(bus.getSitzAnz());
return savedDTO;
}

public List getAllBuses() {
return busRepository.findAll()
.stream()
.map(bus -> {
BusDTO dto = new BusDTO();
dto.setBusNr(bus.getBusNr());
dto.setModell(bus.getModell());
dto.setBereit(bus.isBereit());
dto.setSitzAnz(bus.getSitzAnz());
return dto;
})
.toList();
}

public BusDTO getBusById(Long id) {
return busRepository.findById(id)
.map(bus ->  {
BusDTO dto = new BusDTO();
dto.setBusNr(bus.getBusNr());
dto.setModell(bus.getModell());
dto.setBereit(bus.isBereit());
dto.setSitzAnz(bus.getSitzAnz());
return dto;
})
.orElse(null);
}
}

Docker-compose.yml

Код: Выделить всё

version: "3.8"

services:
# MySQL service for Kunden
kunden-db:
image: mysql:latest
container_name: kunden-db
environment:
MYSQL_DATABASE: kundenDB
MYSQL_ROOT_PASSWORD: root-new
ports:
- "3307:3306"
volumes:
- kunden-db-data:/var/lib/mysql
- ./DB/conf/kunden.sql:/docker-entrypoint-initdb.d/kunden.sql
networks:
- app-network

# MySQL service for Fahrzeuge
fahrzeug-db:
image: mysql:latest
container_name: fahrzeug-db
environment:
MYSQL_DATABASE: fahrzeugDB
MYSQL_ROOT_PASSWORD: root-new
ports:
- "3308:3306"
volumes:
- fahrzeug-db-data:/var/lib/mysql
- ./DB/conf/fahrzeug.sql:/docker-entrypoint-initdb.d/fahrzeug.sql
networks:
- app-network

# Spring Boot application
spring-boot-app:
build:
context: .
dockerfile: Dockerfile
container_name: spring-boot-app
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://fahrzeug-db:3306/fahrzeugDB
SPRING_DATASOURCE_USERNAME: backend
SPRING_DATASOURCE_PASSWORD: backend-pass
SPRING_JPA_HIBERNATE_DDL_AUTO: update
ports:
- "8082:8080"
depends_on:
- fahrzeug-db
- kunden-db
networks:
- app-network

volumes:
kunden-db-data:
fahrzeug-db-data:

networks:
app-network:
driver: bridge

БАЗА ДАННЫХ

Код: Выделить всё

USE fahrzeugDB;

CREATE TABLE fahrzeug (
fahrzeugNr INT AUTO_INCREMENT PRIMARY KEY,
modell VARCHAR(100),
bereit BOOLEAN,
sitzAnz INT
) CHARACTER SET utf8mb4;

create user 'backend' identified by 'backend-pass';
grant select, insert, delete, update on fahrzeug to 'backend';
Я все время пытался настроить контроллер и класс обслуживания для поддержки метода GET, но возникла та же ошибка.

Подробнее здесь: https://stackoverflow.com/questions/792 ... ot-allowed
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • 405 Метод не разрешен: GET не разрешен
    Anonymous » » в форуме JAVA
    0 Ответы
    33 Просмотры
    Последнее сообщение Anonymous
  • Ошибка «Метод HTTP-кода 405 не разрешен» при использовании CURL для запроса GET
    Anonymous » » в форуме Php
    0 Ответы
    59 Просмотры
    Последнее сообщение Anonymous
  • Метод не разрешен. 405 не позволяет использовать методы post, поскольку методы get работают.
    Anonymous » » в форуме C#
    0 Ответы
    34 Просмотры
    Последнее сообщение Anonymous
  • Метод не разрешен. 405 не позволяет использовать методы post, поскольку методы get работают.
    Anonymous » » в форуме C#
    0 Ответы
    29 Просмотры
    Последнее сообщение Anonymous
  • Ошибка «Метод HTTP-кода 405 не разрешен» при использовании CURL для запроса GET
    Anonymous » » в форуме Php
    0 Ответы
    20 Просмотры
    Последнее сообщение Anonymous

Вернуться в «JAVA»