设为首页 收藏本站
查看: 1129|回复: 0

[经验分享] Apache Shiro学习笔记(七)EnvironmentLoaderListener

[复制链接]

尚未签到

发表于 2018-11-19 12:13:55 | 显示全部楼层 |阅读模式
鲁春利的工作笔记,好记性不如烂笔头
  

  web.xml


  Invicme
  
    org.apache.shiro.web.env.EnvironmentLoaderListener
  
  
    shiroEnvironmentClass
    org.apache.shiro.web.env.IniWebEnvironment
  
  
    shiroConfigLocations
    classpath:shiro/shiro-form-filter.ini
  
  
    ShiroFilter
    org.apache.shiro.web.servlet.ShiroFilter
  
  
    ShiroFilter
    /*
  
  
    30
  
  
    index.jsp
  
  web.xml的配置中的作用
1. 启动一个WEB项目的时候,容器(如:Tomcat)会去读它的配置文件web.xml
    读两个节点:  和
2. 紧接着,容器创建一个ServletContext(上下文),这个WEB项目所有部分都将共享这个上下文
3. 容器将转化为键值对,并交给ServletContext
4. 容器创建中的类实例,即创建监听
5. 在监听中会有contextInitialized(ServletContextEvent args)初始化方法
    在这个方法中获得ServletContext = ServletContextEvent.getServletContext();
    context-param的值 = ServletContext.getInitParameter("context-param的键");
6. 得到这个context-param的值之后,可以做一些其他操作了
  

  ShiroFilter
package org.apache.shiro.web.servlet;
import org.apache.shiro.web.env.WebEnvironment;
import org.apache.shiro.web.filter.mgt.FilterChainResolver;
import org.apache.shiro.web.util.WebUtils;
/**
* @see org.apache.shiro.web.env.EnvironmentLoader EnvironmentLoader
* @see org.apache.shiro.web.env.EnvironmentLoaderListener EnvironmentLoaderListener
* @see Apache Shiro Web Documentation
* @since 1.2
*/
public class ShiroFilter extends AbstractShiroFilter {
    /**
     * @see org.apache.shiro.web.env.EnvironmentLoaderListener
     * @since 1.2
     */
    @Override
    public void init() throws Exception {
        //
        WebEnvironment env = WebUtils.getRequiredWebEnvironment(getServletContext());
        setSecurityManager(env.getWebSecurityManager());
        FilterChainResolver resolver = env.getFilterChainResolver();
        if (resolver != null) {
            setFilterChainResolver(resolver);
        }
    }
}  

  辅助工具类WebUtils
package org.apache.shiro.web.util;
public class WebUtils {
    public static WebEnvironment getRequiredWebEnvironment(ServletContext sc)
            throws IllegalStateException {
        WebEnvironment we = getWebEnvironment(sc);
        if (we == null) {
            throw new IllegalStateException("No WebEnvironment found: no EnvironmentLoaderListener registered?");
        }
        return we;
    }
    public static WebEnvironment getWebEnvironment(ServletContext sc) {
        return getWebEnvironment(sc, EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY);
    }
    public static WebEnvironment getWebEnvironment(ServletContext sc, String attrName) {
        if (sc == null) {
            // 异常
        }
        Object attr = sc.getAttribute(attrName);
        if (attr == null) {    // 返回null(ServletContext中无该属性)
            return null;
        }
        if (attr instanceof RuntimeException) {
            // 异常
        }
        if (attr instanceof Error) {
            // 异常
        }
        if (attr instanceof Exception) {
            // 异常
        }
        if (!(attr instanceof WebEnvironment)) {
            // 异常
        }
        // 获取到实际的值
        return (WebEnvironment) attr;
    }
}  

  ServletContext中的EnvironmentLoader.ENVIRONMENT_ATTRIBUTE_KEY属性是在什么时候设置的呢?
  

  WebEnvironment的类图结构

DSC0000.jpg

  

  EnvironmentLoaderListener
package org.apache.shiro.web.env;
public class EnvironmentLoaderListener extends EnvironmentLoader implements ServletContextListener {
    // Web应用被初始化时默认调用的方法
    public void contextInitialized(ServletContextEvent sce) {
        // 调用父类EnvironmentLoader的initEnvironment方法
        initEnvironment(sce.getServletContext());
    }
    // Web应用被销毁时默认调用的方法(reload时是会调用该方法)
    public void contextDestroyed(ServletContextEvent sce) {
        destroyEnvironment(sce.getServletContext());
    }
}  

  EnvironmentLoader
