精华内容
下载资源
问答
  • shiro的安全性当然不用说了,这里谈一谈我配置中遇到的问题:由于本地Maven仓库不给力,好多包都不匹配。 1、shiroFilter 错误  bean注入失败,最可能的是缺少jar包: 常见的是: org.apache....

    shiro的安全性当然不用说了,这里谈一谈我配置中遇到的问题:由于本地Maven仓库不给力,好多包都不匹配。

    1、shiroFilter 错误  

          bean注入失败,最可能的是缺少jar包:

         常见的是:

          org.apache.shiro.spring.LifecycleBeanPostProcessor,

         org.apache.shiro.authc.credential.HashedCredentialsMatcher,

          以及CurrentIniRealm,和UserRealm连带错误。

         解决方法:查看依赖的环境是否存在以上类的jar包。

    2、资源类注入失败:twice entity  same name resource 或 twice  * same name resource等错误是名称存在一样的

       解决方法:修改class的名称。

    转载于:https://my.oschina.net/boonya/blog/91259

    展开全文
  • 1.maven配置shiro所需要的jar <!-- shiro --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>s...

     

    1.maven中配置shiro所需要的jar

    <!-- shiro  -->
        <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>${shiro.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-ehcache</artifactId>
                <version>${shiro.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-web</artifactId>
                <version>${shiro.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>${shiro.version}</version>
            </dependency>
            <dependency>
                <groupId>com.github.theborakompanioni</groupId>
                <artifactId>thymeleaf-extras-shiro</artifactId>
                <version>2.0.0</version>
            </dependency>

    2. 在web.xml中配置   

     <filter>
            <filter-name>shiroFilter</filter-name>
            <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
            <async-supported>true</async-supported>
            <init-param>
                     <param-name>targetFilterLifecycle</param-name>
                     <param-value>true</param-value>
             </init-param>
        </filter>
        <filter-mapping>
            <filter-name>shiroFilter</filter-name>
            <url-pattern>/*</url-pattern>
         </filter-mapping>
     
        <filter>
            <filter-name>setcharacter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>setcharacter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    <!-- Shiro配置 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:spring-mvc.xml,classpath:spring-mybatis.xml,classpath:spring-shiro.xml
            </param-value>
        </context-param>

    3. SpringMVC.xml 配置

        <!-- 开启shiro注解-->
        <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
              depends-on="lifecycleBeanPostProcessor">
            <property name="proxyTargetClass" value="true" />
        </bean>
        <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
            <property name="securityManager" ref="securityManager"/>
        </bean>
    
        <!-- shiro异常跳转 -->
        <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
            <property name="exceptionMappings">
                <props>
                    <prop key="org.apache.shiro.authz.UnauthorizedException">/error/noPermissions</prop>
                    <prop key="org.apache.shiro.authz.UnauthenticatedException">/error/noPermissions</prop>
    
                </props>
            </property>
        </bean>

     

    4. 配置 spring-shiro.xml 

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
    
        <!-- 继承自AuthorizingRealm的自定义Realm,即指定Shiro验证用户登录的类为自定义的UserRealm.java -->  
        <bean id="userRealm" class="com.picc.common.UserRealm"/>
    
        <!-- Shiro默认会使用Servlet容器的Session,可通过sessionMode属性来指定使用Shiro原生Session -->  
        <!-- 即<property name="sessionMode" value="native"/>,详细说明见官方文档 -->  
        <!-- 这里主要是设置自定义的单Realm应用,若有多个Realm,可使用'realms'属性代替 -->  
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
            <property name="realm" ref="userRealm"/>
            <!-- 注入缓存管理器 -->
            <property name="cacheManager" ref="cacheManager" />
        </bean>
    
        <!-- Shiro主过滤器本身功能十分强大,其强大之处就在于它支持任何基于URL路径表达式的、自定义的过滤器的执行 -->  
        <!-- Web应用中,Shiro可控制的Web请求必须经过Shiro主过滤器的拦截,Shiro对基于Spring的Web应用提供了完美的支持 -->  
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
            <!-- Shiro的核心安全接口,这个属性是必须的 -->  
            <property name="securityManager" ref="securityManager"/>  
            <!-- 要求登录时的链接(可根据项目的URL进行替换),非必须的属性,默认会自动寻找Web工程根目录下的"/login.html"页面 -->  
            <property name="loginUrl" value="/login/login"/>  
            <!-- 登录成功后要跳转的连接 -->  
            <property name="successUrl" value="/index"/>
            <!-- 用户访问未对其授权的资源时,所显示的连接 -->  
            <!-- 若想更明显的测试此属性可以修改它的值,如unauthor.jsp,然后用[玄玉]登录后访问/admin/listUser.jsp就看见浏览器会显示unauthor.jsp -->  
        <!--     <property name="unauthorizedUrl" value="/no_permissions.jsp" /> -->
            <!-- Shiro连接约束配置,即过滤链的定义 -->  
            <!-- 此处可配合我的这篇文章来理解各个过滤连的作用http://blog.csdn.net/jadyer/article/details/12172839 -->  
            <!-- 下面value值的第一个'/'代表的路径是相对于HttpServletRequest.getContextPath()的值来的 -->  
            <!-- anon:它对应的过滤器里面是空的,什么都没做,这里.do和.jsp后面的*表示参数,比方说login.jsp?main这种 -->  
            <!-- authc:该过滤器下的页面必须验证后才能访问,它是Shiro内置的一个拦截器org.apache.shiro.web.filter.authc.FormAuthenticationFilter -->  
            <property name="filterChainDefinitions">  
                <value>
                    <!-- anon表示此地址不需要任何权限即可访问 -->      
                    /login/** = anon
                    /**/excludes/** = anon
                    /resources/** = anon 
                    /**/statics/**= anon
                    /print/** = anon
                    /** = authc	
                </value>
            </property>
        </bean>
    
        <!-- 缓存管理器 -->
        <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
            <property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml" />
        </bean>
    
        <!-- Shiro生命周期处理器 -->
        <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
        
    
        <!-- Shiro的注解配置放在spring-mvc中 -->
    
    </beans>

    5. shiro缓存XML  shiro-ehcache.xml   要不然会每次请求都要去校验权限 严重影响效率

    <ehcache updateCheck="false" name="shiroCache">
        <defaultCache
                maxElementsInMemory="10000"
                eternal="false"
                timeToIdleSeconds="120"
                timeToLiveSeconds="120"
                overflowToDisk="false"
                diskPersistent="false"
                diskExpiryThreadIntervalSeconds="120"
        />
    </ehcache>

    6. UserRealm   验证授权

    public class UserRealm extends AuthorizingRealm {
    
        private final static Logger logger = Logger.getLogger(UserRealm.class);
        
        @Autowired
        private UserService userService;
        
        @Autowired
        private BsePlatRoleService roleService;
        
        @Autowired
        private BsePlatFunctionService functionService;
        
         /**
         *  为当前登录的Subject授予角色和权限
         */
        @Override
        protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
            // TODO Auto-generated method stub
            logger.info("======用户授权认证======");
            String userName = principalCollection.getPrimaryPrincipal().toString();
            List<String> roleList = new ArrayList<String>();
            List<String> permissionList = new ArrayList<String>();
            
            try {
                User user = userService.getUserByuname(Integer.parseInt(userName));
                if (null != user) {
                     // 实体类User中包含有用户角色的实体类信息
                    if (null != user.getRoleId()) {
                         // 获取当前登录用户的角色
                        BsePlatRole role = new BsePlatRole();
                        role = roleService.selectByPrimaryKey(user.getRoleId());
                        roleList.add(role.getName());
                        // 实体类Role中包含有角色权限的实体类信息
                         List<Map<String, Object>> functionList = functionService.queryFunctionByRoleId(user.getRoleId());
                         if (null != functionList) {
                             for (int i = 0; i < functionList.size(); i++) {
                                String funFlag = functionList.get(i).get("funFlag").toString();
                                permissionList.add(funFlag);
                            }
                         }
                         
                        ShiroUtils.setSessionByKey("menus", functionList);
                    }
                }
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
            // 为当前用户设置角色和权限
            SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
            simpleAuthorizationInfo.addRoles(roleList);
            simpleAuthorizationInfo.addStringPermissions(permissionList);
            return simpleAuthorizationInfo;
        }
    
          /**
         * 验证当前登录的Subject
         * 
         * @see 经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时
         */
        @Override
        protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
            // TODO Auto-generated method stub
             logger.info("======用户登陆认证======");
            // 获取基于用户名和密码的令牌
                // 实际上这个authcToken是从AdminController里面currentUser.login(token)传过来的
                UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
                
                try {
                    User user = userService.getUserByuname(Integer.parseInt(token.getUsername()));
                    
                    if (null != user) {
                        AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), String.valueOf(user.getUser_id()));
                        this.setSession("currentUser", user);
                        return authcInfo;
                    } else {
                        return null;
                    }
                } catch (NumberFormatException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            return null;
        }
    
        
            /**
             * 将一些数据放到ShiroSession中,以便于其它地方使用
             * 
             * @see 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
             */
            private void setSession(Object key, Object value) {
                Subject currentUser = SecurityUtils.getSubject();
                if (null != currentUser) {
                    Session session = currentUser.getSession();
                    System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
                    if (null != session) {
                        session.setAttribute(key, value);
                    }
                }
            }
    }

     

    7.  添加注解即可使用了  

       @RequiresPermissions("picc.article.add")
        @RequestMapping(value = "/add.html")
        public ModelAndView articleAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {

     

    PS:

        角色表 

    功能表

      

       功能-角色 关联表

    展开全文
  • mavenshiro的整合

    千次阅读 2018-04-26 09:38:37
    前言:最近在看一些shiro 的东西,看的也不是很明白,关于shiro 的研究这里就不详解了,这里只说下shiro 在web 开发中的集成(注: 这里引用的是别人的博文) 1:首先创建maven 项目 2:配置pom.xml 添加框架依赖包 ...

    前言:最近在看一些shiro 的东西,看的也不是很明白,关于shiro 的研究这里就不详解了,这里只说下shiro 在web 开发中的集成(注: 这里引用的是别人的博文)

    1:首先创建maven 项目

    2:配置pom.xml 添加框架依赖包

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.pro.shiro.cas</groupId>
      <artifactId>shiroCas</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>shiroCas Maven Webapp</name>
      <url>http://maven.apache.org</url>
      
       <properties>
            <!-- base setting -->
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.build.locales>zh_CN</project.build.locales>
            <project.build.jdk>1.7</project.build.jdk>
    
            <!-- plugin setting -->
            <mybatis.generator.generatorConfig.xml>${basedir}/src/test/resources/generatorConfig.xml</mybatis.generator.generatorConfig.xml>
            <mybatis.generator.generatorConfig.properties>file:///${basedir}/src/test/resources/generatorConfig.properties</mybatis.generator.generatorConfig.properties>
    
            <!-- plugin versions -->
            <plugin.mybatis.generator>1.3.1</plugin.mybatis.generator>
            <plugin.maven-compiler>3.1</plugin.maven-compiler>
            <plugin.maven-surefire>2.18.1</plugin.maven-surefire>
            <skipTests>true</skipTests>
    
            <!-- lib versions -->
            <junit.version>4.11</junit.version>
            <spring.version>4.0.2.RELEASE</spring.version>
            <mybatis.version>3.2.2</mybatis.version>
            <mybatis.spring.version>1.2.2</mybatis.spring.version>
            <mysql.connector.version>5.1.30</mysql.connector.version>
            <postgresql.version>9.1-901.jdbc4</postgresql.version>
            <slf4j.version>1.6.6</slf4j.version>
            <log4j.version>1.2.12</log4j.version>
            <httpclient.version>4.1.2</httpclient.version>
            <jackson.version>1.9.13</jackson.version>
            <c3p0.version>0.9.1.2</c3p0.version>
            <druid.version>1.0.5</druid.version>
            <tomcat.jdbc.version>7.0.53</tomcat.jdbc.version>
            <jstl.version>1.2</jstl.version>
            <google.collections.version>1.0</google.collections.version>
            <cglib.version>3.1</cglib.version>
            <shiro.version>1.2.3</shiro.version>
            <commons.fileupload.version>1.3.1</commons.fileupload.version>
            <commons.codec.version>1.9</commons.codec.version>
            <commons.net.version>3.3</commons.net.version>
            <aspectj.version>1.6.12</aspectj.version>
            <netty.version>4.0.18.Final</netty.version>
            <hibernate.validator.version>5.1.1.Final</hibernate.validator.version>
        </properties>
      
      
      
      
      <dependencies>
               <!-- junit -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
    
            <!-- springframe start -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-oxm</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-jdbc</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context-support</artifactId>
                <version>${spring.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>${spring.version}</version>
            </dependency>
            <!-- springframe end -->
    
            <!-- mybatis start-->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>${mybatis.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis-spring</artifactId>
                <version>${mybatis.spring.version}</version>
            </dependency>
            <!--mybatis end-->
    
            <!-- mysql-connector -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql.connector.version}</version>
            </dependency>
    
            <!-- DruidDataSource -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>${druid.version}</version>
            </dependency>
    
            <!-- jackson -->
            <dependency>
                <groupId>org.codehaus.jackson</groupId>
                <artifactId>jackson-mapper-asl</artifactId>
                <version>${jackson.version}</version>
            </dependency>
    
            <!-- log start -->
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <!-- log end -->
    
            <!-- servlet api -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>3.0.1</version>
                <scope>provided</scope>
            </dependency>
    
            <!-- jstl -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>${jstl.version}</version>
            </dependency>
    
            <!-- start apache -->
            <dependency>
                <groupId>commons-fileupload</groupId>
                <artifactId>commons-fileupload</artifactId>
                <version>${commons.fileupload.version}</version>
            </dependency>
    
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>${httpclient.version}</version>
            </dependency>
    
            <dependency>
                <groupId>commons-codec</groupId>
                <artifactId>commons-codec</artifactId>
                <version>${commons.codec.version}</version>
            </dependency>
    
            <dependency>
                <groupId>commons-net</groupId>
                <artifactId>commons-net</artifactId>
                <version>${commons.net.version}</version>
            </dependency>
    
            <dependency>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
                <version>1.1.3</version>
            </dependency>
            <dependency>
                <groupId>commons-collections</groupId>
                <artifactId>commons-collections</artifactId>
                <version>3.2.1</version>
            </dependency>
    
            <!-- end apache -->
    
            <!-- google -->
            <dependency>
                <groupId>com.google.collections</groupId>
                <artifactId>google-collections</artifactId>
                <version>${google.collections.version}</version>
            </dependency>
    
            <!-- cglib -->
            <dependency>
                <groupId>cglib</groupId>
                <artifactId>cglib-nodep</artifactId>
                <version>${cglib.version}</version>
            </dependency>
    
    
            <!-- shiro -->
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-spring</artifactId>
                <version>${shiro.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-ehcache</artifactId>
                <version>${shiro.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-core</artifactId>
                <version>${shiro.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-web</artifactId>
                <version>${shiro.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.shiro</groupId>
                <artifactId>shiro-quartz</artifactId>
                <version>${shiro.version}</version>
            </dependency>
    
            <!-- aspectjweaver -->
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
            <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjrt</artifactId>
                <version>${aspectj.version}</version>
            </dependency>
            
              <!-- hibernate-validator -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-validator</artifactId>
                <version>${hibernate.validator.version}</version>
            </dependency>
        
      </dependencies>
      <build>
        <finalName>springShiroCas</finalName>
      </build>
    </project>
    
    

    3:配置web.xml

    <?xml version="1.0" encoding="utf-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
             id="WebApp_ID" version="3.0">
    
        <!-- Spring -->
        <!-- 配置Spring配置文件路径 -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath*:spring-*.xml
            </param-value>
        </context-param>
        <!-- 配置Spring上下文监听器 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <!-- Spring -->
    
        <!-- 配置Spring字符编码过滤器 -->
        <filter>
            <filter-name>encodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <!-- shiro 安全过滤器 -->
        <filter>
            <filter-name>shiroFilter</filter-name>
            <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
            <async-supported>true</async-supported>
            <init-param>
                <param-name>targetFilterLifecycle</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>shiroFilter</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
        <!-- 配置log4j配置文件路径 -->
        <context-param>
            <param-name>log4jConfigLocation</param-name>
            <param-value>classpath:log4j.properties</param-value>
        </context-param>
        <!-- 60s 检测日志配置 文件变化 -->
        <context-param>
            <param-name>log4jRefreshInterval</param-name>
            <param-value>60000</param-value>
        </context-param>
    
        <!-- 配置Log4j监听器 -->
        <listener>
            <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
        </listener>
    
        <!-- Spring MVC 核心控制器 DispatcherServlet 配置 -->
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath*:spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <!-- 拦截所有/rest/* 的请求,交给DispatcherServlet处理,性能最好 -->
            <url-pattern>/rest/*</url-pattern>
        </servlet-mapping>
    
        <!-- 首页 -->
        <welcome-file-list>
            <welcome-file>rest/index</welcome-file>
        </welcome-file-list>
    
        <!-- 错误页 -->
        <error-page>
            <error-code>404</error-code>
            <location>/rest/page/404</location>
        </error-page>
        <error-page>
            <error-code>500</error-code>
            <location>/rest/page/500</location>
        </error-page>
        <error-page>
            <exception-type>org.apache.shiro.authz.AuthorizationException</exception-type>
            <location>/rest/page/401</location>
        </error-page>
    
    </web-app>
    

    4、spring配置 spring-mybatis.xml:

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
           xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
           xmlns:cache="http://www.springframework.org/schema/cache"
           xsi:schemaLocation="
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/jdbc
        http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">
    
        <!-- 自动扫描quick4j包 ,将带有注解的类 纳入spring容器管理 -->
        <context:component-scan base-package="com.shiro"></context:component-scan>
    
        <!-- 引入配置文件 -->
        <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="locations">
                <list>
                    <value>classpath*:jdbc.properties</value>
                </list>
            </property>
        </bean>
    
        <!-- dataSource 配置 -->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
            <!-- 基本属性 url、user、password -->
            <property name="url" value="${jdbc.url}"/>
            <property name="username" value="${jdbc.username}"/>
            <property name="password" value="${jdbc.password}"/>
    
            <!-- 配置初始化大小、最小、最大 -->
            <property name="initialSize" value="${ds.initialSize}"/>
            <property name="minIdle" value="${ds.minIdle}"/>
            <property name="maxActive" value="${ds.maxActive}"/>
    
            <!-- 配置获取连接等待超时的时间 -->
            <property name="maxWait" value="${ds.maxWait}"/>
    
            <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
            <property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}"/>
    
            <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
            <property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}"/>
    
            <property name="validationQuery" value="SELECT 'x'"/>
            <property name="testWhileIdle" value="true"/>
            <property name="testOnBorrow" value="false"/>
            <property name="testOnReturn" value="false"/>
    
            <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
            <property name="poolPreparedStatements" value="false"/>
            <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
    
            <!-- 配置监控统计拦截的filters -->
            <property name="filters" value="stat"/>
        </bean>
    
     <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <!-- 自动扫描mapping.xml 文件 -->
            <property name="mapperLocations" value="classpath:com/shiro/dao/*.xml" />
             <!-- 开启缓存支持 -->
             <property name="configurationProperties">
                <props>
                    <prop key="cacheEnabled">true</prop>
                    <!-- 查询时,关闭关联对象即时加载以提高性能 -->
                    <prop key="lazyLoadingEnabled">false</prop>
                    <!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指定),不会加载关联表的所有字段,以提高性能 -->
                    <prop key="aggressiveLazyLoading">true</prop>
                    <!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
                    <prop key="multipleResultSetsEnabled">true</prop>
                    <!-- 允许使用列标签代替列名 -->
                    <prop key="useColumnLabel">true</prop>
                    <!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
                    <prop key="useGeneratedKeys">true</prop>
                    <!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
                    <prop key="autoMappingBehavior">FULL</prop>
                    <!-- 对于批量更新操作缓存SQL以提高性能 -->
                    <prop key="defaultExecutorType">BATCH</prop>
                    <!-- 数据库超过25000秒仍未响应则超时 -->
                    <prop key="defaultStatementTimeout">25000</prop>
                </props>
            </property>     
        </bean>
              
        <!-- spring与mybatis整合配置,扫描所有dao -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.shiro.dao"
              p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
    
        <!-- 对dataSource 数据源进行事务管理 -->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
              p:dataSource-ref="dataSource"/>
    
        <!-- 事务管理 通知 -->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <!-- 对insert,update,delete 开头的方法进行事务管理,只要有异常就回滚 -->
                <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
                <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
                <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
                <!-- select,count开头的方法,开启只读,提高数据库访问性能 -->
                <tx:method name="select*" read-only="true"/>
                <tx:method name="count*" read-only="true"/>
                <!-- 对其他方法 使用默认的事务管理 -->
                <tx:method name="*"/>
            </tx:attributes>
        </tx:advice>
    
        <!-- 事务 aop 配置 -->
        <aop:config>
            <aop:pointcut id="serviceMethods" expression="execution(* com.shiro.service..*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
        </aop:config>
    
        <!-- 配置使Spring采用CGLIB代理 -->
        <aop:aspectj-autoproxy proxy-target-class="true"/>
    
        <!-- 启用对事务注解的支持 -->
        <tx:annotation-driven transaction-manager="transactionManager"/>
    
        <!-- Cache配置 -->
        <cache:annotation-driven cache-manager="cacheManager"/>
        <bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"
              p:configLocation="classpath:ehcache.xml"/>
        <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"
              p:cacheManager-ref="ehCacheManagerFactory"/>
    </beans>
    
    
    

    5: 数据库配置文件 jdbc.properties

    ##JDBC Global Setting  
    jdbc.driver=com.mysql.jdbc.Driver  
    jdbc.url=jdbc:mysql://localhost:3306/quick4j?useUnicode=true&characterEncoding=utf-8  
    jdbc.username=root  
    jdbc.password=admin123  
      
    ##DataSource Global Setting  
      
    #配置初始化大小、最小、最大  
    ds.initialSize=1  
    ds.minIdle=1  
    ds.maxActive=20  
      
    #配置获取连接等待超时的时间   
    ds.maxWait=60000  
      
    #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒  
    ds.timeBetweenEvictionRunsMillis=60000  
      
    #配置一个连接在池中最小生存的时间,单位是毫秒  
    ds.minEvictableIdleTimeMillis=300000  
    

    6:缓存配置文件 ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?>  
    <ehcache updateCheck="false" name="txswx-ehcache">  
        <diskStore path="java.io.tmpdir"/>  
        <!-- DefaultCache setting. -->  
        <defaultCache maxEntriesLocalHeap="10000" eternal="true" timeToIdleSeconds="300" timeToLiveSeconds="600"  
                      overflowToDisk="true" maxEntriesLocalDisk="100000"/>  
    </ehcache>  
    

    7: ehcache-shiro.xml

     <ehcache updateCheck="false" name="shiroCache">
    
        <defaultCache
                maxElementsInMemory="10000"
                eternal="false"
                timeToIdleSeconds="120"
                timeToLiveSeconds="120"
                overflowToDisk="false"
                diskPersistent="false"
                diskExpiryThreadIntervalSeconds="120"
                />
    </ehcache>
    
    

    8: Shiro 配置 : spring-shiro.xml要配置realms bean

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
    
        <description>apache shiro配置</description>
    
        <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
            <property name="securityManager" ref="securityManager"/>
            <property name="loginUrl" value="/rest/page/login"/>
            <property name="successUrl" value="/rest/index"/>
            <property name="unauthorizedUrl" value="/rest/page/401"/>
            <property name="filterChainDefinitions">
                <value>
                    <!-- 静态资源允许访问 -->
                    /app/** = anon
                    /assets/** = anon
                    <!-- 登录页允许访问 -->
                    /rest/user/login = anon
                    <!-- 如果某个资源允许访问, 直接匹配成anon 即可 -->
                     <!--  /rest/user/* = anon  -->  
                     <!-- 如果某个资源需要认证,且要有相应的角色,可以直接如下设置,可以设置多个角色用逗号隔开,  有可以设置权限控制 -->   
                     <!--  也是使用注解来实现, 具体见 UserController 类 -->     
                    /rest/user/admin = authc ,roles[admin]  ,perms[user:create]         
                   <!--  /rest/user/admin = authc ,perms[user:create] -->
                     <!-- 其他资源需要认证  ,需要认证的资源 匹配成 authc-->                    
                  <!--    /** = authc -->
                </value>
            </property>
        </bean>
    
        <!-- 缓存管理器 使用Ehcache实现 -->
        <bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
            <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
        </bean>
    
        <!-- 会话DAO -->
        <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/>
    
        <!-- 会话管理器 -->
        <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
            <property name="sessionDAO" ref="sessionDAO"/>
        </bean>
    
        <!-- 安全管理器 -->
        <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
            <property name="realms">
                <list>
                <!-- 这里引用的是 com.shiro.security.SecurityRealm.java 类 -->
                    <ref bean="securityRealm"/>
                </list>
            </property>
            <!-- cacheManager,集合spring缓存工厂 -->
            <!-- <property name="cacheManager" ref="shiroEhcacheManager" /> -->
            <!-- <property name="sessionManager" ref="sessionManager" /> -->
        </bean>
    
        <!-- Shiro生命周期处理器 -->
        <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    
    </beans>
    
    

    9:Spring MVC 配置

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd 
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd 
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    
        <!-- 扫描controller(controller层注入) -->
        <context:component-scan base-package="com.shiro.controller"/>
    
        <!-- 会自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 两个bean,是spring MVC为@Controllers分发请求所必须的 -->
        <!-- 指定自己定义的validator -->
        <mvc:annotation-driven validator="validator"/>
    
        <!-- 以下 validator ConversionService 在使用 mvc:annotation-driven 会 自动注册 -->
        <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
            <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
            <!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties -->
            <property name="validationMessageSource" ref="messageSource"/>
        </bean>
    
        <!-- 国际化的消息资源文件(本系统中主要用于显示/错误消息定制) -->
        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
            <property name="basenames">
                <list>
                    <!-- 在web环境中一定要定位到classpath 否则默认到当前web应用下找 -->
                    <value>classpath:messages</value>
                    <value>classpath:org/hibernate/validator/ValidationMessages</value>
                </list>
            </property>
            <property name="useCodeAsDefaultMessage" value="false"/>
            <property name="defaultEncoding" value="UTF-8"/>
            <property name="cacheSeconds" value="60"/>
        </bean>
    
        <mvc:interceptors>
            <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor"/>
        </mvc:interceptors>
    
        <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
            <property name="defaultLocale" value="zh_CN"/>
        </bean>
    
        <!-- 支持返回json(避免IE在ajax请求时,返回json出现下载 ) -->
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
            <property name="messageConverters">
                <list>
                    <ref bean="mappingJacksonHttpMessageConverter"/>
                </list>
            </property>
        </bean>
        <bean id="mappingJacksonHttpMessageConverter"
              class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="supportedMediaTypes">
                <list>
                    <value>text/plain;charset=UTF-8</value>
                    <value>application/json;charset=UTF-8</value>
                </list>
            </property>
        </bean>
        <!-- 支持返回json -->
    
        <!-- 对模型视图添加前后缀 -->
        <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
              p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>
    
        <!-- 配置springMVC处理上传文件的信息 -->
        <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="utf-8"/>
            <property name="maxUploadSize" value="10485760000"/>
            <property name="maxInMemorySize" value="40960"/>
        </bean>
    
        <!-- 启用shrio授权注解拦截方式 -->
        <aop:config proxy-target-class="true"></aop:config>
        <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
            <property name="securityManager" ref="securityManager"/>
        </bean>
    
    </beans>
    
    
    

    10:log4j.properties

    # DEBUG,INFO,WARN,ERROR,FATAL  
    LOG_LEVEL=INFO  
      
    log4j.rootLogger=${LOG_LEVEL},CONSOLE,FILE  
      
    log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender  
    log4j.appender.CONSOLE.Encoding=utf-8  
    log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout  
    #log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{8}@(%F:%L):%m%n   
    log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm:ss} %C{1}@(%F:%L):%m%n  
      
    log4j.appender.FILE=org.apache.log4j.DailyRollingFileAppender  
    log4j.appender.FILE.File=${catalina.base}/logs/quick4j.log  
    log4j.appender.FILE.Encoding=utf-8  
    log4j.appender.FILE.DatePattern='.'yyyy-MM-dd  
    log4j.appender.FILE.layout=org.apache.log4j.PatternLayout  
    #log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout  
    log4j.appender.FILE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} %C{8}@(%F\:%L)\:%m%n   
    
    

    11: sql 文件在项目中


    12:shiro 理解

     1: 使用shiro 在访问资源的时候, 首先会通过shiro 进行过滤,具体过滤条件
    
     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
            <property name="securityManager" ref="securityManager"/>
            <!-- 如果需要权限, 然而没有登录的话,会跳转到 登录界面url /rest/page/login -->
            <property name="loginUrl" value="/rest/page/login"/>
             <!-- 登录成功后会跳转到  /rest/index-->
            <property name="successUrl" value="/rest/index"/>
            <!-- 如果没有权限的话,会跳转到 /rest/page/401 -->
            <property name="unauthorizedUrl" value="/rest/page/401"/>
            <property name="filterChainDefinitions">
                <value>
                    <!-- 静态资源允许访问 -->
                    /app/** = anon
                    /assets/** = anon
                    <!-- 登录页允许访问 -->
                    /rest/user/login = anon
                    <!-- 如果某个资源允许访问, 直接匹配成anon 即可 -->
                     <!--  /rest/user/* = anon  -->  
                     <!-- 如果某个资源需要认证,且要有相应的角色,可以直接如下设置,可以设置多个角色用逗号隔开,  有可以设置权限控制 -->   
                     <!--  也是使用注解来实现, 具体见 UserController 类 -->     
                    /rest/user/admin = authc ,roles[admin]  ,perms[user:create]         
                   <!--  /rest/user/admin = authc ,perms[user:create] -->
                     <!-- 其他资源需要认证  ,需要认证的资源 匹配成 authc-->                    
                  <!--    /** = authc -->
                </value>
            </property>
        </bean>
    
     2:用户在进行登录的时候会进行身份的验证, 具体见UserController.java
    


    作者:烟雾袅绕
    链接:https://www.jianshu.com/p/023ca8206067
    來源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
    展开全文
  • Eclipse中整合SSM+Maven+Shiro。 项目中有用到shiro,所以查了些资料搭建了个Demo,有兴趣的可以看看。 1.搭建完后项目结构 1.1 创建Maven项目 打包方式选war 2.配置文件 2.1 pom....

    Eclipse中整合SSM+Maven+Shiro。 项目中有用到shiro,所以查了些资料搭建了个Demo,有兴趣的可以看看。

    1.搭建完后项目结构


    1.1 创建Maven项目


    打包方式选war


    2.配置文件

    2.1 pom.xml

    [html] view plain copy
    1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <groupId>com.shiro.demo</groupId>
        <artifactId>shiro-demo</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>war</packaging>  
        <name>shiro-demo</name>  
        <url>http://maven.apache.org</url>  
        <dependencies>  
          <!-- shiro核心包 -->  
          <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-core</artifactId>  
            <version>1.2.5</version>  
          </dependency>  
          <!-- 添加shiro web支持 -->  
          <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-web</artifactId>  
            <version>1.2.5</version>  
          </dependency>  
          <!-- 添加shiro spring支持 -->  
          <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-spring</artifactId>  
            <version>1.2.5</version>  
          </dependency>  
          <!-- 添加sevlet支持 -->  
          <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>javax.servlet-api</artifactId>  
            <version>3.1.0</version>  
          </dependency>  
          <!-- 添加jsp支持 -->  
          <dependency>  
            <groupId>javax.servlet.jsp</groupId>  
            <artifactId>javax.servlet.jsp-api</artifactId>  
            <version>2.3.1</version>  
          </dependency>  
          <!-- 添加jstl支持 -->  
          <dependency>  
            <groupId>javax.servlet</groupId>  
            <artifactId>jstl</artifactId>  
            <version>1.2</version>  
          </dependency>  
          <!-- 添加log4j日志 -->  
          <dependency>  
            <groupId>log4j</groupId>  
            <artifactId>log4j</artifactId>  
            <version>1.2.17</version>  
          </dependency>  
          <dependency>  
            <groupId>commons-logging</groupId>  
            <artifactId>commons-logging</artifactId>  
            <version>1.2</version>  
          </dependency>  
          <dependency>  
            <groupId>org.slf4j</groupId>  
            <artifactId>slf4j-api</artifactId>  
            <version>1.7.21</version>  
          </dependency>  
        
         
      <!-- 添加spring支持 -->  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-core</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-beans</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-context-support</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-web</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-webmvc</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-tx</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-jdbc</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aop</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
          <dependency>  
            <groupId>org.springframework</groupId>  
            <artifactId>spring-aspects</artifactId>  
            <version>4.3.0.RELEASE</version>  
          </dependency>  
        
          <!-- 添加mybatis支持 -->  
          <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis</artifactId>  
            <version>3.4.0</version>  
          </dependency>  
          <dependency>  
            <groupId>org.mybatis</groupId>  
            <artifactId>mybatis-spring</artifactId>  
            <version>1.3.0</version>  
          </dependency>  
        
          <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
      <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>druid</artifactId>
         <version>1.0.18</version>
      </dependency>
          
          <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.15</version>
      </dependency>
      <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
      <version>2.2</version>
      </dependency>
      <dependency>
      <groupId>c3p0</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.1.2</version>
      </dependency>
        
          <dependency>  
            <groupId>junit</groupId>  
            <artifactId>junit</artifactId>  
            <version>4.12</version>  
            <scope>test</scope>  
          </dependency>  
        </dependencies>  
        <build>  
          <finalName>shiro</finalName>  
        </build>  
        
      </project>
    2.2 log4j.properties
    [java] view plain copy
    1. log4j.rootLogger=DEBUG, Console    
    2.   
    3. #Console    
    4. log4j.appender.Console=org.apache.log4j.ConsoleAppender    
    5. log4j.appender.Console.layout=org.apache.log4j.PatternLayout    
    6. log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n    
    7.   
    8. log4j.logger.java.sql.ResultSet=INFO    
    9. log4j.logger.org.apache=INFO    
    10. log4j.logger.java.sql.Connection=DEBUG    
    11. log4j.logger.java.sql.Statement=DEBUG    
    12. log4j.logger.java.sql.PreparedStatement=DEBUG    

    2.2.1 conf-db.properties

    datasource.driverClassName=com.mysql.jdbc.Driver
    datasource.timeBetweenEvictionRunsMillis=60000
    datasource.minEvictableIdleTimeMillis=300000
    datasource.validationQuery=SELECT 'x'
    datasource.testWhileIdle=true
    datasource.testOnBorrow=false
    datasource.testOnReturn=false
    
    datasource.url=jdbc:mysql://***.***.**.**:3306/**?useUnicode=true&characterEncoding=UTF-8
    datasource.username=****
    datasource.password=****
    datasource.initialSize=3
    datasource.minIdle=3
    datasource.maxActive=20
    datasource.maxWait=60000
    


    2.3 web.xml

    [html] view plain copy
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
    3.   <display-name>shiro-demo</display-name>  
    4.   <welcome-file-list>  
    5.     <welcome-file>index.jsp</welcome-file>  
    6.   </welcome-file-list>  
    7.   
    8.   <!-- spring监听器 -->  
    9.   <listener>  
    10.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
    11.   </listener>  
    12.   <context-param>  
    13.     <param-name>contextConfigLocation</param-name>  
    14.     <param-value>classpath:applicationContext.xml</param-value>  
    15.   </context-param>  
    16.   
    17.   <!-- 添加springmvc支持 -->  
    18.   <servlet>  
    19.     <servlet-name>springMVC</servlet-name>  
    20.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
    21.     <init-param>  
    22.         <param-name>contextConfigLocation</param-name>  
    23.         <param-value>classpath:spring-mvc.xml</param-value>  
    24.     </init-param>  
    25.   </servlet>  
    26.   <servlet-mapping>  
    27.     <servlet-name>springMVC</servlet-name>  
    28.     <url-pattern>*.do</url-pattern>  
    29.   </servlet-mapping>  
    30.   
    31.   <!-- 添加shiro过滤器 -->  
    32.   <filter>  
    33.     <filter-name>shiroFilter</filter-name>  
    34.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
    35.     <init-param>  
    36.         <!-- 该值缺省为false,表示声明周期由SpringApplicationContext管理,设置为true表示ServletContainer管理 -->  
    37.         <param-name>targetFilterLifecycle</param-name>  
    38.         <param-value>true</param-value>  
    39.     </init-param>  
    40.   </filter>  
    41.   <filter-mapping>  
    42.     <filter-name>shiroFilter</filter-name>  
    43.     <url-pattern>/*</url-pattern>  
    44.   </filter-mapping>  
    45.   
    46.   <!-- 编码过滤器 -->  
    47.   <filter>  
    48.     <filter-name>encodingFilter</filter-name>  
    49.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
    50.     <async-supported>true</async-supported>  
    51.     <init-param>  
    52.         <param-name>encoding</param-name>  
    53.         <param-value>UTF-8</param-value>  
    54.     </init-param>  
    55.   </filter>  
    56.   <filter-mapping>  
    57.     <filter-name>encodingFilter</filter-name>  
    58.     <url-pattern>/*</url-pattern>  
    59.   </filter-mapping>  
    60. </web-app>  
    2.4  applicationContext.xml(核心配置)

    [html] view plain copy
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.        xmlns:p="http://www.springframework.org/schema/p"  
    5.        xmlns:aop="http://www.springframework.org/schema/aop"  
    6.        xmlns:context="http://www.springframework.org/schema/context"  
    7.        xmlns:jee="http://www.springframework.org/schema/jee"  
    8.        xmlns:tx="http://www.springframework.org/schema/tx"  
    9.        xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
    10.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
    11.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
    12.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
    13.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  
    14.   
    15.     <!-- 自动扫描 -->  
    16.     <context:component-scan base-package="com.demo.service" />
    17.     <!-- 加载配置we -->
    18. <context:property-placeholder location="classpath*:conf*.properties"/>  
    19.   
    20.     <!--配置数据源-->  
    21.   
      	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
      		init-method="init" destroy-method="close">
      		<!--数据源驱动类可不写,Druid默认会自动根据URL识别DriverClass -->
      		<property name="driverClassName" value="${datasource.driverClassName}" />
      		<!--基本属性 url user password -->
      		<property name="url" value="${datasource.url}" />
      		<property name="username" value="${datasource.username}" />
      		<property name="password" value="${datasource.password}" />
      
      		<!--配置初始化大小、最小、最大 -->
      		<property name="initialSize" value="${datasource.initialSize}" />
      		<property name="minIdle" value="${datasource.minIdle}" />
      		<property name="maxActive" value="${datasource.maxActive}" />
      
      		<!--配置获取连接等待超时的时间 -->
      		<property name="maxWait" value="${datasource.maxWait}" />
      
      		<!--配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
      		<property name="timeBetweenEvictionRunsMillis" value="${datasource.timeBetweenEvictionRunsMillis}" />
      
      		<!--配置一个连接在池中最小生存的时间,单位是毫秒 -->
      		<property name="minEvictableIdleTimeMillis" value="${datasource.minEvictableIdleTimeMillis}" />
      
      		<property name="validationQuery" value="${datasource.validationQuery}" />
      		<property name="testWhileIdle" value="${datasource.testWhileIdle}" />
      		<property name="testOnBorrow" value="${datasource.testOnBorrow}" />
      		<property name="testOnReturn" value="${datasource.testOnReturn}" />
      		<!-- 配置监控统计拦截的filters -->
      		<property name="filters" value="stat" />
      	</bean>

    22.     <!--配置mybatis的sqlSessionFactory-->  
    23.     <bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
    24.         <property name="dataSource" ref="dataSource"/>  
    25.         <!-- 自动扫描mappers.xml文件 -->  
    26.         <property name="mapperLocations" value="classpath:demo/mappers/*.xml "/>  
    27.         <!--mybatis配置文件-->  
    28.         <property name="configLocation" value="classpath:mybatis-config.xml"/>  
    29.     </bean>  
    30.   
    31.     <!--DAO接口所在包名,spring 会自动查找其下的-->  
    32.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
    33.         <property name="basePackage" value="com.demo.dao"/>  
    34.         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>  
    35.     </bean>  
    36.   
    37.     <!--自定义Realm-->  
    38.     <bean id="myRealm" class="com.demo.realm.MyRealm"/>  
    39.   
    40.     <!--安全管理-->  
    41.     <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
    42.         <property name="realm" ref="myRealm"></property>  
    43.     </bean>  
    44.   
    45.     <!--shiro 过滤器-->  
    46.     <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
    47.         <!-- Shiro过滤器的核心安全接口,这个属性是必须的-->  
    48.         <property name="securityManager" ref="securityManager"/>  
    49.         <!--身份认证失败,则跳转到登录页面的配置-->  
    50.         <property name="loginUrl" value="/login.jsp"/>  
    51.         <!--权限认证失败,则跳转到指定页面-->  
    52.         <property name="unauthorizedUrl" value="/unauthorized.jsp"/>  
    53.         <!-- Shiro连接约束配置,即过滤链的定义-->  
    54.         <property name="filterChainDefinitions">  
    55.             <value>  
    56.                 /login=anon  
    57.                 /user/admin*=authc 
    58.                 /user/student*/**=roles[teacher]  
    59.                 /user/teacher*/**=perms["user:create"]  
    60.             </value>  
    61.         </property>  
    62.     </bean>  
    63. </beans>  

    3.整合Mybatis

    3.1全局配置文件

        首先配置一个mybatis的全局配置文件mybatis-config.xml,因为数据源都交给spring管理了,所以全局配置文件就比较清晰了。

       mybatis-config.xml

    [html] view plain copy
    1. <?xml version="1.0" encoding="UTF-8" ?>  
    2. <!DOCTYPE configuration  
    3.         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
    4.         "http://mybatis.org/dtd/mybatis-3-config.dtd">  
    5. <configuration>  
    6.     <!-- 别名 -->  
    7.     <typeAliases>  
    8.         <package name="com.demo.entity"/>  
    9.     </typeAliases>  
    10. </configuration>  
    3.2配置mapper映射文件

        UserMapper.xml

    [html] view plain copy
    1. <?xml version="1.0" encoding="UTF-8" ?>  
    2. <!DOCTYPE mapper  
    3.         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
    4.         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
    5. <mapper namespace="com.demo.entity.User">  
    6.     <select id="getByUsername" parameterType="String" resultType="user">  
    7.         select * from tb_user where username=#{username}  
    8.     </select>  
    9.   
    10.     <select id="getRoles" parameterType="String" resultType="String">  
    11.         select r.rolename  from t_user u,t_role r where u.role_id=r.id and u.username=#{username}  
    12.     </select>  
    13.   
    14.     <select id="getPermissions" parameterType="String" resultType="String">  
    15.         select p.permissionname from t_user u,t_role r,t_permission p where u.role_id=r.id and p.role_id=r.id  
    16.         and u.username=#{username}  
    17.     </select>  
    18. </mapper>  
    3.3mapper接口(UserMapper.java)

    [java] view plain copy
    1. public interface UserMapper {  
    2.     public User getByUsername(String username);  
    3.   
    4.     public Set<String> getRoles(String username);  
    5.   
    6.     public Set<String> getPermissions(String username);  
    7.   
    8. }  
        只需要写接口,不需要写实现,spring的配置文件中会去扫描mapper,会自动创建一个代理对象来执行相应的方法,要注意的是这个接口的方法名要和上面mapper映射文件的id号一样的,否则是无法映射到具体的statement上面的,会报错。


    3.4 entity类

        这里写个简单的User类

    [java] view plain copy
    1. public class User {  
    2.     private Integer  id;  
    3.     private String username;  
    4.     private String password;  
    5.     //get set方法省略  
    6.   
    7. }  
    3.5  Service
        接口UserService.java

    [java] view plain copy
    1. public interface UserService {  
    2.     public User getByUsername(String username);  
    3.   
    4.     public Set<String> getRoles(String username);  
    5.   
    6.     public Set<String> getPermissions(String username);  
    7.   
    8. }  

        UserServiceImpl.Java

    [java] view plain copy
    1. @Service  
    2. public class UserServiceImpl implements UserService {  
    3.     @Resource  
    4.     private UserMapper userDao;  
    5.     public User getByUsername(String username){  
    6.             return userDao.getByUsername(username);  
    7.     }  
    8.     public Set<String> getRoles(String username){  
    9.             return userDao.getRoles(username);  
    10.     }  
    11.     public Set<String> getPermissions(String username){  
    12.            return userDao.getPermissions(username);  
    13.     }  
    14. }  
    在service的实现类中,注入刚刚写好的dao接口即可调用其中的方法了,使用的是spring自动创建的代理对象去执行的。

    4 整合SpringMVC

    4.1配置文件

    spring-mvc.xml

    [html] view plain copy
    1. <?xml version="1.0" encoding="UTF-8"?>  
    2. <beans xmlns="http://www.springframework.org/schema/beans"  
    3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    4.        xmlns:p="http://www.springframework.org/schema/p"  
    5.        xmlns:aop="http://www.springframework.org/schema/aop"  
    6.        xmlns:context="http://www.springframework.org/schema/context"  
    7.        xmlns:jee="http://www.springframework.org/schema/jee"  
    8.        xmlns:tx="http://www.springframework.org/schema/tx"  
    9.        xsi:schemaLocation="  
    10.         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd  
    11.         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd  
    12.         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd  
    13.         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd  
    14.         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">  
    15. <!-- 使用注解的包,包括子集-->  
    16. <context:component-scan base-package="demo.controller"/>  
    17.   
    18. <!--视图解析器-->  
    19. <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
    20.     <property name="prefix" value="/"></property>  
    21.     <property name="suffix" value=".jsp"></property>  
    22. </bean>  
    23. </beans>  

    4.2 Controller

        UserController.java

    [java] view plain copy
    1. package demo.controller;  
    2.   
    3. import demo.entity.User;  
    4. import org.apache.shiro.SecurityUtils;  
    5. import org.apache.shiro.authc.UsernamePasswordToken;  
    6. import org.apache.shiro.subject.Subject;  
    7. import org.springframework.web.bind.annotation.RequestMapping;  
    8. import org.springframework.stereotype.Controller;  
    9. import javax.servlet.http.HttpServletRequest;  
    10.   
    11. @Controller  
    12. @RequestMapping("/user")  
    13. public class UserController {  
    14.     //用户登录  
    15.     @RequestMapping("/login")  
    16.     public String login(User user, HttpServletRequest request){  
    17.   
    18.         Subject subject=SecurityUtils.getSubject();  
    19.         UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());  
    20.         try {  
    21.             //调用subject.login(token)进行登录,会自动委托给securityManager,调用之前  
    22.             subject.login(token);//会跳到我们自定义的realm中  
    23.             request.getSession().setAttribute("user",user);  
    24.             return "success";  
    25.         }catch (Exception e){  
    26.             e.printStackTrace();  
    27.             request.getSession().setAttribute("user",user);  
    28.             request.setAttribute("error","用户名或密码错误");  
    29.             return "login";  
    30.         }  
    31.     }  
    32.   
    33.     @RequestMapping("/logout")  
    34.     public String logout(HttpServletRequest request){  
    35.         request.getSession().invalidate();  
    36.         return "index";  
    37.     }  
    38.   
    39.     @RequestMapping("/admin")  
    40.     public String admin(HttpServletRequest request){  
    41.         return "success";  
    42.     }  
    43.   
    44.     @RequestMapping("/student")  
    45.     public String student(HttpServletRequest request){  
    46.         return "success";  
    47.     }  
    48.   
    49.     @RequestMapping("/teacher")  
    50.     public String teacher(HttpServletRequest request){  
    51.         return "success";  
    52.     }  
    53. }  
    4.3完成自定义的realm

        上面用户登录会执行一个subject.login(token);这里会跳转到我们自定义的realm中,接下来就定义一下我们自己的realm,由于这里是和mybatis整合了,所以不需要原来的那个Dbutil去连接数据库了,直接使用mybatis中的mapper接口,也就是上面写的dao。

    [java] view plain copy
    1. public class MyRealm extends AuthorizingRealm {  
    2.     @Resource  
    3.     private UserServiceImpl userServiceImpl;  
    4.   
    5.     //为当前登录成功的用户授予权限和角色,已经登录成功了。  
    6.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
    7.         String username=(String) principals.getPrimaryPrincipal();  
    8.         SimpleAuthorizationInfo  authorizationInfo=new SimpleAuthorizationInfo();  
    9.         authorizationInfo.setRoles(userServiceImpl.getRoles(username));  
    10.         authorizationInfo.setStringPermissions(userServiceImpl.getPermissions(username));  
    11.         return authorizationInfo;  
    12.     }  
    13.     //验证当前登录的用户,获取认证信息。  
    14.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
    15.         String username=(String) token.getPrincipal();//获取用户名  
    16.         User user=userServiceImpl.getByUsername(username);  
    17.         if(user!=null){  
    18.             AuthenticationInfo authcInfo =new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(),"myRealm");  
    19.             return authcInfo;  
    20.         }else{  
    21.             return null;  
    22.         }  
    23.     }  
    24. }  
    5.几个jsp页面

    login.jsp

    [java] view plain copy
    1. <body>  
    2.     <form action="${pageContext.request.contextPath }/user/login.do" method="post">  
    3.         username:<input type="text" name="username"/><br>  
    4.         password:<input type="password" name="password"/><br>  
    5.         <input type="submit" value="登录">${error}  
    6.     </form>  
    7. </body>  

    success.jsp

    [java] view plain copy
    1. <body>  
    2.     欢迎你${user.username}  
    3.     <a href="/user/logout.do">退出</a>  
    4. </body>  

    unauthorized.jsp

    [java] view plain copy
    1. <body>  
    2.      认证未通过,或者权限不足  
    3.      <a href="${pageContext.request.contextPath}/user/login.do">退出</a>  
    4. </body>  

    6.测试

        根据spring的配置文件中对shiro的url拦截配置,我们首先请求:http://localhost:8080/shiro-demo/user/admin.do测试身份认证,然后会跳转到登录页面让我们登录,登录成功后,再次请求这个url就会进入success.jsp页面了。

        再测试角色和权限认证,可以先后输入http://localhost:8080/shiro-demo/user/student.do来测试角色认证,输入http://localhost:8080/shiro-demo/user/teacher.do来测试权限认证。通过登陆不同的用户去测试即可。


    参考这个博主的:http://blog.csdn.net/sanluo11/article/details/60581067

    展开全文
  • erp项目 基于ssm+easyUI+mysql+maven+shiro开发 本系统实现目标如下: ## 项目技术架构(Spring+SpringMVC+Mybatis) ## - Maven - Spring(IOC DI AOP 声明式事务处理) - SpringMVC(支持Restful风格) - Hibernate...
  • erp项目 基于ssm+easyUI+mysql+maven+shiro开发 本系统实现目标如下: ## 项目技术架构(Spring+SpringMVC+Mybatis) ## - Maven - Spring(IOC DI AOP 声明式事务处理) - SpringMVC(支持Restful风格) - Hibernate...
  • 说明:关于SpringMvc+maven参考之前的播客,这里直接配置1.首先在pom.xml文件中配置依赖包&lt;!--shiro start--&gt; &lt;dependency&gt; &lt;groupId&gt;org.apache.shiro&lt;/groupId...
  • 1、pom.xml文件配置: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocatio...
  • 在Eclipse中检出Shiro的官方示例,地址http://svn.apache.org/repos/asf/shiro/trunk/samples/,参考spring-hibernate项目配置。由于之前对Maven的认识不足所以今天专门配置来了解其工作机制,下面是我按照SVN上配置...
  • 1、pom.xml配置 &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="...
  • 配置shiro

    2020-05-28 16:25:12
    maven依赖 1.1 普通maven <properties> <shiro.version>1.2.4</shiro.version> </properties> <dependency> <groupId>org.apache.shiro</groupId> <...
  • Maven项目下的shiro配置

    千次阅读 2018-06-03 19:30:28
    一、认识Shiro 二、代码结构 1、代码目录: 2、pom.xml所有的依赖: &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="...http://maven.apache.o...
  • Maven+SSM+Shiro整合配置

    万次阅读 多人点赞 2017-02-18 13:22:39
    2.shiro的运行轨迹是用户登入以后,shiro会自动查询用户的角色以及权限,并将用户信息保存到session里,当用户在进行访问资源时候,会根据之前对资源权限的定义,检查用户是否具有这个权限,比如访问/allUser,访问...
  • 在springboot配置shiro

    2020-12-04 16:38:37
    一、引入maven配置 1 2 3 4 5 <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version...
  • Maven+ssm+shiro配置

    2020-04-07 17:24:36
    shiro.xml(shiro) /User/login = anon /vali-admin-3.0.0/**=anon /user/logout = logout /** = authc pom.xml 不要全部copy 看着来 4.0.0 org.xt.yzx org.xt.yzx 1.0-SNAPSHOT war org.xt.yzx Maven Webapp ...
  • 当我们在控制器方法写了 @RequiresPermissions Shiro在访问时, 就会判断有没有该权限,如果没有,就不会...2.在配置文件当中添加Shiro注解扫描 <!-- 配置为true即使用cglib继承的方式, false为jdk的接口动态...
  • SSM+shiro+maven整合配置

    千次阅读 2017-11-10 15:29:12
    整合思路第一步:整合dao层mybatis和spring整合,通过spring管理mapper接口。...使用配置方式将service接口配置在spring配置文件中。 实现事务控制。第三步:整合springmvc由于springmvc是spring的模块
  • 最近项目需要进行高要求的Web权限管理,在比较Spring security和Shiro之后由于Shiro更大的灵活度和更强的配置性选择了Shiro。 不过官方的文档写的对于集成spring不太清楚,尤其是Realm怎样实现。 因此,在查阅一...
  • 最近在做SSM(SpringMVC+Shiro+MyBatis)整合的一个项目,对于shiro配置不是特别熟练,于是想要写下来,加深一下印象。在有SpringMVC+MyBatis配置的基础上整合shiro: 首先进入shiro的官方网站...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 681
精华内容 272
关键字:

maven配置shiro