我们在开发时,更愿意使用速度更快,体积更小的H2数据库,但有时候,我们仍然想知道数据库中到底发生了什么。本文将阐述如何在开发时,使用spring-boot
内置的数据库查看工具,来实现数据库的查看。
本文环境: spring-boot:2.0.3.RELEASE
+ spring-security
增加映射
spring-boot
的数据库管理控制台的默认地址为:h2-console
。但该地址默认情况,并没有添加路由映射。也就是说,虽然org.h2.server.web.WebServlet
这个包为我们提供了web
管理界面,但是由于spring-boot
默认并没有暴露它,所以我们通过URL
找不到。解决的方法,当然是为其添加映射了。
package com.mengyunzhi.check_apply_online.config;
import org.h2.server.web.WebServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfig {
/**
* 添加h2控制台的映射地址
* @return
* @author 河北工业大学梦云智开发团队 panjie
*/
@Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/h2-console/*");
return registrationBean;
}
}
如果出现找不到WebServlet
提示,请在pom.xml
的com.h2database
依赖一项中,去除scope
属性。
启动程序,我们打开相应地址:
注意: 这里需要将jdbc url
更改为spring-boot
为我们默认创建的数据库jdbc:h2:mem:testdb
,然后点击connect
。否则,是看不到我们的数据表的。
此时,如果你也使用了spring-security
,将会得到一个空白界面,如果你没有使用,应该已经正常访问了。
添加frame
支持
空白界面是由于H2
的控制台,使用的是frame
结构,而spring-security
默认是关闭了该选项。
此时,我们应该来到spring-security
配置下,增加对frame
的支持:
package com.mengyunzhi.check_apply_online.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
static final Logger logger = LoggerFactory.getLogger(SecurityConfig.class);
@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
logger.info("设置httpSecurity:认证方式,除注册地址以外,其它授权请求.");
...
// to enable h2 web console
httpSecurity.csrf().disable();
httpSecurity.headers().frameOptions().disable();
}
}
此时,我们再次打开 h2
控制台,选择好连接的数据库后,点击连接,即可以查看和编辑H2
数据库了。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。