Home » Java » Enterprise Java » Configure Embedded H2 Console With Spring MVC Application

About Mohamed Sanaulla

Mohamed Sanaulla

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

Published on Java Code Geeks with permission by Mohamed Sanaulla, partner at our JCG program. See the original article here: Configure Embedded H2 Console With Spring MVC Application

Opinions expressed by Java Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of