Site icon Experiences Unlimited

Configure Embedded H2 Console With Spring MVC Application

In our previous post we deployed a Spring MVC app using embedded H2 database to Tomcat. Browsing the data in an embedded DB is difficult because we cannot connect an external client to view the data.

H2 provides a Web console which we can enable and use this to browse the data as shown below:

Its a very convenient tool to write and test your queries. Enabling this as simple as adding the below code to class which implements WebApplicationInitializer or extends any implementation of WebApplicationInitializer for example AbstractAnnotationConfigDispatcherServletInitializer:

@Override
public void onStartup(ServletContext servletContext) 
  throws ServletException {
  super.onStartup(servletContext);
  ServletRegistration.Dynamic servlet = servletContext
    .addServlet("h2-console", new WebServlet());
  servlet.setLoadOnStartup(2);
  servlet.addMapping("/console/*");
}

The method onStartup is used to initialize the servlets (the task done by web.xml), so we will override this method to register the servlet exposed by H2 as shown above.

The console can be accessed from the url: http://localhost:8080/sample/console. This requires a login as shown below:

The last part of the JDBC Url jdbc:h2:mem:testdb i.e testdb is determined by the value set while you are configuring embedded H2 datasource as shown below:

@Bean
public DataSource dataSource() {
  return new EmbeddedDatabaseBuilder()
    .generateUniqueName(false)
    .setName("testdb")
    .setType(EmbeddedDatabaseType.H2)
    .addDefaultScripts()
    .setScriptEncoding("UTF-8")
    .ignoreFailedDrops(true)
    .build();
}

The DB configuration can be found here and the servlet configuration Java code can be found here

Exit mobile version