Spring结合Shiro进行权限控制

1.引入Shiro的Maven依赖

[html]  view plain  copy
  1. <!-- Spring 整合Shiro需要的依赖 -->  
  2.   <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>xzy</groupId>
      <artifactId>blog</artifactId>
      <packaging>war</packaging>
      <version>0.0.1-SNAPSHOT</version>
      <name>blog Maven Webapp</name>
      <url>http://maven.apache.org</url>
      <dependencies>
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>javax.servlet-api</artifactId>
       <version>3.1.0</version>
       <scope>provided</scope>
    </dependency>   
        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
       <groupId>javax.servlet</groupId>
       <artifactId>jstl</artifactId>
       <version>1.2</version>
    </dependency>  
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis</artifactId>
       <version>3.4.4</version>
    </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
       <groupId>mysql</groupId>
       <artifactId>mysql-connector-java</artifactId>
       <version>5.1.38</version>
    </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-core -->
    <dependency>
       <groupId>org.apache.shiro</groupId>
       <artifactId>shiro-core</artifactId>
       <version>1.2.2</version>
    </dependency>
         <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
       <groupId>commons-logging</groupId>
       <artifactId>commons-logging</artifactId>
       <version>1.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-context</artifactId>
       <version>4.3.8.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-webmvc</artifactId>
       <version>4.3.8.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->


    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-web -->
    <dependency>
       <groupId>org.apache.shiro</groupId>
       <artifactId>shiro-web</artifactId>
       <version>1.2.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.shiro/shiro-spring -->
    <dependency>
       <groupId>org.apache.shiro</groupId>
       <artifactId>shiro-spring</artifactId>
       <version>1.2.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
       <groupId>org.mybatis</groupId>
       <artifactId>mybatis-spring</artifactId>
       <version>1.3.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
  3. <--dbcp连接池-->
    <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-dbcp2</artifactId>
       <version>2.1.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
    <!--c3p0连接池 -->
  4. <dependency>
       <groupId>com.mchange</groupId>
       <artifactId>c3p0</artifactId>
       <version>0.9.5.2</version>
    </dependency> -->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
       <groupId>org.springframework</groupId>
       <artifactId>spring-jdbc</artifactId>
       <version>4.3.8.RELEASE</version>
    </dependency>
    <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-mongodb</artifactId>
            <version>1.10.3.RELEASE</version>
        </dependency>
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
  5. <--文件上传依赖-->
    <dependency>
       <groupId>commons-fileupload</groupId>
       <artifactId>commons-fileupload</artifactId>
       <version>1.3.2</version>
    </dependency>
      <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>1.8.4.RELEASE</version>
    </dependency>
       <!-- https://mvnrepository.com/artifact/org.springframework.session/spring-session-data-redis -->
    <dependency>
       <groupId>org.springframework.session</groupId>
       <artifactId>spring-session-data-redis</artifactId>
       <version>1.3.1.RELEASE</version>
    </dependency>
       <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
  6. <--redis实现session共享,解决nginx实现负载均衡后产生的不同tomcat服务器的数据不能共享session的数据问题-->
    <dependency>
       <groupId>redis.clients</groupId>
       <artifactId>jedis</artifactId>
       <version>2.9.0</version>
    </dependency>
      </dependencies>
      <build>
        <finalName>blog</finalName>
      </build>
    </project>
  7.    
  8.     <!-- 除此之外还有一些东西也不可少spring, spring-mvc, MyBatis等-->



2.web.xml中配置


