admin管理员组文章数量:1430484
I am building a simple bus reservation web app with Java 21 for backend . I keep getting error 405 Method Not Allowed ( GET not supported ) , This is my current code and i test with postman
BUS CONTROLLER
package com.example.controller;
import java.util.List;
import .springframework.beans.factory.annotation.Autowired;
import .springframework.http.ResponseEntity;
import .springframework.web.bind.annotation.GetMapping;
import .springframework.web.bind.annotation.PathVariable;
import .springframework.web.bind.annotation.PostMapping;
import .springframework.web.bind.annotation.RequestBody;
import .springframework.web.bind.annotation.RequestMapping;
import .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<List<BusDTO>> getAllBuses() {
List<BusDTO> buses = busService.getAllBuses();
return ResponseEntity.ok(buses);
}
// GET: Retrieve a specific bus by ID
@GetMapping("/{id}")
public ResponseEntity<BusDTO> 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<BusDTO> createBus(@RequestBody BusDTO busDTO) {
BusDTO createdBus = busService.addBus(busDTO);
return ResponseEntity.ok(createdBus);
}
// Optional Test Endpoint
@GetMapping("/test")
public ResponseEntity<String> 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;
}
}
BUS ENTITY
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;
}
}
BUSSERVICE
package com.example.Service;
import java.util.List;
import .springframework.beans.factory.annotation.Autowired;
import .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<BusDTO> 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
DATABASE
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';
2024-11-20T11:29:35.651Z WARN 1 --- [ws2024_team_f] [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "create table bus (bus_nr bigint not null auto_increment, bereit bit not null, modell varchar(255), sitz_anz integer not null, primary key (bus_nr)) engine=InnoDB" via JDBC [CREATE command denied to user 'backend'@'172.19.0.4' for table 'bus']
.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table bus (bus_nr bigint not null auto_increment, bereit bit not null, modell varchar(255), sitz_anz integer not null, primary key (bus_nr)) engine=InnoDB" via JDBC [CREATE command denied to user 'backend'@'172.19.0.4' for table 'bus']
at .hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:94) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:583) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:523) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:323) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:80) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:240) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:119) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:280) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.spi.SchemaManagementToolCoordinator.lambda$process$5(SchemaManagementToolCoordinator.java:144) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at java.base/java.util.HashMap.forEach(HashMap.java:1429) ~[na:na]
at .hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:141) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.boot.internal.SessionFactoryObserverForSchemaExport.sessionFactoryCreated(SessionFactoryObserverForSchemaExport.java:37) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.internal.SessionFactoryObserverChain.sessionFactoryCreated(SessionFactoryObserverChain.java:35) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:322) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:457) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1506) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:75) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:390) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:366) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1802) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:337) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:335) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:954) ~[spring-context-6.1.14.jar!/:6.1.14]
at .springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:625) ~[spring-context-6.1.14.jar!/:6.1.14]
at .springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.run(SpringApplication.java:335) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.run(SpringApplication.java:1363) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.run(SpringApplication.java:1352) ~[spring-boot-3.3.5.jar!/:3.3.5]
at com.example.Ws2024TeamFApplication.main(Ws2024TeamFApplication.java:11) ~[!/:0.0.1-SNAPSHOT]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
at .springframework.boot.loader.launch.Launcher.launch(Launcher.java:102) ~[app.jar:0.0.1-SNAPSHOT]
at .springframework.boot.loader.launch.Launcher.launch(Launcher.java:64) ~[app.jar:0.0.1-SNAPSHOT]
at .springframework.boot.loader.launch.JarLauncher.main(JarLauncher.java:40) ~[app.jar:0.0.1-SNAPSHOT]
Caused by: java.sql.SQLSyntaxErrorException: CREATE command denied to user 'backend'@'172.19.0.4' for table 'bus'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:121) ~[mysql-connector-j-8.3.0.jar!/:8.3.0]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-j-8.3.0.jar!/:8.3.0]
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:770) ~[mysql-connector-j-8.3.0.jar!/:8.3.0]
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:653) ~[mysql-connector-j-8.3.0.jar!/:8.3.0]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-5.1.0.jar!/:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-5.1.0.jar!/:na]
at .hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:80) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
... 42 common frames omitted
2024-11-20T11:29:35.659Z INFO 1 --- [ws2024_team_f] [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2024-11-20T11:29:36.060Z WARN 1 --- [ws2024_team_f] [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning 2024-11-20T11:29:36.471Z WARN 1 --- [ws2024_team_f] [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: 25e64de9-731e-495b-a589-34cb7c057fe1
This generated password is for development use only. Your security configuration must be updated before running your application in production.
2024-11-20T11:29:36.496Z INFO 1 --- [ws2024_team_f] [ main] r$InitializeUserDetailsManagerConfigurer : Global AuthenticationManager configured with UserDetailsService bean with name inMemoryUserDetailsManager
2024-11-20T11:29:36.703Z INFO 1 --- [ws2024_team_f] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'
2024-11-20T11:29:36.732Z INFO 1 --- [ws2024_team_f] [ main] com.example.Ws2024TeamFApplication : Started Ws2024TeamFApplication in 4.901 seconds (process running for 5.466)
2024-11-20T11:30:20.500Z INFO 1 --- [ws2024_team_f] [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-11-20T11:30:20.501Z INFO 1 --- [ws2024_team_f] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2024-11-20T11:30:20.504Z INFO 1 --- [ws2024_team_f] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms
2024-11-20T11:30:20.716Z WARN 1 --- [ws2024_team_f] [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' is not supported]
I kept trying to adjust the controller and service class to Support GET method but the same error is emerging
I am building a simple bus reservation web app with Java 21 for backend . I keep getting error 405 Method Not Allowed ( GET not supported ) , This is my current code and i test with postman
BUS CONTROLLER
package com.example.controller;
import java.util.List;
import .springframework.beans.factory.annotation.Autowired;
import .springframework.http.ResponseEntity;
import .springframework.web.bind.annotation.GetMapping;
import .springframework.web.bind.annotation.PathVariable;
import .springframework.web.bind.annotation.PostMapping;
import .springframework.web.bind.annotation.RequestBody;
import .springframework.web.bind.annotation.RequestMapping;
import .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<List<BusDTO>> getAllBuses() {
List<BusDTO> buses = busService.getAllBuses();
return ResponseEntity.ok(buses);
}
// GET: Retrieve a specific bus by ID
@GetMapping("/{id}")
public ResponseEntity<BusDTO> 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<BusDTO> createBus(@RequestBody BusDTO busDTO) {
BusDTO createdBus = busService.addBus(busDTO);
return ResponseEntity.ok(createdBus);
}
// Optional Test Endpoint
@GetMapping("/test")
public ResponseEntity<String> 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;
}
}
BUS ENTITY
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;
}
}
BUSSERVICE
package com.example.Service;
import java.util.List;
import .springframework.beans.factory.annotation.Autowired;
import .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<BusDTO> 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
DATABASE
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';
2024-11-20T11:29:35.651Z WARN 1 --- [ws2024_team_f] [ main] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL "create table bus (bus_nr bigint not null auto_increment, bereit bit not null, modell varchar(255), sitz_anz integer not null, primary key (bus_nr)) engine=InnoDB" via JDBC [CREATE command denied to user 'backend'@'172.19.0.4' for table 'bus']
.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table bus (bus_nr bigint not null auto_increment, bereit bit not null, modell varchar(255), sitz_anz integer not null, primary key (bus_nr)) engine=InnoDB" via JDBC [CREATE command denied to user 'backend'@'172.19.0.4' for table 'bus']
at .hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:94) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:583) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:523) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:323) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:80) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:240) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:119) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:280) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.tool.schema.spi.SchemaManagementToolCoordinator.lambda$process$5(SchemaManagementToolCoordinator.java:144) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at java.base/java.util.HashMap.forEach(HashMap.java:1429) ~[na:na]
at .hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:141) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.boot.internal.SessionFactoryObserverForSchemaExport.sessionFactoryCreated(SessionFactoryObserverForSchemaExport.java:37) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.internal.SessionFactoryObserverChain.sessionFactoryCreated(SessionFactoryObserverChain.java:35) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:322) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:457) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1506) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
at .springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:75) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:390) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:366) ~[spring-orm-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1853) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1802) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:600) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:522) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:337) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:335) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:205) ~[spring-beans-6.1.14.jar!/:6.1.14]
at .springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:954) ~[spring-context-6.1.14.jar!/:6.1.14]
at .springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:625) ~[spring-context-6.1.14.jar!/:6.1.14]
at .springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.refreshContext(SpringApplication.java:456) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.run(SpringApplication.java:335) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.run(SpringApplication.java:1363) ~[spring-boot-3.3.5.jar!/:3.3.5]
at .springframework.boot.SpringApplication.run(SpringApplication.java:1352) ~[spring-boot-3.3.5.jar!/:3.3.5]
at com.example.Ws2024TeamFApplication.main(Ws2024TeamFApplication.java:11) ~[!/:0.0.1-SNAPSHOT]
at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:580) ~[na:na]
at .springframework.boot.loader.launch.Launcher.launch(Launcher.java:102) ~[app.jar:0.0.1-SNAPSHOT]
at .springframework.boot.loader.launch.Launcher.launch(Launcher.java:64) ~[app.jar:0.0.1-SNAPSHOT]
at .springframework.boot.loader.launch.JarLauncher.main(JarLauncher.java:40) ~[app.jar:0.0.1-SNAPSHOT]
Caused by: java.sql.SQLSyntaxErrorException: CREATE command denied to user 'backend'@'172.19.0.4' for table 'bus'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:121) ~[mysql-connector-j-8.3.0.jar!/:8.3.0]
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-j-8.3.0.jar!/:8.3.0]
at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:770) ~[mysql-connector-j-8.3.0.jar!/:8.3.0]
at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:653) ~[mysql-connector-j-8.3.0.jar!/:8.3.0]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-5.1.0.jar!/:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-5.1.0.jar!/:na]
at .hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:80) ~[hibernate-core-6.5.3.Final.jar!/:6.5.3.Final]
... 42 common frames omitted
2024-11-20T11:29:35.659Z INFO 1 --- [ws2024_team_f] [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default' 2024-11-20T11:29:36.060Z WARN 1 --- [ws2024_team_f] [ main] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning 2024-11-20T11:29:36.471Z WARN 1 --- [ws2024_team_f] [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: 25e64de9-731e-495b-a589-34cb7c057fe1
This generated password is for development use only. Your security configuration must be updated before running your application in production.
2024-11-20T11:29:36.496Z INFO 1 --- [ws2024_team_f] [ main] r$InitializeUserDetailsManagerConfigurer : Global AuthenticationManager configured with UserDetailsService bean with name inMemoryUserDetailsManager
2024-11-20T11:29:36.703Z INFO 1 --- [ws2024_team_f] [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port 8080 (http) with context path '/'
2024-11-20T11:29:36.732Z INFO 1 --- [ws2024_team_f] [ main] com.example.Ws2024TeamFApplication : Started Ws2024TeamFApplication in 4.901 seconds (process running for 5.466)
2024-11-20T11:30:20.500Z INFO 1 --- [ws2024_team_f] [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-11-20T11:30:20.501Z INFO 1 --- [ws2024_team_f] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2024-11-20T11:30:20.504Z INFO 1 --- [ws2024_team_f] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet : Completed initialization in 3 ms
2024-11-20T11:30:20.716Z WARN 1 --- [ws2024_team_f] [nio-8080-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' is not supported]
I kept trying to adjust the controller and service class to Support GET method but the same error is emerging
Share Improve this question edited Nov 20, 2024 at 11:34 iheb khemila asked Nov 19, 2024 at 14:02 iheb khemilaiheb khemila 11 bronze badge 7- 1 How are you hitting the API ? – Harsh Commented Nov 19, 2024 at 14:09
- I am using Postman with the following Details : Method : GET localhost:8082/api/buses Basic Authorization with user/passkey – iheb khemila Commented Nov 19, 2024 at 14:13
- Please confirm if you cleaned and rebuilt your docker image after making the change. As of current state, your code should work. Infact I would advise you to run your application outside the container and check if its working. You can remove its relation with database and try again. Keep trying till you get a very simple code which is still not working. – Anubhav Sharma Commented Nov 19, 2024 at 20:57
- Method not allowed, ideally means you are trying to invoke the correct endpoint, however with a wrong REST Action type, for e.g. hitting the right endpoint of GET but selecting POST or any other from postman , just ensure that is not the case – Harsh Commented Nov 20, 2024 at 4:22
- provide the snippet of the error that you are getting on console if u are using spring security use logging.level..springframework.security=DEBUG for debugging – Naren D Commented Nov 20, 2024 at 7:07
1 Answer
Reset to default 0Method Not Allowed basically comes when you have different method in Controller and accessing using different method in URL. So make sure that whatever method you are using in endpoint the same method should be use in URL.
@RestController
@RequestMapping("/api/buses")
public class BusController {
@GetMapping
public ResponseEntity<List<BusDTO>> getAllBuses() {
List<BusDTO> buses = busService.getAllBuses();
return ResponseEntity.ok(buses);
}
}
Test with Postman :
<base_url>/api/buses => Make sure above endpoint should be used with GET mapping method only
本文标签: java405 Method Not AllowedGET not allowedStack Overflow
版权声明:本文标题:java - 405 Method Not Allowed : GET not allowed - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745556609a2663225.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论