package org.apache.shiro.web.env;
public class EnvironmentLoader {
    // 在web.xml文件中指定WebEnvironment的实现类
    public static final String ENVIRONMENT_CLASS_PARAM = "shiroEnvironmentClass";
    // 在web.xml文件中指定ini文件路径(不指定则默认加载/WEB-INF/shiro.ini)
    public static final String CONFIG_LOCATIONS_PARAM = "shiroConfigLocations";
    // 初始化Environment实例
    public WebEnvironment initEnvironment(ServletContext servletContext) throws IllegalStateException {
        if (servletContext.getAttribute(ENVIRONMENT_ATTRIBUTE_KEY) != null) {
            // 第一次Web应用启动时上下文中已经存在该KEY的属性,说明web.xml文件配置有问题,可能有多个EnvironmentLoader*的定义
            // 异常
        }
        // 记录日志
        servletContext.log("Initializing Shiro environment");
        log.info("Starting Shiro environment initialization.");
        // 记录当前时间
        long startTime = System.currentTimeMillis();
        try {
            // 获取WebEnvironment类的实例
            WebEnvironment environment = createEnvironment(servletContext);
            // 在ServletContext中设置KEY,设置完成后在WebUtils中就可以获取到了
            servletContext.setAttribute(ENVIRONMENT_ATTRIBUTE_KEY, environment);
            // 在日志中输出ServletContext中设置WebEnvironment耗费的时间(毫秒)
            if (log.isInfoEnabled()) {
                long elapsed = System.currentTimeMillis() - startTime;
                log.info("Shiro environment initialized in {} ms.", elapsed);
            }
            return environment;
        } catch (RuntimeException ex) {
            // 异常
        } catch (Error err) {
            // 异常
        }
    }
    // 在给定的ServletContext中设置WebEnvironment
    protected WebEnvironment createEnvironment(ServletContext sc) {
        Class clazz = determineWebEnvironmentClass(sc);
        if (!MutableWebEnvironment.class.isAssignableFrom(clazz)) {    // native方法,底层JVM实现
           // 异常
        }
        // 从ServletContext中获取shiroConfigLocations属性的值(classpath:shiro/shiro-form-filter.ini)
        String configLocations = sc.getInitParameter(CONFIG_LOCATIONS_PARAM);
        boolean configSpecified = StringUtils.hasText(configLocations);
        if (configSpecified && !(ResourceConfigurable.class.isAssignableFrom(clazz))) {
            // 异常
        }
        // 获取类的实例(ClassUtils.newInstance(clazz) ==>  return clazz.newInstance();)
        MutableWebEnvironment environment = (MutableWebEnvironment) ClassUtils.newInstance(clazz);
        // 调用父类DefaultWebEnvironment的setServletContext
        environment.setServletContext(sc);
        if (configSpecified && (environment instanceof ResourceConfigurable)) {
            // 调用父类ResourceBasedWebEnvironment的setConfigLocations
            ((ResourceConfigurable) environment).setConfigLocations(configLocations);
        }
        customizeEnvironment(environment);
        // LifecycleUtils.init中会调用environment.init方法(IniWebEnvironment.init())
        LifecycleUtils.init(environment);
        // 返回得到的WebEnvironment类的实例(IniWebEnvironment的实例)
        return environment;
    }
    // 获取WebEnvironment的Class类对象
    protected Class determineWebEnvironmentClass(ServletContext servletContext) {
        // ENVIRONMENT_CLASS_PARAM = "shiroEnvironmentClass";获取web.xml文件中声明的属性值
        String className = servletContext.getInitParameter(ENVIRONMENT_CLASS_PARAM);
        if (className != null) {
            try {
                // web.xml配置的参数对应className=org.apache.shiro.web.env.IniWebEnvironment
                return ClassUtils.forName(className);   
            } catch (UnknownClassException ex) {
                // 异常
            }
        } else {    // 如果未配置则使用该IniWebEnvironment类
            return IniWebEnvironment.class;
        }
    }
    // 空的方法体,可以实现自定义的逻辑
    protected void customizeEnvironment(WebEnvironment environment) {
        // ......
    }
}  

  





运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-636993-1-1.html 上篇帖子: LAMP_apache结合php_4 下篇帖子: Apache Shiro学习笔记(七)IniWebEnvironment
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表