[html]  view plain  copy
  1. <!-- 配置shiro的核心拦截器 -->  
  2.    <filter>    
  3.        <filter-name>shiroFilter</filter-name>    
  4.        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    
  5.    </filter>    
  6.    <filter-mapping>    
  7.        <filter-name>shiroFilter</filter-name>    
  8.        <url-pattern>/*</url-pattern>    
  9.    </filter-mapping>   




3.    编写自己的UserRealm类继承自Realm,主要实现认证和授权的管理操作


[java]  view plain  copy

  1. import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;


    import org.apache.shiro.authc.AuthenticationException;
    import org.apache.shiro.authc.AuthenticationInfo;
    import org.apache.shiro.authc.AuthenticationToken;
    import org.apache.shiro.authc.SimpleAuthenticationInfo;
    import org.apache.shiro.authc.UsernamePasswordToken;
    import org.apache.shiro.authz.AuthorizationInfo;
    import org.apache.shiro.authz.SimpleAuthorizationInfo;
    import org.apache.shiro.realm.AuthorizingRealm;
    import org.apache.shiro.subject.PrincipalCollection;
    import org.springframework.beans.factory.annotation.Autowired;


    import com.xzy.bean.UserDTO;
    import com.xzy.bean.UserRolePermsBean;
    import com.xzy.dao.IMongoDAO;
    import com.xzy.dao.IUserDAO;
    //extends AuthorizingRealm
    public class MyBatisRealm extends AuthorizingRealm{
  1. //面向接口编程思想
    1.  //Spring自动注入对象
    private IUserDAO userDAO;
    private IMongoDAO mongoDAO;
  1. //Spring自动注入对象

    @Autowired
    public void setMongo(IMongoDAO mongoDAO) {
    this.mongoDAO = mongoDAO;
    }


    @Autowired
    public void setUserDAO(IUserDAO userDAO) {
    this.userDAO = userDAO;
    }


    @Override
    public String getName() {
    // TODO Auto-generated method stub
    return "MyBatisRealm";
    }
    /**
    * MongoDB在用户角色权限验证中的缓存
    */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection princlpals) {
    //System.out.println("角色权限认证");
    Iterator<String > it = princlpals.iterator();
    String userName = it.next();
    //从MongoDB缓存查询用户角色权限信息
    UserRolePermsBean bean = mongoDAO.findRoleAndPerms(userName);
    Set<String> roleSet = null;
    Set<String> permsSet = null;
    if (bean==null) {
    //从MySQL数据库中查询
    String roleName = userDAO.getRoleByUserName(userName);
    if (roleName==null) {
    System.out.println("角色不存在");
    return null;
    }
    roleSet = new HashSet<String>();
    roleSet.add(roleName);
    List<String> perms = userDAO.getPermsByRoleName(roleName);
    permsSet = new HashSet<String>(perms);
    UserRolePermsBean urpBean = new UserRolePermsBean();
    urpBean.setUserName(userName);
    urpBean.setRoleSet(roleSet);
    urpBean.setPermsSet(permsSet);
    //保存角色权限数据到MongoDB中
    mongoDAO.saveRoleAndPerms(urpBean);
    }else {
    //MongoDB中有角色权限信息,直接读取
    roleSet = bean.getRoleSet();
    permsSet = bean.getPermsSet();
    }

      SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
    simpleAuthorizationInfo.setRoles(roleSet);;
    simpleAuthorizationInfo.setStringPermissions(permsSet);
    return simpleAuthorizationInfo;
    }


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
    //System.out.println("登录认证");
    UsernamePasswordToken loginToken = (UsernamePasswordToken) token;
    String userName = loginToken.getUsername();
    String userPassword = new String(loginToken.getPassword());
    UserDTO userDTO = new UserDTO();
    userDTO.setUserName(userName);
    userDTO.setUserPassword(userPassword);
    UserDTO user = userDAO.getUserByNameAndPassword(userDTO);
    if (user!=null) {
    SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getUserPassword(), getName());
    return authenticationInfo;
    }
    return null;
    }

    }


4.在web项目的web.xml中进行Shiro的相关配置


1、添加shiroFilter定义 

