Spring Boot如何在启动时取得servletContext

小结

Sping Boot在启动的时候尝试获取servletContext的时候会返回null空,进行了一些尝试,可以在Spring Boot启动后获取servletContext。

问题

Sping Boot在启动的时候尝试获取servletContext的时候往往会返回null空,是因为servletContext还没有被初始化完成。

以下办法返回null空

SpringBeanContext servletContext = new SpringBeanContext();
servletContext.contextInitialized();
servletContext = servletContext.getServletContext();

以下自动注入Autowire也不行,

@Autowired
private ServletContext servletContext;

以下办法也是不行的,Spring Boot也没有web.xml可以配置。

servletContext servletContext = ContextLoader.getCurrentWebApplicationContext().getServletContext();

解决

尝试了等待Spring Boot启动后来获取这个ServletContext,是可以的。这里使用了springboot扩展机制 - spring factories

META-INFspring.factories中设置以下触发。

org.springframework.context.ApplicationListener=\
com.bean.TestListener

再通过以下的过程是可以取得ServletContext的:

public class TestListener implements ApplicationContextAware,
        ApplicationListener<ApplicationStartedEvent>
{
    private ApplicationContext ctx;

    @Autowired
    private ServletContext servletContext;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event)
    {
        //get the container who trigger the event
        ConfigurableApplicationContext c = event.getApplicationContext();
        if (c == ctx)
        {
            System.out.println("-----Event trigger container and listener container are the same. -----");
        }
        // add in cusomized process.
        System.out.println("========Execute customized process. =======");
    }

    // interface to inject method, and access to Spring container 
    @Override
    public void setApplicationContext(ApplicationContext ctx) throws BeansException
    {
        this.ctx = ctx;
    }
}

参考

CSDN: spring boot 获取applicationContext servletContext
CSDN: SpringBoot获取ServletContext和webApplicationConnect几种方法
CSDN: spring项目获取ServletContext
springboot2启动时执行,初始化(或定时任务)servletContext问题
CSDN: Spring Boot 定义系统启动任务
CSDN: springboot扩展机制——spring factories
CSDN: spring框架监听ServletContext启动,并加入一些属性到ServletContext
CSDN: Spring Boot 定义系统启动任务
CSDN: 第二十四节 SpringBoot使用spring.factories
Spring Boot 你不得不会的 spring.factories 配置
springboot2启动时执行,初始化(或定时任务)servletContext问题
springboot自动配置原理以及spring.factories文件的作用详解

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,可以使用拦截器来实现登录拦截器。与使用session不同,我们可以使用ServletContext来保存用户信息,以便在请求之间共享。 首先,创建一个实现HandlerInterceptor接口的拦截器类,例如: ``` @Component public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 从ServletContext中获取用户信息,如果为空则表示未登录 User user = (User) request.getServletContext().getAttribute("user"); if (user == null) { // 重定向到登录页面 response.sendRedirect("/login"); return false; } // 已登录,放行请求 return true; } } ``` 在preHandle方法中,我们从ServletContext中获取保存的用户信息,如果为空则表示未登录,此我们重定向到登录页面,并返回false阻止请求继续进行。如果用户已经登录,则返回true放行请求。 接下来,将拦截器注册到Spring Boot中。可以使用WebMvcConfigurerAdapter类的addInterceptors方法来注册拦截器,例如: ``` @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired private LoginInterceptor loginInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns("/login", "/register"); } } ``` 在addInterceptors方法中,我们将拦截器添加到InterceptorRegistry中,并指定需要拦截的路径("/**"表示所有请求),同排除登录和注册页面(避免重定向死循环)。 以上就是在Spring Boot中使用ServletContext实现登录拦截器的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值