无法查看h2数据库的Web控制台以及如何更改默认的h2端口。

11 浏览
0 Comments

无法查看h2数据库的Web控制台以及如何更改默认的h2端口。

我对H2数据库还不熟悉。为了开发目的,我想使用H2数据库,但在将其配置到我的Spring Boot Web应用程序时遇到了问题。我已经阅读了多个教程和SO线程,但没有一个能解决我的问题。以下是我尝试过的方法,但都没有成功。

要求:

1. 我需要一个可以在Web界面上查看的H2数据库(控制台视图)。

2. 即使停止运行我的Web应用程序或甚至停止我的机器(笔记本电脑),我也希望数据持久化,这样我就不必再次输入所有数据,并可以从离开的地方继续。

3. 我希望将控制台的默认端口(8080)更改为我自己选择的端口(XXXX)。

根据H2特性页面上的信息,我尝试了使用TCP的服务器模式,但无法成功启动我的应用程序,也无法查看控制台(Web)应用程序,也无法更改默认端口为我自己选择的端口。

如果需要更多代码或其他细节以更好地理解问题,请告诉我。

0
0 Comments

问题:无法查看H2数据库的Web控制台,以及如何更改默认的H2端口。

原因:在使用Spring Security和H2数据库时,由于缺少路径配置,导致无法查看H2数据库的Web控制台。

解决方法:在WebSecurityConfigurerAdapter的子类中添加路径配置,以允许访问H2数据库的相关路径。

代码如下:

protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
    .antMatchers(HttpMethod.GET,"/h2/**").permitAll()
    .antMatchers(HttpMethod.POST,"/h2/**").permitAll()
    .anyRequest().authenticated();
    
    // to avoid X-Frame-Options header of Spring Security
    http.headers().frameOptions().disable();
}

参考文献:

- [X-Frame-Options](https://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/appendix-namespace.html#nsa-frame-options)

- [spring guru](https://springframework.guru/using-the-h2-database-console-in-spring-boot-with-spring-security/)

0
0 Comments

在使用Spring Boot时,如果无法访问H2数据库的Web控制台并且需要更改默认的H2端口,可能的原因如下所述,以及解决方法。

问题可能的原因:

- Bean配置中缺少添加"webAllowOthers"和"webPort"参数。

解决方法:

- 首先,确保正确导入所需的库。

- 在Bean配置中添加以下代码,以配置H2控制台Servlet:

import org.h2.server.web.WebServlet;
import org.springframework.boot.context.embedded.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
public class WebConfiguration {
    ServletRegistrationBean h2servletRegistration(){
        ServletRegistrationBean registration = new ServletRegistrationBean( new org.h2.server.web.WebServlet());
        registration.addUrlMappings("/h2-console/*");
        registration.addInitParameter("webAllowOthers", "true");
        registration.addInitParameter("webPort", "7777");// <-- 修改为所需的端口号
        return registration;
    }
}

- 然后,将通过URLhttp://localhost:7777/h2-console访问H2控制台。

如果问题仍然存在,可以尝试以下解决方法:

- 检查spring.datasource.url是否正确配置。

- 参考这个答案,它提供了TCP服务器和Web服务器(用于控制台访问)的配置,或许可以帮助解决问题。

0