SpringBoot Accessing H2 console

Viewed 30402

I have a basic SpringBoot app., embedded Tomcat, Thymeleaf template engine. I've created this bean to access the console:

@Bean
public ServletRegistrationBean h2ConsoleServletRegistration() {
    ServletRegistrationBean bean = new ServletRegistrationBean(new WebServlet());
    bean.addUrlMappings("/console/*");
    return bean;
}

I access to the console: http://localhost:8080/appContext/console/login.do?jsessionid=f3585792a9bf1f0cf1a0b6a09dcefe1a

I have my beans annotated as follows:

@Entity
@Table(name="t_user")
public class User implements Serializable, UserDetails {
..
}

My application properties:

# Spring Data JPA properties

spring.datasource.url=jdbc:h2:mem:testdb;MODE=MySQL;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true

hibernate.dialect=org.hibernate.dialect.H2Dialect

But I don't see any table created by JPA:

enter image description here

5 Answers

We only need below configuration in application.properties file:

spring.h2.console.enabled=true

By default h2 will be available at http://localhost:8080/h2-console/

But one can define spring.h2.console.path=/h2 in application.properties and after that h2 can be accessed using http://localhost:8080/h2.

Now if you have implemented SecurityConfig in application then you will need to add

// Make H2-Console non-secured; for debug purposes
.and().csrf().ignoringAntMatchers("/h2/**")
// Allow pages to be loaded in frames from
// the same origin; needed for H2-Console
.and().headers().frameOptions().sameOrigin()

in http.authorizeRequests()

We can access the H2 console with default path as http://localhost:8080/h2-console if we have devtools dependency in pom.xml else we have to specify the path for H2 in an application.properties as below


With devtools can be accessed at http://localhost:8080/h2-console/

POM: spring-boot-starter, h2, spring-boot-starter-web, spring-boot-devtools

Without devtools - we need to set it in properties:

spring.h2.console.enabled=true 
spring.h2.console.path=/h2-console

POM: spring-boot-starter, h2, spring-boot-starter-web

This was the case for Spring Boot 2.1.1 might helpful to others

Related