关于#springboot#的问题,如何解决?

有一个任何页面都需要的参数,为了简化代码,所以我想在spring容器启动时或者加载时就执行一个带参的方法从数据库获得那个参数(只要页面加载前能得到就行),然后传到session或者其它作用域什么的,然后前端thymeleaf得到那个数据,请问该怎么弄,谢谢

可以使用Spring的InitializingBean接口或者@PostConstruct注解来实现在Spring容器启动时或者加载时执行带参方法的功能。

具体实现步骤如下:

  1. 定义一个类,实现InitializingBean接口或者在方法上添加@PostConstruct注解。

  2. 在类中注入需要的依赖,例如数据库操作的DAO或者Service。

  3. 实现afterPropertiesSet()方法或者带有@PostConstruct注解的方法,在该方法中从数据库获取需要的参数,并将参数存储到Session或者其它作用域中。

  4. 在Thymeleaf模板中使用${}表达式获取存储在Session或者其它作用域中的参数,例如${sessionScope.param}。

示例代码如下:

@Component
public class InitParam implements InitializingBean {
 
    @Autowired
    private ParamService paramService;
 
    @Autowired
    private HttpSession session;
 
    @Override
    public void afterPropertiesSet() throws Exception {
        //从数据库获取需要的参数
        String paramValue = paramService.getParamValue();
        //将参数存储到Session中
        session.setAttribute("param", paramValue);
    }
}

在Thymeleaf模板中使用${sessionScope.param}获取存储在Session中的参数。

您好,您可以通过实现ApplicationRunnerCommandLineRunner接口,在Spring容器启动后执行一些初始化或加载操作,并将得到的数据放入Session或其它作用域中。

具体实现步骤如下:

  1. 首先定义一个服务类,用于从数据库中获取所需参数:
@Service
public class AppConfigService {
    @Autowired
    private AppConfigRepository appConfigRepository;

    public AppConfig getAppConfig() {
        return appConfigRepository.getAppConfig();
    }
}

这里假设您的参数保存在AppConfig对象中,并且您已经定义了AppConfigRepository,可以从数据库中获取该对象。

  1. 接着,实现CommandLineRunnerApplicationRunner接口,并在run()方法中获取所需参数,并将其保存在Session或其它作用域中:
@Component
public class AppConfigRunner implements CommandLineRunner {
    @Autowired
    private AppConfigService appConfigService;

    @Autowired
    private HttpSession session;

    @Override
    public void run(String... args) throws Exception {
        AppConfig appConfig = appConfigService.getAppConfig();
        session.setAttribute("appConfig", appConfig);
    }
}

这里通过appConfigService获取所需参数,并将其保存在Session中,以键值对"appConfig"作为Session中的属性名。

  1. 在Thymeleaf模板中,可以通过${session.appConfig}来获取该参数值,并在页面中使用:
<body>
    <div>AppConfig参数值:${session.appConfig}</div>
</body>

这样,就可以在Spring容器启动时从数据库中获取所需参数,并将其保存在Session中,供Thymeleaf模板使用。

注意,在使用Session时,需要确保Session已经创建并且存在,否则可能会出现空指针异常。另外,还需要在application.properties文件中配置server.session.timeout属性,以保证Session的有效时间足够使用。

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 你可以看下这个问题的回答https://ask.csdn.net/questions/688790
  • 你也可以参考下这篇文章:springboot集成thymeleaf中遇到不能返回页面,只返回字符串。
  • 除此之外, 这篇博客: SpringBoot搭建一个小而美的博客中的 以上就是我在本博客中遇到的一些坑,最坑人的还是thymeleaf,弄了半天才恍然大悟过来 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:




  • 您还可以看一下 十三老师的SpringBoot实战教程:SpringBoot企业级线上商城项目讲解课程中的 Thymeleaf th 标签实践小节, 巩固相关知识点
  • 以下回答来自chatgpt:

    为了从数据库获取参数并在任何页面中使用它,可以创建一个自定义的拦截器,并将其添加到Spring的拦截器链中。

    首先,创建一个持有参数的类(例如,ParameterHolder)和一个服务类(例如,ParameterService),该服务类提供从数据库中获取参数的方法(例如,getParameter())。

    然后,在ParameterInterceptor类中创建一个preHandle()方法,获取ParameterService实例并将获取的参数存储在各种作用域(如会话)中。

    最后,在Spring的配置文件中添加拦截器和将其添加到拦截器链中的一些示例代码:

    public class ParameterInterceptor extends HandlerInterceptorAdapter {
    
        private ParameterService parameterService;
    
        @Override
        public boolean preHandle(HttpServletRequest request,
                                 HttpServletResponse response,
                                 Object handler)
                throws Exception {
    
            // get parameter from service
            ParameterHolder parameterHolder = parameterService.getParameter();
    
            // put parameter in Session
            request.getSession().setAttribute("parameter", parameterHolder);
    
            return true;
        }
    
        // getter and setter for ParameterService
    }
    
    @Configuration
    @EnableWebMvc
    public class AppConfig extends WebMvcConfigurerAdapter {
    
        @Bean
        public ParameterService parameterService() {
            return new ParameterServiceImpl();
        }
    
        @Bean
        public ParameterInterceptor parameterInterceptor() {
            return new ParameterInterceptor();
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(parameterInterceptor());
        }
    
        // other configurations ...
    }
    

    在Thymeleaf视图中,可以使用表达式访问放置在会话中的参数:

    <!DOCTYPE html>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>My Page</title>
    </head>
    <body>
    
        <h1>My Page</h1>
    
        <!-- use parameter from session -->
        <div th:text="${session.parameter.value}"></div>
    
    </body>
    </html>
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

要在Spring容器启动时或加载时执行一个带参的方法,并从数据库获取参数,在页面加载前将参数传递到前端Thymeleaf模板中,可以按照以下步骤进行:

  1. 创建一个使用@Autowired注解的Service,用于从数据库中获取参数值。例如,你可以创建一个名为"ParameterService"的类,并在其中编写获取参数值的方法。
@Service
public class ParameterService {
    public String getParameter() {
        // 从数据库中获取参数值的代码逻辑
        // 返回参数值
    }
}
  1. 在你希望在Spring容器启动或加载时执行的类(例如,实现了InitializingBean接口或使用@PostConstruct注解的类)中注入ParameterService,并调用获取参数值的方法。
@Component
public class StartupInitializer implements InitializingBean {
    @Autowired
    private ParameterService parameterService;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 调用ParameterService中的获取参数值的方法
        String parameter = parameterService.getParameter();
        // 将参数值存储到Session或其他作用域(例如ServletContext)
        // 例如:request.getSession().setAttribute("parameter", parameter);
    }
}
  1. 在Thymeleaf模板中,可以通过Thymeleaf表达式直接访问存储在Session或其他作用域中的参数值。
<p>参数值: <span th:text="${#httpServletRequest.getSession().getAttribute('parameter')}"></span></p>

在这个例子中,我们使用了#httpServletRequest对象来获取请求的Session,并使用getAttribute方法从Session中获取之前存储的参数值,然后将其显示在页面上。

这样,当Spring容器启动或加载时,会执行StartupInitializer类中的方法,从数据库获取参数值并存储到Session(或其他作用域)中,然后可以在Thymeleaf模板中通过表达式访问该参数值并进行展示。