SSM+shiro整合

效果图:



简介

1.shiro是用于权限控制还有对密码加密的框架,同时可以控制尝试登入次数,超出将对用户锁定

2.shiro的运行轨迹是用户登入以后,shiro会自动查询用户的角色以及权限,并将用户信息保存到session里,当用户在进行访问资源时候,会根据之前对资源权限的定义,检查用户是否具有这个权限,比如访问/allUser,访问需要admin的角色,shiro会根据登入用户的信息,检查用户是否具有admin的角色

3.shiro1.2提供了passwordService,对密码加密更加方便

4.shiro的shiroFilter配置,如果是访问其他已存在的页面被拦截到登录页面,登录后就会跳转到之前的页面;如果是直接访问登录页面或者是通过退出登录到登录页面,再次登录就会跳转到“/”

5.Spring MVC的json传输,可以自动的根据属性名称,将json和对象自动转换

6.实例环境的搭建 http://blog.csdn.net/zzhao114/article/details/54958339

7.实例用到的mybatis多表联立 http://blog.csdn.net/zzhao114/article/details/55106270

8.实例  http://download.csdn.net/download/zzhao114/9757441

(http://download.csdn.net/download/zzhao114/9936992  这个加入了数据库还有简单的文档)


遇到的问题及解决

1.shiro定义的权限控制无效的问题

在web.xml中需要将shiro的配置放在是Spring MVC的配置之前,shiro的过滤集为<url-pattern>/*</url-pattern>,Spring MVC的过滤集为<url-pattern>/</url-pattern>

2.使用shiro加密,用户登入密码匹配一直不成功问题

自定义的userRealm,不能通过注释的方式自动注册bean,不然不能讲使用passwordService的加密方式对密码正确的匹配,需要在配置文件里配置

  1. <!– 注册自定义的Realm,并把密码匹配器注入,使用注解的方式自动注解会无法正确匹配密码 –>  
  2.     <bean id=“userRealm” class=“com.shiro.UserRealm”>  
  3.         <property name=“credentialsMatcher” ref=“passwordMatcher”/>  
  4.         <property name=“cachingEnabled” value=“false”/>  
  5.     </bean>  
<!-- 注册自定义的Realm,并把密码匹配器注入,使用注解的方式自动注解会无法正确匹配密码 -->
    <bean id="userRealm" class="com.shiro.UserRealm">
        <property name="credentialsMatcher" ref="passwordMatcher"/>
        <property name="cachingEnabled" value="false"/>
    </bean>

3.shiro的注解无效问题

需要在Spring MVC的配置文件中启动shiro注解

  1. <!–启用shiro注解 –>  
  2.     <bean  
  3.         class=“org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator”  
  4.         depends-on=“lifecycleBeanPostProcessor”>  
  5.         <property name=“proxyTargetClass” value=“true” />  
  6.     </bean>  
  7.     <bean  
  8.         class=“org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor”>  
  9.         <property name=“securityManager” ref=“securityManager” />  
  10.     </bean>  
<!--启用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>

4.使用注解后,无权限异常的问题

如果没有对资源的访问权限,并不是跳转到在shiro配置文件中的<property name=”unauthorizedUrl” value=”/unauthorized” />设置的url,而是抛出无权限的异常,需要在Spring MVC的配置文件中加入即可解决

  1. <!– shiro为集成springMvc 拦截异常,使用注解时无权限的跳转 –>  
  2.     <bean  
  3.         class=“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”>  
  4.         <property name=“exceptionMappings”>  
  5.             <props>  
  6.                 <!– 这里你可以根据需要定义N多个错误异常转发 –>  
  7.                 <prop key=“org.apache.shiro.authz.UnauthorizedException”>redirect:/unauthorized</prop>  
  8.                 <prop key=“org.apache.shiro.authz.UnauthenticatedException”>redirect:/unauthorized</prop>  
  9.                 <prop key=“java.lang.IllegalArgumentException”>/error</prop>  <!– 参数错误(bizError.jsp) –>  
  10.                 <prop key=“java.lang.Exception”>/error</prop>  <!– 其他错误为’未定义错误’(unknowError.jsp) –>  
  11.             </props>  
  12.         </property>  
  13.     </bean>  
<!-- shiro为集成springMvc 拦截异常,使用注解时无权限的跳转 -->
    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!-- 这里你可以根据需要定义N多个错误异常转发 -->
                <prop key="org.apache.shiro.authz.UnauthorizedException">redirect:/unauthorized</prop>
                <prop key="org.apache.shiro.authz.UnauthenticatedException">redirect:/unauthorized</prop>
                <prop key="java.lang.IllegalArgumentException">/error</prop>  <!-- 参数错误(bizError.jsp) -->
                <prop key="java.lang.Exception">/error</prop>  <!-- 其他错误为'未定义错误'(unknowError.jsp) -->
            </props>
        </property>
    </bean>

5.对静态资源设置不须任何权限的问题

需要同时在Spring MVC和shiro的配置文件中配置。

Spring MVC:

  1. <!– 静态资源访问(不拦截此目录下的东西的访问) –>  
  2.     <mvc:resources location=“/js/” mapping=“/js/**” />  
  3.     <mvc:resources location=“/icon/” mapping=“/icon/**” />  
<!-- 静态资源访问(不拦截此目录下的东西的访问) -->
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/icon/" mapping="/icon/**" />
Shiro:

  1. /icon/**=anon  
  2. /js/**=anon  
/icon/**=anon
/js/**=anon

6.shiro中的successUrl不生效的问题

successUrl配置只是做为一种附加配置,只有session中没有用户请求地址时才会使用successUrl。系统默认的是认证成功后跳转到上一次请求的路径,如果是首次请求,那shiro就会跳转到默认虚拟路径“/”,也就是跳转到index.jsp。

7.使用json问题

需要在Spring MVC加入json转换器

  1. <!– 启动SpringMVC的注解功能,完成请求和注解POJO的映射 –>  
  2.     <bean  
  3.         class=“org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”>  
  4.         <property name=“messageConverters”>  
  5.             <list>  
  6.                 <ref bean=“jsonMapping” />     <!– JSON转换器 –>  
  7.             </list>  
  8.         </property>  
  9.     </bean>  
  10.   
  11.     <!–避免IE执行AJAX时,返回JSON出现下载文件 –>  
  12.     <bean id=“jsonMapping”  
  13.         class=“org.springframework.http.converter.json.MappingJacksonHttpMessageConverter”>  
  14.         <property name=“supportedMediaTypes”>  
  15.             <list>  
  16.                 <value>text/html;charset=gbk</value>  
  17.             </list>  
  18.         </property>  
  19.     </bean>  
<!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonMapping" />     <!-- JSON转换器 -->
            </list>
        </property>
    </bean>

    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="jsonMapping"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=gbk</value>
            </list>
        </property>
    </bean>
需要的jar包:

  1. <!– 映入JSON –>  
  2.         <dependency>  
  3.             <groupId>org.codehaus.jackson</groupId>  
  4.             <artifactId>jackson-mapper-asl</artifactId>  
  5.             <version>1.9.13</version>  
  6.         </dependency>  
<!-- 映入JSON -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>


拓展

1.登入的几种异常

  1. try {  
  2.             subject.login(token);  
  3.         } catch (UnknownAccountException uae) {  
  4.             logger.info(”用户名为【” + token.getPrincipal() + “】不存在”);  
  5.         } catch (IncorrectCredentialsException ice) {  
  6.             logger.info(”用户名为【 ” + token.getPrincipal() + “ 】密码错误!”);  
  7.         } catch (LockedAccountException lae) {  
  8.             logger.info(”用户名为【” + token.getPrincipal() + “ 】的账户锁定,请联系管理员。”);  
  9.         } catch (DisabledAccountException dax) {  
  10.             logger.info(”用户名为:【” + token.getHost() + “】用户已经被禁用.”);  
  11.         } catch (ExcessiveAttemptsException eae) {  
  12.             logger.info(”用户名为:【” + token.getHost() + “】的用户登录次数过多,有暴力破解的嫌疑.”);  
  13.         } catch (ExpiredCredentialsException eca) {  
  14.             logger.info(”用户名为:【” + token.getHost() + “】用户凭证过期.”);  
  15.         } catch (AuthenticationException ae) {  
  16.             logger.info(”用户名为:【” + token.getHost() + “】用户验证失败.”);  
  17.         } catch (Exception e) {  
  18.             logger.info(”别的异常信息。。。。具体查看继承关系”);  
  19.         }  
try {
            subject.login(token);
        } catch (UnknownAccountException uae) {
            logger.info("用户名为【" + token.getPrincipal() + "】不存在");
        } catch (IncorrectCredentialsException ice) {
            logger.info("用户名为【 " + token.getPrincipal() + " 】密码错误!");
        } catch (LockedAccountException lae) {
            logger.info("用户名为【" + token.getPrincipal() + " 】的账户锁定,请联系管理员。");
        } catch (DisabledAccountException dax) {
            logger.info("用户名为:【" + token.getHost() + "】用户已经被禁用.");
        } catch (ExcessiveAttemptsException eae) {
            logger.info("用户名为:【" + token.getHost() + "】的用户登录次数过多,有暴力破解的嫌疑.");
        } catch (ExpiredCredentialsException eca) {
            logger.info("用户名为:【" + token.getHost() + "】用户凭证过期.");
        } catch (AuthenticationException ae) {
            logger.info("用户名为:【" + token.getHost() + "】用户验证失败.");
        } catch (Exception e) {
            logger.info("别的异常信息。。。。具体查看继承关系");
        }

2.filterChainDefinitions的解释

  1. <property name=“filterChainDefinitions”>        
  2.             <value>        
  3.                 <!– anon表示此地址不需要任何权限即可访问 –>      
  4.                 /static/**=anon      
  5.                 <!– perms[user:query]表示访问此连接需要权限为user:query的用户 –>      
  6.                 /user=perms[user:query]      
  7.                 <!– roles[manager]表示访问此连接需要用户的角色为manager –>      
  8.                 /user/add=roles[manager]      
  9.                 /user/del/**=roles[admin]      
  10.                 /user/edit/**=roles[manager]      
  11.                 <!–所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login–>        
  12.                 /** = authc      
  13.             </value>        
  14.         </property>   
<property name="filterChainDefinitions">      
            <value>      
                <!-- anon表示此地址不需要任何权限即可访问 -->    
                /static/**=anon    
                <!-- perms[user:query]表示访问此连接需要权限为user:query的用户 -->    
                /user=perms[user:query]    
                <!-- roles[manager]表示访问此连接需要用户的角色为manager -->    
                /user/add=roles[manager]    
                /user/del/**=roles[admin]    
                /user/edit/**=roles[manager]    
                <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login-->      
                /** = authc    
            </value>      
        </property> 

3.shiro在jsp页面的用法

配置:

  1. <%@ taglib prefix=“shiro” uri=“http://shiro.apache.org/tags” %>  
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
用法:
  1. <shiro:authenticated>用户已经登录显示此内容</shiro:authenticated>      
  2.     <shiro:hasRole name=“manager”>manager角色登录显示此内容</shiro:hasRole>      
  3.     <shiro:hasRole name=“admin”>admin角色登录显示此内容</shiro:hasRole>      
  4.     <shiro:hasRole name=“normal”>normal角色登录显示此内容</shiro:hasRole>            
  5.     <shiro:hasAnyRoles name=“manager,admin”>** manager or admin 角色用户登录显示此内容**</shiro:hasAnyRoles>      
  6.     <shiro:principal/>显示当前登录用户名      
  7.     <shiro:hasPermission name=“add”>add权限用户显示此内容</shiro:hasPermission>      
  8.     <shiro:hasPermission name=“user:query”>query权限用户显示此内容<shiro:principal/></shiro:hasPermission>      
  9.     <shiro:lacksPermission name=“user:del”> 不具有user:del权限的用户显示此内容 </shiro:lacksPermission>   
<shiro:authenticated>用户已经登录显示此内容</shiro:authenticated>    
    <shiro:hasRole name="manager">manager角色登录显示此内容</shiro:hasRole>    
    <shiro:hasRole name="admin">admin角色登录显示此内容</shiro:hasRole>    
    <shiro:hasRole name="normal">normal角色登录显示此内容</shiro:hasRole>          
    <shiro:hasAnyRoles name="manager,admin">** manager or admin 角色用户登录显示此内容**</shiro:hasAnyRoles>    
    <shiro:principal/>显示当前登录用户名    
    <shiro:hasPermission name="add">add权限用户显示此内容</shiro:hasPermission>    
    <shiro:hasPermission name="user:query">query权限用户显示此内容<shiro:principal/></shiro:hasPermission>    
    <shiro:lacksPermission name="user:del"> 不具有user:del权限的用户显示此内容 </shiro:lacksPermission> 

具体的配置:

数据库:

user:id、username、password

mapping_UR:userid(FK:user.id)、roleid(FK:role.id)

role:id、name
mapping_RP:roleid(FK:role.id)、permissionid(FK:permission.id)

permission:id、pname

spring-shiro

  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <beans xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  3.     xmlns=“http://www.springframework.org/schema/beans” xmlns:util=“http://www.springframework.org/schema/util”  
  4.     xmlns:context=“http://www.springframework.org/schema/context” xmlns:p=“http://www.springframework.org/schema/p”  
  5.     xmlns:tx=“http://www.springframework.org/schema/tx” xmlns:mvc=“http://www.springframework.org/schema/mvc”  
  6.     xmlns:aop=“http://www.springframework.org/schema/aop”  
  7.     xsi:schemaLocation=”http://www.springframework.org/schema/beans  
  8.     http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx  
  9.     http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context  
  10.     http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc  
  11.     http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop  
  12.     http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/util   
  13.     http://www.springframework.org/schema/util/spring-util.xsd”>  
  14.       
  15.     <!– 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 –>  
  16.     <bean id=“shiroFilter” class=“org.apache.shiro.spring.web.ShiroFilterFactoryBean”>  
  17.         <!– 调用我们配置的权限管理器 –>  
  18.         <property name=“securityManager” ref=“securityManager” />  
  19.         <!– 配置我们的登录请求地址 –>  
  20.         <property name=“loginUrl” value=“/login.jsp” />  
  21.         <!– 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 –>  
  22.         <property name=“successUrl” value=“/Adduser.jsp” />  
  23.         <!– 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 –>  
  24.         <property name=“unauthorizedUrl” value=“/unauthorized” />  
  25.         <property name=“filters”>  
  26.             <util:map>  
  27.                 <entry key=“logout” value-ref=“logoutFilter” />  
  28.             </util:map>  
  29.         </property>  
  30.         <!– 权限配置 –>  
  31.         <property name=“filterChainDefinitions”>  
  32.             <value>  
  33.                 <!– anon表示此地址不需要任何权限即可访问 –>  
  34.                 /login=anon  
  35.                 /icon/**=anon  
  36.                 /js/**=anon  
  37.                 /logout=logout  
  38.                 <!–所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login –>  
  39.                 /** = authc  
  40.             </value>  
  41.         </property>  
  42.     </bean>  
  43.     <bean id=“logoutFilter” class=“org.apache.shiro.web.filter.authc.LogoutFilter”>  
  44.         <property name=“redirectUrl” value=“/login.jsp” />  
  45.     </bean>  
  46.   
  47.     <!– 凭证匹配器 –>  
  48.     <bean id=“passwordMatcher” class=“org.apache.shiro.authc.credential.PasswordMatcher”>  
  49.         <property name=“passwordService” ref=“passwordService” />  
  50.     </bean>  
  51.     <bean id=“passwordService”  
  52.         class=“org.apache.shiro.authc.credential.DefaultPasswordService”>  
  53.         <property name=“hashService” ref=“hashService”></property>  
  54.         <property name=“hashFormat” ref=“hashFormat”></property>  
  55.         <property name=“hashFormatFactory” ref=“hashFormatFactory”></property>  
  56.     </bean>  
  57.     <bean id=“hashService” class=“org.apache.shiro.crypto.hash.DefaultHashService”></bean>  
  58.     <bean id=“hashFormat” class=“org.apache.shiro.crypto.hash.format.Shiro1CryptFormat”></bean>  
  59.     <bean id=“hashFormatFactory”  
  60.         class=“org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory”>  
  61.     </bean>  
  62.   
  63.     <!– 会话ID生成器 –>  
  64.     <bean id=“sessionIdGenerator”  
  65.         class=“org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator” />  
  66.     <!– 会话Cookie模板 关闭浏览器立即失效 –>  
  67.     <bean id=“sessionIdCookie” class=“org.apache.shiro.web.servlet.SimpleCookie”>  
  68.         <constructor-arg value=“sid” />  
  69.         <property name=“httpOnly” value=“true” />  
  70.         <property name=“maxAge” value=“-1” />  
  71.     </bean>  
  72.     <!– 会话DAO –>  
  73.     <bean id=“sessionDAO”  
  74.         class=“org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO”>  
  75.         <property name=“sessionIdGenerator” ref=“sessionIdGenerator” />  
  76.     </bean>  
  77.     <!– 会话验证调度器,每30分钟执行一次验证 ,设定会话超时及保存 –>  
  78.     <bean name=“sessionValidationScheduler”  
  79.         class=“org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler”>  
  80.         <property name=“interval” value=“1800000” />  
  81.         <property name=“sessionManager” ref=“sessionManager” />  
  82.     </bean>  
  83.     <!– 会话管理器 –>  
  84.     <bean id=“sessionManager”  
  85.         class=“org.apache.shiro.web.session.mgt.DefaultWebSessionManager”>  
  86.         <!– 全局会话超时时间(单位毫秒),默认30分钟 –>  
  87.         <property name=“globalSessionTimeout” value=“1800000” />  
  88.         <property name=“deleteInvalidSessions” value=“true” />  
  89.         <property name=“sessionValidationSchedulerEnabled” value=“true” />  
  90.         <property name=“sessionValidationScheduler” ref=“sessionValidationScheduler” />  
  91.         <property name=“sessionDAO” ref=“sessionDAO” />  
  92.         <property name=“sessionIdCookieEnabled” value=“true” />  
  93.         <property name=“sessionIdCookie” ref=“sessionIdCookie” />  
  94.     </bean>  
  95.   
  96.     <!– 安全管理器 –>  
  97.     <bean id=“securityManager” class=“org.apache.shiro.web.mgt.DefaultWebSecurityManager”>  
  98.         <property name=“realm” ref=“userRealm” />  
  99.         <!– 使用下面配置的缓存管理器 –>  
  100.         <property name=“cacheManager” ref=“cacheManager” />  
  101.         <property name=“sessionManager” ref=“sessionManager” />  
  102.     </bean>  
  103.     <!– 相当于调用SecurityUtils.setSecurityManager(securityManager) –>  
  104.     <bean  
  105.         class=“org.springframework.beans.factory.config.MethodInvokingFactoryBean”>  
  106.         <property name=“staticMethod”  
  107.             value=“org.apache.shiro.SecurityUtils.setSecurityManager” />  
  108.         <property name=“arguments” ref=“securityManager” />  
  109.     </bean>  
  110.   
  111.     <!– 注册自定义的Realm,并把密码匹配器注入,使用注解的方式自动注解会无法正确匹配密码 –>  
  112.     <bean id=“userRealm” class=“com.shiro.UserRealm”>  
  113.         <property name=“credentialsMatcher” ref=“passwordMatcher”/>  
  114.         <property name=“cachingEnabled” value=“false”/>  
  115.     </bean>  
  116.       
  117.     <bean id=“cacheManager” class=“org.apache.shiro.cache.MemoryConstrainedCacheManager” />  
  118.     <!– 保证实现了Shiro内部lifecycle函数的bean执行 –>  
  119.     <bean id=“lifecycleBeanPostProcessor” class=“org.apache.shiro.spring.LifecycleBeanPostProcessor” />  
  120. </beans>   
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/util 
    http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 调用我们配置的权限管理器 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 配置我们的登录请求地址 -->
        <property name="loginUrl" value="/login.jsp" />
        <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址 -->
        <property name="successUrl" value="/Adduser.jsp" />
        <!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->
        <property name="unauthorizedUrl" value="/unauthorized" />
        <property name="filters">
            <util:map>
                <entry key="logout" value-ref="logoutFilter" />
            </util:map>
        </property>
        <!-- 权限配置 -->
        <property name="filterChainDefinitions">
            <value>
                <!-- anon表示此地址不需要任何权限即可访问 -->
                /login=anon
                /icon/**=anon
                /js/**=anon
                /logout=logout
                <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login -->
                /** = authc
            </value>
        </property>
    </bean>
    <bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
        <property name="redirectUrl" value="/login.jsp" />
    </bean>

    <!-- 凭证匹配器 -->
    <bean id="passwordMatcher" class="org.apache.shiro.authc.credential.PasswordMatcher">
        <property name="passwordService" ref="passwordService" />
    </bean>
    <bean id="passwordService"
        class="org.apache.shiro.authc.credential.DefaultPasswordService">
        <property name="hashService" ref="hashService"></property>
        <property name="hashFormat" ref="hashFormat"></property>
        <property name="hashFormatFactory" ref="hashFormatFactory"></property>
    </bean>
    <bean id="hashService" class="org.apache.shiro.crypto.hash.DefaultHashService"></bean>
    <bean id="hashFormat" class="org.apache.shiro.crypto.hash.format.Shiro1CryptFormat"></bean>
    <bean id="hashFormatFactory"
        class="org.apache.shiro.crypto.hash.format.DefaultHashFormatFactory">
    </bean>

    <!-- 会话ID生成器 -->
    <bean id="sessionIdGenerator"
        class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />
    <!-- 会话Cookie模板 关闭浏览器立即失效 -->
    <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
        <constructor-arg value="sid" />
        <property name="httpOnly" value="true" />
        <property name="maxAge" value="-1" />
    </bean>
    <!-- 会话DAO -->
    <bean id="sessionDAO"
        class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
        <property name="sessionIdGenerator" ref="sessionIdGenerator" />
    </bean>
    <!-- 会话验证调度器,每30分钟执行一次验证 ,设定会话超时及保存 -->
    <bean name="sessionValidationScheduler"
        class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
        <property name="interval" value="1800000" />
        <property name="sessionManager" ref="sessionManager" />
    </bean>
    <!-- 会话管理器 -->
    <bean id="sessionManager"
        class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
        <!-- 全局会话超时时间(单位毫秒),默认30分钟 -->
        <property name="globalSessionTimeout" value="1800000" />
        <property name="deleteInvalidSessions" value="true" />
        <property name="sessionValidationSchedulerEnabled" value="true" />
        <property name="sessionValidationScheduler" ref="sessionValidationScheduler" />
        <property name="sessionDAO" ref="sessionDAO" />
        <property name="sessionIdCookieEnabled" value="true" />
        <property name="sessionIdCookie" ref="sessionIdCookie" />
    </bean>

    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="userRealm" />
        <!-- 使用下面配置的缓存管理器 -->
        <property name="cacheManager" ref="cacheManager" />
        <property name="sessionManager" ref="sessionManager" />
    </bean>
    <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
    <bean
        class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod"
            value="org.apache.shiro.SecurityUtils.setSecurityManager" />
        <property name="arguments" ref="securityManager" />
    </bean>

    <!-- 注册自定义的Realm,并把密码匹配器注入,使用注解的方式自动注解会无法正确匹配密码 -->
    <bean id="userRealm" class="com.shiro.UserRealm">
        <property name="credentialsMatcher" ref="passwordMatcher"/>
        <property name="cachingEnabled" value="false"/>
    </bean>

    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />
    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans> 

spring-mvc

  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” xmlns:context=“http://www.springframework.org/schema/context”  
  4.     xmlns:mvc=“http://www.springframework.org/schema/mvc”  
  5.     xsi:schemaLocation=”  
  6.               http://www.springframework.org/schema/mvc  
  7.               http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd  
  8.               http://www.springframework.org/schema/beans  
  9.               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  10.               http://www.springframework.org/schema/context  
  11.               http://www.springframework.org/schema/context/spring-context-3.0.xsd”>  
  12.   
  13.     <!– 扫描所有的 controller –>  
  14.     <context:component-scan base-package=“com.Controllers” />  
  15.   
  16.     <!– 启动注解驱动 SpringMVC 功能 –>  
  17.     <mvc:annotation-driven />  
  18.   
  19.     <!– 启动SpringMVC的注解功能,完成请求和注解POJO的映射 –>  
  20.     <bean  
  21.         class=“org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter”>  
  22.         <property name=“messageConverters”>  
  23.             <list>  
  24.                 <ref bean=“jsonMapping” />     <!– JSON转换器 –>  
  25.             </list>  
  26.         </property>  
  27.     </bean>  
  28.   
  29.     <!–避免IE执行AJAX时,返回JSON出现下载文件 –>  
  30.     <bean id=“jsonMapping”  
  31.         class=“org.springframework.http.converter.json.MappingJacksonHttpMessageConverter”>  
  32.         <property name=“supportedMediaTypes”>  
  33.             <list>  
  34.                 <value>text/html;charset=gbk</value>  
  35.             </list>  
  36.         </property>  
  37.     </bean>  
  38.   
  39.     <!– 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 –>  
  40.     <bean id=“multipartResolver”  
  41.         class=“org.springframework.web.multipart.commons.CommonsMultipartResolver”>  
  42.         <!– 默认编码 –>  
  43.         <property name=“defaultEncoding” value=“gbk” />  
  44.         <!– 文件大小最大值 –>  
  45.         <property name=“maxUploadSize” value=“10485760000” />  
  46.         <!– 内存中的最大值 –>  
  47.         <property name=“maxInMemorySize” value=“40960” />  
  48.     </bean>  
  49.   
  50.     <!– 定义跳转的文件的前后缀,视图模式配置 –>  
  51.     <bean  
  52.         class=“org.springframework.web.servlet.view.InternalResourceViewResolver”>  
  53.         <property name=“prefix” value=“” />  
  54.         <property name=“suffix” value=“.jsp” />  
  55.     </bean>  
  56.   
  57.     <!–启用shiro注解 –>  
  58.     <bean  
  59.         class=“org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator”  
  60.         depends-on=“lifecycleBeanPostProcessor”>  
  61.         <property name=“proxyTargetClass” value=“true” />  
  62.     </bean>  
  63.     <bean  
  64.         class=“org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor”>  
  65.         <property name=“securityManager” ref=“securityManager” />  
  66.     </bean>  
  67.     <!– shiro为集成springMvc 拦截异常,使用注解时无权限的跳转 –>  
  68.     <bean  
  69.         class=“org.springframework.web.servlet.handler.SimpleMappingExceptionResolver”>  
  70.         <property name=“exceptionMappings”>  
  71.             <props>  
  72.                 <!– 这里你可以根据需要定义N多个错误异常转发 –>  
  73.                 <prop key=“org.apache.shiro.authz.UnauthorizedException”>redirect:/unauthorized</prop>  
  74.                 <prop key=“org.apache.shiro.authz.UnauthenticatedException”>redirect:/unauthorized</prop>  
  75.                 <prop key=“java.lang.IllegalArgumentException”>/error</prop>  <!– 参数错误(bizError.jsp) –>  
  76.                 <prop key=“java.lang.Exception”>/error</prop>  <!– 其他错误为’未定义错误’(unknowError.jsp) –>  
  77.             </props>  
  78.         </property>  
  79.     </bean>  
  80.   
  81.     <!– 静态资源访问(不拦截此目录下的东西的访问) –>  
  82.     <mvc:resources location=“/js/” mapping=“/js/**” />  
  83.     <mvc:resources location=“/icon/” mapping=“/icon/**” />  
  84.       
  85. </beans>  
<?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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
              http://www.springframework.org/schema/mvc
              http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
              http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
              http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <!-- 扫描所有的 controller -->
    <context:component-scan base-package="com.Controllers" />

    <!-- 启动注解驱动 SpringMVC 功能 -->
    <mvc:annotation-driven />

    <!-- 启动SpringMVC的注解功能,完成请求和注解POJO的映射 -->
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jsonMapping" />     <!-- JSON转换器 -->
            </list>
        </property>
    </bean>

    <!--避免IE执行AJAX时,返回JSON出现下载文件 -->
    <bean id="jsonMapping"
        class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=gbk</value>
            </list>
        </property>
    </bean>

    <!-- 配置文件上传,如果没有使用文件上传可以不用配置,当然如果不配,那么配置文件中也不必引入上传组件包 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 默认编码 -->
        <property name="defaultEncoding" value="gbk" />
        <!-- 文件大小最大值 -->
        <property name="maxUploadSize" value="10485760000" />
        <!-- 内存中的最大值 -->
        <property name="maxInMemorySize" value="40960" />
    </bean>

    <!-- 定义跳转的文件的前后缀,视图模式配置 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!--启用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为集成springMvc 拦截异常,使用注解时无权限的跳转 -->
    <bean
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!-- 这里你可以根据需要定义N多个错误异常转发 -->
                <prop key="org.apache.shiro.authz.UnauthorizedException">redirect:/unauthorized</prop>
                <prop key="org.apache.shiro.authz.UnauthenticatedException">redirect:/unauthorized</prop>
                <prop key="java.lang.IllegalArgumentException">/error</prop>  <!-- 参数错误(bizError.jsp) -->
                <prop key="java.lang.Exception">/error</prop>  <!-- 其他错误为'未定义错误'(unknowError.jsp) -->
            </props>
        </property>
    </bean>

    <!-- 静态资源访问(不拦截此目录下的东西的访问) -->
    <mvc:resources location="/js/" mapping="/js/**" />
    <mvc:resources location="/icon/" mapping="/icon/**" />

</beans>

web.xml

  1. <?xml version=“1.0” encoding=“UTF-8”?>  
  2. <web-app xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”  
  3.     xmlns=“http://xmlns.jcp.org/xml/ns/javaee”  
  4.     xsi:schemaLocation=“http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd”  
  5.     id=“WebApp_ID” version=“3.1”>  
  6.   
  7.     <display-name>M-Shiro</display-name>  
  8.   
  9.     <welcome-file-list>  
  10.         <welcome-file>index.jsp</welcome-file>  
  11.     </welcome-file-list>  
  12.   
  13.     <!– 读取Spring配置文件 –>  
  14.     <context-param>  
  15.         <param-name>contextConfigLocation</param-name>  
  16.         <param-value>  
  17.             classpath:config/spring-mybatis.xml  
  18.             classpath:config/spring-shiro.xml  
  19.         </param-value>  
  20.     </context-param>  
  21.     <listener>  
  22.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  23.     </listener>  
  24.   
  25.     <!– 日志记录 –>  
  26.     <context-param>  
  27.         <!– 日志配置文件路径 –>  
  28.         <param-name>log4jConfigLocation</param-name>  
  29.         <param-value>classpath:properties/log4j.properties</param-value>  
  30.     </context-param>  
  31.     <context-param>  
  32.         <!– 日志页面的刷新间隔 –>  
  33.         <param-name>log4jRefreshInterval</param-name>  
  34.         <param-value>6000</param-value>  
  35.     </context-param>  
  36.     <listener>  
  37.         <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  38.     </listener>  
  39.   
  40.     <!– Shiro配置 –>  
  41.     <filter>  
  42.         <filter-name>shiroFilter</filter-name>  
  43.         <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  44.         <async-supported>true</async-supported>  
  45.         <init-param>  
  46.             <param-name>targetFilterLifecycle</param-name>  
  47.             <param-value>true</param-value>  
  48.         </init-param>  
  49.     </filter>  
  50.     <filter-mapping>  
  51.         <filter-name>shiroFilter</filter-name>  
  52.         <url-pattern>/*</url-pattern>  
  53.     </filter-mapping>  
  54.   
  55.     <!– Spring MVC配置 –>  
  56.     <servlet>  
  57.         <servlet-name>SpringMVC</servlet-name>  
  58.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  59.         <init-param>  
  60.             <param-name>contextConfigLocation</param-name>  
  61.             <param-value>classpath:config/spring-mvc.xml</param-value>  
  62.         </init-param>  
  63.         <load-on-startup>1</load-on-startup>  
  64.     </servlet>  
  65.     <servlet-mapping>  
  66.         <servlet-name>SpringMVC</servlet-name>  
  67.         <url-pattern>/</url-pattern>  
  68.     </servlet-mapping>  
  69.   
  70. </web-app>  
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">

    <display-name>M-Shiro</display-name>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- 读取Spring配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            classpath:config/spring-mybatis.xml
            classpath:config/spring-shiro.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 日志记录 -->
    <context-param>
        <!-- 日志配置文件路径 -->
        <param-name>log4jConfigLocation</param-name>
        <param-value>classpath:properties/log4j.properties</param-value>
    </context-param>
    <context-param>
        <!-- 日志页面的刷新间隔 -->
        <param-name>log4jRefreshInterval</param-name>
        <param-value>6000</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>

    <!-- 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>

    <!-- Spring MVC配置 -->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:config/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

UserRealm

  1. package com.shiro;  
  2.   
  3. import javax.annotation.Resource;  
  4. import org.apache.shiro.authc.AuthenticationException;  
  5. import org.apache.shiro.authc.AuthenticationInfo;  
  6. import org.apache.shiro.authc.AuthenticationToken;  
  7. import org.apache.shiro.authc.SimpleAuthenticationInfo;  
  8. import org.apache.shiro.authc.UnknownAccountException;  
  9. import org.apache.shiro.authz.AuthorizationInfo;  
  10. import org.apache.shiro.authz.SimpleAuthorizationInfo;  
  11. import org.apache.shiro.realm.AuthorizingRealm;  
  12. import org.apache.shiro.subject.PrincipalCollection;  
  13. import com.pojo.*;  
  14. import com.service.IUserService;  
  15.   
  16. public class UserRealm extends AuthorizingRealm {  
  17.       
  18.     @Resource  
  19.     private IUserService userService;  
  20.   
  21.     @Override  
  22.     protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {  
  23.           
  24.         String username = (String)principals.getPrimaryPrincipal();  
  25.         SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();  
  26.         authorizationInfo.setRoles(userService.findRoles(username));  
  27.         authorizationInfo.setStringPermissions(userService.findPermissions(username));  
  28.   
  29.         return authorizationInfo;  
  30.     }  
  31.   
  32.     @Override  
  33.     protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {  
  34.   
  35.         String username = (String)token.getPrincipal();  
  36.         User user = userService.findByUsername(username);  
  37.           
  38.         if(user == null) {  
  39.             throw new UnknownAccountException();//没找到帐号  
  40.         }  
  41.           
  42.         //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现  
  43.         SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(  
  44.                 user.getUsername(), //用户名  
  45.                 user.getPassword(),  
  46.                 getName()  //realm name  
  47.         );  
  48.           
  49.         return authenticationInfo;  
  50.     }  
  51. }  
package com.shiro;

import javax.annotation.Resource;
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.UnknownAccountException;
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 com.pojo.*;
import com.service.IUserService;

public class UserRealm extends AuthorizingRealm {

    @Resource
    private IUserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        String username = (String)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(userService.findRoles(username));
        authorizationInfo.setStringPermissions(userService.findPermissions(username));

        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String)token.getPrincipal();
        User user = userService.findByUsername(username);

        if(user == null) {
            throw new UnknownAccountException();//没找到帐号
        }

        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                user.getUsername(), //用户名
                user.getPassword(),
                getName()  //realm name
        );

        return authenticationInfo;
    }
}

登入

  1. @RequestMapping(value = “/login”, method = RequestMethod.POST)  
  2.     @ResponseBody  
  3.     public Message login(@RequestBody UserValidate userValidate) {  
  4.           
  5.         UsernamePasswordToken token = new UsernamePasswordToken(userValidate.getUsername(), userValidate.getPassword());  
  6.         token.setRememberMe(userValidate.getRememberme());  
  7.         try {  
  8.             SecurityUtils.getSubject().login(token);  
  9.             return new Message(“login success”);  
  10.         } catch (UnknownAccountException uae) {  
  11.             return new Message(“error username”);  
  12.         } catch (IncorrectCredentialsException ice) {  
  13.             return new Message(“error password”);  
  14.         }  
  15.     }  
@RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Message login(@RequestBody UserValidate userValidate) {

        UsernamePasswordToken token = new UsernamePasswordToken(userValidate.getUsername(), userValidate.getPassword());
        token.setRememberMe(userValidate.getRememberme());
        try {
            SecurityUtils.getSubject().login(token);
            return new Message("login success");
        } catch (UnknownAccountException uae) {
            return new Message("error username");
        } catch (IncorrectCredentialsException ice) {
            return new Message("error password");
        }
    }

注册添加

  1. @RequestMapping(value = “/addUser”, method = RequestMethod.POST)  
  2.     @ResponseBody  
  3.     public User adduser(@RequestBody User u) {  
  4.         String pwd = u.getPassword();  
  5.         String newpwd = passwordService.encryptPassword(pwd);  
  6.         u.setPassword(newpwd);  
  7.         User user = userService.createUser(u);  
  8.         int uid = user.getUserid();  
  9.         List<Mapping_UR> urlist = u.getMapping_UR();  
  10.         if (urlist != null) {  
  11.             for (Mapping_UR ur : urlist) {  
  12.                 if (ur != null) {  
  13.                     int roleid = ur.getRole().getRoleid();  
  14.                     userService.correlationRoles(uid, roleid);  
  15.                 }  
  16.             }  
  17.         }  
  18.   
  19.         return user;  
  20.     }  
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public User adduser(@RequestBody User u) {
        String pwd = u.getPassword();
        String newpwd = passwordService.encryptPassword(pwd);
        u.setPassword(newpwd);
        User user = userService.createUser(u);
        int uid = user.getUserid();
        List<Mapping_UR> urlist = u.getMapping_UR();
        if (urlist != null) {
            for (Mapping_UR ur : urlist) {
                if (ur != null) {
                    int roleid = ur.getRole().getRoleid();
                    userService.correlationRoles(uid, roleid);
                }
            }
        }

        return user;
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值