关于Servlet3.0新增特性ServletContainer

2019-02-21  本文已影响0人  呓语的风
简介
使用方式:

ServletContext增加filter或listener,容器会自动加载,可以直接使用,不需要在web.xml中配置,如果做框架就省去了配置web.xml的步骤

public class StrutsContainerInitializer implements ServletContainerInitializer {
    private static final Logger logger = 
LoggerFactory.getLogger(StrutsContainerInitializer.class);

    public void onStartup(Set<Class<?>> initializerClasses, ServletContext ctx) 
throws ServletException {
        ctx.addFilter("StrutsFilter", StrutsFilter.class);
        logger.debug("ServletContext start up with a struts filter");
                ctx.addListener(SessionListener.class); //Session监听
    }

}

使用@HandlesTypes注解后,Servlet容器会扫描到当前应用里我们自己实现的类,然后把它们放在initializerClasses集合里,这样我们就可以在容器初始化时写一些需要预加载的代码

@HandlesTypes(WebInitializer.class)
public class StrutsContainerInitializer implements ServletContainerInitializer {
    private static final Logger logger = 
LoggerFactory.getLogger(StrutsContainerInitializer.class);

    public void onStartup(Set<Class<?>> initializerClasses, ServletContext ctx) 
throws ServletException {
        if (initializerClasses == null || initializerClasses.isEmpty()) {
            logger.debug("No web initializer classes");
            return;
        }

        for (Class<?> clazz : initializerClasses) {
            try {
                ((WebInitializer) clazz.newInstance()).onStartup(ctx);
                logger.debug("WebInitializer {} started", clazz.getName());
            } catch (InstantiationException | IllegalAccessException e) {
                logger.error("WebInitializer start faild", e);
            }
        }
    }

}

有兴趣的童鞋可以亲自尝试一下。

上一篇下一篇

猜你喜欢

热点阅读