shiro-web配置过滤器(ShrioFilter)

    <!--初始化securityManager对象所需要的环境配置-->
    <context-param>
        <param-name>shiroEnvironmentClass</param-name>
        <param-value>org.apache.shiro.web.env.IniWebEnvironment</param-value>
    </context-param>
    <context-param>
        <param-name>shiroConfigLocations</param-name>
        <param-value>classpath:shiro.ini</param-value>
    </context-param>
    <!--
        从Shiro 1.2开始引入了Environment/WebEnvironment的概念,即由它们的实现提供相应的SecurityManager及其相应的依赖。
        ShiroFilter会自动找到Environment然后获取相应的依赖。
        底层:返回反射创建shiroEnvironmentClass对象,调用其init方法.
            shiroEnvironmentClass中的init方法创建SecurityManager实例并绑定到当前运行环境
     -->
    <listener>
        <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
    </listener>


    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <!-- 拦截所有的请求 -->
        <url-pattern>/*</url-pattern>
    </filter-mapping>

----------------------------------shiro.ini---------------------------------------

[main]
#默认是/login.jsp
authc.loginUrl=/login
#用户无需要的角色时跳转的页面
roles.unauthorizedUrl=/nopermission.jsp
#用户无需要的权限时跳转的页面
perms.unauthorizedUrl=/nopermission.jsp
#登出之后重定向的页面
logout.redirectUrl=/login
[users]
admin=666,admin
zhangsan=666,deptMgr
[roles]
admin=employee:*,department:*
deptMgr=department:view
[urls]
#静态资源可以匿名访问
/static/**=anon
#访问员工列表需要身份认证及需要拥有admin角色
/employee=authc,roles[admin]
#访问部门列表需要身份认证及需要拥有department:view的权限
/department=authc,perms["department:view"]
#当请求loginOut,会被logout捕获并清除session
/loginOut=logout
#所有的请求都需要身份认证
/**=authc

----------------------------------collection处理登录操作---------------------------------------

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        //如果登录失败从 request中获取认证异常信息,shiroLoginFailure就是shiro异常类的全限定名
        String exceptionClassName = (String)req.getAttribute("shiroLoginFailure");
        
        //根据shiro返回的异常类路径判断,抛出指定异常信息
        
        if(exceptionClassName != null) {
        //基本终会抛给异常处理器
            req.setAttribute("errorMsg", "账号不存在");
        }else if(IncorrectCredentialsException.class.getName().equals(exceptionClassName)) {
            req.setAttribute("errorMsg", "用户名/密码错误");
        }else {
            req.setAttribute("errorMsg","其它异常信息");//最终在异常处理器生成未知错误
        }
        //此方法不处理登录成功(认证成功), shiro认证成功会自动跳转到上一个请求路径
        //登录失败还到login页面
        
        req.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(req, resp);
    }

猜你喜欢

转载自blog.csdn.net/qq_25635139/article/details/84784053