Xml代码   收藏代码
  1. <!DOCTYPE web-app PUBLIC
     "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
     "http://java.sun.com/dtd/web-app_2_3.dtd" >
     <web-app>
      <display-name>Archetype Created Web Application</display-name>
      <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>
      classpath:spring-shiro-web.xml,
      /WEB-INF/spring-servlet.xml
     
      </param-value>
      </context-param>
      <!-- 一个web可以有多个filter -->
      <filter>
      <filter-name>springSessionRepositoryFilter</filter-name>
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
      </filter>
      <filter>
      <filter-name>Encoding</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>
      <filter-name>shiroFilter</filter-name>
      <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
      <init-param>
      <param-name>targetFilterLifecycle</param-name>
      <param-value>true</param-value>
      </init-param>
      </filter>
      <filter-mapping>
      <filter-name>springSessionRepositoryFilter</filter-name>
      <url-pattern>/*</url-pattern>
      </filter-mapping>
      <filter-mapping>
      <filter-name>Encoding</filter-name>
      <url-pattern>/*</url-pattern>
      </filter-mapping>
      <filter-mapping>
      <filter-name>shiroFilter</filter-name>
      <url-pattern>/*</url-pattern>
      </filter-mapping>
      <!--  tomcat启动时加载spring配置文档-->
      <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <servlet>
      <servlet-name>spring</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      </servlet>
      <servlet-mapping>
      <servlet-name>spring</servlet-name>
      <url-pattern>/</url-pattern>
      </servlet-mapping>
     </web-app>

2、spring-servlet配置
Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
        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/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/data/mongo 
    http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
             http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd">
            <mvc:default-servlet-handler/>
            <mvc:annotation-driven></mvc:annotation-driven>
       <context:component-scan base-package="com.xzy.controller"></context:component-scan>
          <context:component-scan base-package="com.xzy.dao.impl"></context:component-scan>
       <!--  redis中的session管理-->  
    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
             <!-- session的生命周期 -->
             <property name="maxInactiveIntervalInSeconds" value="3600"></property>
            </bean>
            <bean id="jedisFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
             <property name="hostName" value="39.108.56.56"/>
                <property name="port" value="6379"/>
               <!--  <property name="password" value="123456"/> -->
                <property name="timeout" value="4000"/>
            </bean>
    <!-- 配置dbcp连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    <property name="url" value="jdbc:mysql://39.108.56.56:3306/blog"></property>
    <property name="username" value="root"></property>
    <property name="password" value="Xzy930903?!"></property>
    </bean>
            <!-- <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
            <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
            <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/blog"></property>
            <property name="user" value="root"></property>
            <property name="password" value="123456"></property>
            </bean> -->
            <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="mapperLocations" value="classpath:com/xzy/bean/*.xml"></property>
            </bean>
            <tx:annotation-driven transaction-manager="transactionManager"/>
            <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
            </bean>
            <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="1000000"/>
    </bean>
            <mongo:mongo-client host="39.108.56.56" port="27017">
            <mongo:client-options write-concern="NORMAL"/>
            </mongo:mongo-client>
            <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
            <constructor-arg name="mongo" ref="mongo"></constructor-arg>
            <constructor-arg name="databaseName" value="blog"></constructor-arg>
            </bean>
           
    </beans>

3、添加realm定义 ,spring-shiro-web.xml配置

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
            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">
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"></property>
    <property name="loginUrl" value="/login.jsp"></property>
    <property name="filterChainDefinitions">
           <value>
             /login.jsp=anon<!-- 不指定过滤器 -->
             /index.jsp=anon
             /*.jsp=authc<!-- 需要验证后才能访问 -->
         
           </value>
       </property>
    </bean>
     <!--  redis中的session管理-->  
    <bean class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration">
             <!-- session的生命周期 -->
             <property name="maxInactiveIntervalInSeconds" value="3600"></property>
            </bean>
            <bean id="jedisFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
             <property name="hostName" value="39.108.56.56"/>
                <property name="port" value="6379"/>
                <!-- <property name="password" value="123456"/> -->
                <property name="timeout" value="4000"/>
            </bean>
    <bean id="myRealm" class="com.xzy.realm.MyBatisRealm"></bean>
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <property name="realm" ref="myRealm"></property>
    </bean>
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    </beans>
4、配置EhCache

  <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager" />

5、保证实现了Shiro内部lifecycle函数的bean执行

<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>


特别注意:

   如果使用Shiro相关的注解,需要在springmvc-servlet.xml中配置一下信息


<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager"/>
</bean>


备注:Shiro权限管理的过滤器解释:


[java]  view plain  copy
  1. 默认过滤器(10个)   
  2. anon -- org.apache.shiro.web.filter.authc.AnonymousFilter  
  3. authc -- org.apache.shiro.web.filter.authc.FormAuthenticationFilter  
  4. authcBasic -- org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter  
  5. perms -- org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter  
  6. port -- org.apache.shiro.web.filter.authz.PortFilter  
  7. rest -- org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter  
  8. roles -- org.apache.shiro.web.filter.authz.RolesAuthorizationFilter  
  9. ssl -- org.apache.shiro.web.filter.authz.SslFilter  
  10. user -- org.apache.shiro.web.filter.authc.UserFilter  
  11. logout -- org.apache.shiro.web.filter.authc.LogoutFilter  
  12.   
  13.   
  14. anon:例子/admins/**=anon 没有参数,表示可以匿名使用。   
  15. authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数   
  16. roles:例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。   
  17. perms:例子/admins/user/**=perms[user:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。   
  18. rest:例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中method为post,get,delete等。   
  19. port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数。   
  20. authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证   
  21. ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https   
  22. user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查   


关于Shiro的标签应用:

[java]  view plain  copy
  1. <shiro:authenticated> 登录之后  
  2. <shiro:notAuthenticated> 不在登录状态时  
  3. <shiro:guest> 用户在没有RememberMe时  
  4. <shiro:user> 用户在RememberMe时  
  5. <shiro:hasAnyRoles name="abc,123" > 在有abc或者123角色时  
  6. <shiro:hasRole name="abc"> 拥有角色abc  
  7. <shiro:lacksRole name="abc"> 没有角色abc  
  8. <shiro:hasPermission name="abc"> 拥有权限abc  
  9. <shiro:lacksPermission name="abc"> 没有权限abc  
  10. <shiro:principal> 显示用户登录名  


以上是Shiro的相关配置,出于安全的考虑,一般都会使用ACL(基于角色的用户权限管理去控制用户登录后的权限)

ACL详细代码案例如下:


涉及到的表:3+2(User,Role,Permission  +  user-role,role-permission)

3张实体表+2张关系表

1.关于User类:

[java]  view plain  copy
  1. package com.jay.demo.bean;  
  2.   
  3. import java.util.HashSet;  
  4. import java.util.Set;  
  5.   
  6. public class User {  
  7.     private String id;  
  8.     private String username;  
  9.     private String password;  
  10.     private Set<Role> roleSet = new HashSet<Role>();  
  11.       
  12.     public User() {  
  13.     }  
  14.   
  15.     public String getId() {  
  16.         return id;  
  17.     }  
  18.   
  19.     public void setId(String id) {  
  20.         this.id = id;  
  21.     }  
  22.   
  23.     public String getUsername() {  
  24.         return username;  
  25.     }  
  26.   
  27.     public void setUsername(String username) {  
  28.         this.username = username;  
  29.     }  
  30.   
  31.     public String getPassword() {  
  32.         return password;  
  33.     }  
  34.   
  35.     public void setPassword(String password) {  
  36.         this.password = password;  
  37.     }  
  38.   
  39.     public Set<Role> getRoleSet() {  
  40.         return roleSet;  
  41.     }  
  42.   
  43.     public void setRoleSet(Set<Role> roleSet) {  
  44.         this.roleSet = roleSet;  
  45.     }  
  46.   
  47.       
  48. }  


2.关于Role表

[java]  view plain  copy
  1. package com.jay.demo.bean;  
  2.   
  3. import java.io.Serializable;  
  4. import java.util.HashSet;  
  5. import java.util.Set;  
  6.   
  7. public class Role implements Serializable {  
  8.   
  9.     private static final long serialVersionUID = -4987248128309954399L;  
  10.   
  11.     private Integer id;  
  12.     private String name;  
  13.     private Set<Permission> permissionSet = new HashSet<Permission>();  
  14.   
  15.     public Role() {  
  16.         super();  
  17.     }  
  18.       
  19.     // --------------------------------------------------------------------------------  
  20.   
  21.     @Override  
  22.     public int hashCode() {  
  23.         final int prime = 31;  
  24.         int result = 1;  
  25.         result = prime * result + ((id == null) ? 0 : id.hashCode());  
  26.         return result;  
  27.     }  
  28.   
  29.     @Override  
  30.     public boolean equals(Object obj) {  
  31.         if (this == obj)  
  32.             return true;  
  33.         if (obj == null)  
  34.             return false;  
  35.         if (getClass() != obj.getClass())  
  36.             return false;  
  37.         Role other = (Role) obj;  
  38.         if (id == null) {  
  39.             if (other.id != null)  
  40.                 return false;  
  41.         } else if (!id.equals(other.id))  
  42.             return false;  
  43.         return true;  
  44.     }  
  45.       
  46.     // --------------------------------------------------------------------------------  
  47.   
  48.     public Integer getId() {  
  49.         return id;  
  50.     }  
  51.   
  52.     public void setId(Integer id) {  
  53.         this.id = id;  
  54.     }  
  55.   
  56.     public String getName() {  
  57.         return name;  
  58.     }  
  59.   
  60.     public void setName(String name) {  
  61.         this.name = name;  
  62.     }  
  63.   
  64.     public Set<Permission> getPermissionSet() {  
  65.         return permissionSet;  
  66.     }  
  67.   
  68.     public void setPermissionSet(Set<Permission> permissionSet) {  
  69.         this.permissionSet = permissionSet;  
  70.     }  
  71.   
  72. }  


3.关于permission表

[java]  view plain  copy
  1. <pre name="code" class="java">package com.jay.demo.bean;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class Permission implements Serializable {  
  6.   
  7.     private static final long serialVersionUID = -8025597823572680802L;  
  8.   
  9.     private Integer id;  
  10.     private String name;  
  11.   
  12.     public Permission() {  
  13.         super();  
  14.     }  
  15.   
  16.     // --------------------------------------------------------------------------------------  
  17.   
  18.     @Override  
  19.     public int hashCode() {  
  20.         final int prime = 31;  
  21.         int result = 1;  
  22.         result = prime * result + ((id == null) ? 0 : id.hashCode());  
  23.         return result;  
  24.     }  
  25.   
  26.     @Override  
  27.     public boolean equals(Object obj) {  
  28.         if (this == obj)  
  29.             return true;  
  30.         if (obj == null)  
  31.             return false;  
  32.         if (getClass() != obj.getClass())  
  33.             return false;  
  34.         Permission other = (Permission) obj;  
  35.         if (id == null) {  
  36.             if (other.id != null)  
  37.                 return false;  
  38.         } else if (!id.equals(other.id))  
  39.             return false;  
  40.         return true;  
  41.     }  
  42.   
  43.     // --------------------------------------------------------------------------------------  
  44.   
  45.     public Integer getId() {  
  46.         return id;  
  47.     }  
  48.   
  49.     public void setId(Integer id) {  
  50.         this.id = id;  
  51.     }  
  52.   
  53.     public String getName() {  
  54.         return name;  
  55.     }  
  56.   
  57.     public void setName(String name) {  
  58.         this.name = name;  
  59.     }  
  60.   
  61. }  


 

4.dao层接口

[java]  view plain  copy
  1. package com.jay.demo.dao;  
  2.   
  3. import com.jay.demo.bean.User;  
  4.   
  5. public interface UserDao {  
  6.       
  7.     User findUserByUsername(String username);   
  8. }  


4.使用Mybatis完成的Dao层实现


[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.xzy.bean.userDTOMapper">
    <select id="getUserById" parameterType="int" resultMap="userResultMap">
    select user_name,user_account,user_password from tb_user where user_id=#{userId}
    </select>
    <select id="select" parameterType="com.xzy.bean.UserDTO" resultMap="userResultMap">
    select * from tb_user where user_name = #{userName} and user_password=#{userPassword}
    </select>

    <parameterMap type="com.xzy.bean.UserDTO" id="userParameterMap">
    <parameter property="userName"/>
    <parameter property="userPassword"/>
    </parameterMap>
    <resultMap type="com.xzy.bean.UserDTO" id="userResultMap">
    <id column="user_id" property="userId"/>
    <result column="user_name" property="userName"/>
    <result column="user_account" property="userAccount"/>
    <result column="user_password" property="userPassword"/>
    </resultMap>
    </mapper>
  2. <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.xzy.bean.roleDTOMapper">
    <resultMap type="com.xzy.bean.RoleDTO" id="roleResultMap">
    <id column="role_id" property="roleId"/>
    <result column="role_name" property="roleName"/>
    </resultMap>
    <select id="getRoleByUserName" parameterType="string" resultType="string">
    select r.role_name 
    from tb_user u join tb_ur ur on u.user_id = ur.ur_user_id
    join tb_role r on  ur_role_id = r.role_id where u.user_name = #{userName};
    </select>
    </mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xzy.bean.permsDTOMapper">
<resultMap type="com.xzy.bean.PermsDTO" id="permsResultMap">
<id column="perms_id" property="permsId"/>
<result column="perms_name" property="permsName"/>
</resultMap>
<select id="getPermsByRoleName" parameterType="string" resultType="string">
select p.perms_name from tb_role r join tb_rp rp on r.role_id=rp_role_id 
join tb_perms p on rp.rp_perms_id=p.perms_id 
where role_name=#{roleName}
</select>

</mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值