亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

詳解spring整合shiro權(quán)限管理與數(shù)據(jù)庫(kù)設(shè)計(jì)

 更新時(shí)間:2017年05月24日 10:18:18   作者:小爺胡漢三  
這篇文章主要介紹了詳解spring整合shiro權(quán)限管理與數(shù)據(jù)庫(kù)設(shè)計(jì),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧

之前的文章中我們完成了基礎(chǔ)框架的搭建,現(xiàn)在基本上所有的后臺(tái)系統(tǒng)都逃不過(guò)權(quán)限管理這一塊,這算是一個(gè)剛需了?,F(xiàn)在我們來(lái)集成shiro來(lái)達(dá)到顆?;瘷?quán)限管理,也就是從連接菜單到頁(yè)面功能按鈕,都進(jìn)行權(quán)限都驗(yàn)證,從前端按鈕的顯示隱藏,到后臺(tái)具體功能方法的權(quán)限驗(yàn)證。

首先要先設(shè)計(jì)好我們的數(shù)據(jù)庫(kù),先來(lái)看一張比較粗糙的數(shù)據(jù)庫(kù)設(shè)計(jì)圖:

具體的數(shù)據(jù)庫(kù)設(shè)計(jì)代碼

/*
Navicat MySQL Data Transfer

Source Server     : 本機(jī)
Source Server Version : 50537
Source Host      : localhost:3306
Source Database    : task

Target Server Type  : MYSQL
Target Server Version : 50537
File Encoding     : 65001

Date: 2017-01-19 09:58:27
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for sys_authority
-- ----------------------------
DROP TABLE IF EXISTS `sys_authority`;
CREATE TABLE `sys_authority` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
 `data_url` varchar(100) NOT NULL COMMENT '連接路徑或方法',
 `menu_class` varchar(50) NOT NULL COMMENT '菜單樣式',
 `menu_code` varchar(50) NOT NULL COMMENT '菜單編碼',
 `menu_name` varchar(50) NOT NULL COMMENT '菜單名稱(chēng)',
 `parent_menucode` varchar(50) DEFAULT NULL COMMENT '上級(jí)菜單編碼',
 `sequence` bigint(20) DEFAULT '0' COMMENT '排序',
 `menu_type` varchar(2) DEFAULT '1' COMMENT '菜單類(lèi)型(1是左導(dǎo)航菜單 2是按鈕權(quán)限)',
 `create_time` varchar(30) NOT NULL COMMENT '創(chuàng)建時(shí)間',
 PRIMARY KEY (`id`),
 UNIQUE KEY `uk_sys_authority_menu_code` (`menu_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='菜單表';

-- ----------------------------
-- Records of sys_authority
-- ----------------------------

-- ----------------------------
-- Table structure for sys_department
-- ----------------------------
DROP TABLE IF EXISTS `sys_department`;
CREATE TABLE `sys_department` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
 `department_key` varchar(20) NOT NULL COMMENT '部門(mén)編碼',
 `department_value` varchar(40) NOT NULL COMMENT '部門(mén)名稱(chēng)',
 `description` varchar(200) DEFAULT NULL COMMENT '描述',
 `parent_departmentkey` varchar(20) DEFAULT NULL COMMENT '上級(jí)部門(mén)編碼',
 `create_time` varchar(30) DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
 PRIMARY KEY (`id`),
 UNIQUE KEY `uk_sys_department_department_key` (`department_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='部門(mén)表';

-- ----------------------------
-- Records of sys_department
-- ----------------------------

-- ----------------------------
-- Table structure for sys_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
 `role_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
 `role_key` varchar(30) DEFAULT NULL COMMENT '角色編碼',
 `create_time` varchar(30) DEFAULT NULL COMMENT '創(chuàng)建時(shí)間',
 `description` varchar(200) DEFAULT NULL COMMENT '描述',
 `role_value` varchar(40) NOT NULL COMMENT '角色名稱(chēng)',
 `company_id` bigint(20) DEFAULT NULL,
 PRIMARY KEY (`role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COMMENT='角色表';

-- ----------------------------
-- Records of sys_role
-- ----------------------------
INSERT INTO `sys_role` VALUES ('1', 'ROLE_USER', null, null, '', null);
INSERT INTO `sys_role` VALUES ('2', 'ROLE_ADMIN', null, null, '', null);

-- ----------------------------
-- Table structure for sys_role_authority
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_authority`;
CREATE TABLE `sys_role_authority` (
 `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵編號(hào)自增長(zhǎng)',
 `menu_code` varchar(50) NOT NULL COMMENT '菜單編碼',
 `role_key` varchar(40) NOT NULL COMMENT '角色編碼',
 `menu_type` int(11) DEFAULT NULL COMMENT '菜單類(lèi)型 1 導(dǎo)航 2 按鈕',
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='角色菜單表';

-- ----------------------------
-- Records of sys_role_authority
-- ----------------------------

-- ----------------------------
-- Table structure for sys_role_permission
-- ----------------------------
DROP TABLE IF EXISTS `sys_role_permission`;
CREATE TABLE `sys_role_permission` (
 `role_id` int(11) NOT NULL COMMENT '角色主鍵編號(hào)',
 `permissions` varchar(1000) DEFAULT NULL COMMENT '按鈕權(quán)限',
 KEY `FK9q28ewrhntqeipl1t04kh1be7` (`role_id`),
 CONSTRAINT `FK9q28ewrhntqeipl1t04kh1be7` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`role_id`),
 CONSTRAINT `fk_sys_role_permission_role_id` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='角色按鈕權(quán)限表';

-- ----------------------------
-- Records of sys_role_permission
-- ----------------------------

-- ----------------------------
-- Table structure for sys_user
-- ----------------------------
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
 `user_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
 `login_account` varchar(30) NOT NULL COMMENT '登錄賬號(hào)',
 `login_pass` varchar(65) NOT NULL COMMENT '登錄密碼',
 `user_name` varchar(20) DEFAULT NULL COMMENT '昵稱(chēng)',
 `user_head` varchar(30) DEFAULT NULL COMMENT '頭像',
 `user_phone` varchar(20) DEFAULT NULL COMMENT '手機(jī)',
 `user_email` varchar(30) DEFAULT NULL COMMENT '郵箱',
 `user_sex` int(11) DEFAULT NULL COMMENT '性別',
 `user_birthday` varchar(30) DEFAULT NULL COMMENT '生日',
 `register_time` varchar(30) NOT NULL COMMENT '注冊(cè)時(shí)間',
 `department_key` varchar(20) DEFAULT NULL COMMENT '部門(mén)編碼',
 PRIMARY KEY (`user_id`),
 UNIQUE KEY `uk_sys_user_login_account` (`login_account`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COMMENT='用戶(hù)表';

-- ----------------------------
-- Records of sys_user
-- ----------------------------
INSERT INTO `sys_user` VALUES ('2', 'hzw2312', '63cbbfefc6a5f389ea64299134e989a9a378d1293cad8b5623331bf5d0e023a9', null, null, null, 'hzw2312@sina.com', null, null, '2017-01-18 14:39:23', null);
INSERT INTO `sys_user` VALUES ('3', 'hzw2312f', '63cbbfefc6a5f389ea64299134e989a9a378d1293cad8b5623331bf5d0e023a9', null, null, null, 'hzw23d12@sina.com', null, null, '2017-01-18 15:25:08', null);
INSERT INTO `sys_user` VALUES ('4', 'hhsykx', '63cbbfefc6a5f389ea64299134e989a9a378d1293cad8b5623331bf5d0e023a9', null, null, null, 'hhs2312@sina.com', null, null, '2017-01-18 15:25:47', null);

-- ----------------------------
-- Table structure for sys_user_role
-- ----------------------------
DROP TABLE IF EXISTS `sys_user_role`;
CREATE TABLE `sys_user_role` (
 `user_id` bigint(20) NOT NULL COMMENT '用戶(hù)編號(hào)',
 `role_id` int(20) NOT NULL COMMENT '角色編號(hào)',
 PRIMARY KEY (`user_id`,`role_id`),
 KEY `FKhh52n8vd4ny9ff4x9fb8v65qx` (`role_id`),
 CONSTRAINT `FKb40xxfch70f5qnyfw8yme1n1s` FOREIGN KEY (`user_id`) REFERENCES `sys_user` (`user_id`),
 CONSTRAINT `FKhh52n8vd4ny9ff4x9fb8v65qx` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`role_id`),
 CONSTRAINT `fk_sys_user_role_role_id` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`role_id`),
 CONSTRAINT `fk_sys_user_role_user_id` FOREIGN KEY (`user_id`) REFERENCES `sys_user` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用戶(hù)角色映射表';

-- ----------------------------
-- Records of sys_user_role
-- ----------------------------
INSERT INTO `sys_user_role` VALUES ('3', '1');
INSERT INTO `sys_user_role` VALUES ('4', '1');
INSERT INTO `sys_user_role` VALUES ('2', '2');

下面我們開(kāi)始根據(jù)之前的框架集成shiro

首先在pom.xml添加shiro的支持,先在properties中聲明一下要倒入的版本:

<properties> 
  <shiro.version>1.3.2</shiro.version> 
  <commons-logging.version>1.2</commons-logging.version> 
</properties> 

然后在是dependency的添加:

<!-- shiro權(quán)限 --> 
    <dependency> 
      <groupId>org.apache.shiro</groupId> 
      <artifactId>shiro-all</artifactId> 
      <version>${shiro.version}</version> 
    </dependency> 
     
    <!-- commons-logging --> 
    <dependency> 
      <groupId>commons-logging</groupId> 
      <artifactId>commons-logging</artifactId> 
      <version>${commons-logging.version}</version> 
    </dependency> 

下面是shiro的配置跟spring配置放在同級(jí)目錄spring-shiro.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:util="http://www.springframework.org/schema/util" 
    xmlns:aop="http://www.springframework.org/schema/aop" 
    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 
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> 
   
   
  <!-- 緩存管理器 使用Ehcache實(shí)現(xiàn) --> 
  <bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager"> 
    <property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml" /> 
  </bean> 
   
  <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> 
    <!--認(rèn)證管理器--> 
    <property name="realm" ref="shiroSecurityRealm" /> 
    <!-- 緩存管理器 --> 
    <property name="cacheManager" ref="cacheManager" /> 
    <!-- rememberMe管理器 --> 
    <property name="rememberMeManager" ref="rememberMeManager"/> 
  </bean> 
  <!-- 會(huì)話(huà)ID生成器 --> 
  <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator"/> 
 
  <!-- 會(huì)話(huà)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> 
   
  <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">  
    <constructor-arg value="rememberMe"/>  
    <property name="httpOnly" value="true"/> 
    <property name="maxAge" value="2592000"/><!-- 30天 -->  
  </bean> 
  <!-- rememberMe管理器 --> 
  <bean id="rememberMeManager" 
    class="org.apache.shiro.web.mgt.CookieRememberMeManager">  
    <property name="cipherKey" value="#{T(org.apache.shiro.codec.Base64).decode('7gzYfKjTASKdsai43ds==')}"/>  
     <property name="cookie" ref="rememberMeCookie"/> 
  </bean> 
   
  <!-- 會(huì)話(huà)DAO --> 
  <bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO"> 
    <property name="activeSessionsCacheName" value="shiro-activeSessionCache"/> 
    <property name="sessionIdGenerator" ref="sessionIdGenerator"/> 
  </bean> 
  <!-- 會(huì)話(huà)驗(yàn)證調(diào)度器 --> 
  <bean id="sessionValidationScheduler" class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler"> 
    <property name="sessionValidationInterval" value="3000000"/> 
    <property name="sessionManager" ref="sessionManager"/> 
  </bean> 
 
  <!-- 會(huì)話(huà)管理器 --> 
  <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager"> 
    <property name="globalSessionTimeout" value="3000000"/> 
    <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="formAuthenticationFilter" class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">  
    <property name="rememberMeParam" value="rememberMe"/>  
  </bean> 
   
   
  <bean id="sysUserFilter" class="yfkj.gz.task.security.SysUserFilter"/> 
   
  <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> 
    <property name="securityManager" ref="securityManager"/> 
    <property name="loginUrl" value="/login.jsp"/> 
    <property name="successUrl" value="/page/main.action"/> 
    <property name="filters"> 
      <util:map> 
        <entry key="authc"> 
          <bean class="org.apache.shiro.web.filter.authc.PassThruAuthenticationFilter"/> 
        </entry> 
        <entry key="sysUser" value-ref="sysUserFilter"/> 
      </util:map> 
    </property> 
    <property name="filterChainDefinitions"> 
      <value> 
        /static/** = anon 
        /login.jsp = anon 
        /sysuser/login.action = anon 
        /sysuser/register.action = anon 
        /sysuser/getEMailCount.action = anon 
        /sysuser/getUserNameCount.action = anon 
        /sysuser/logout.action = logout 
        /** = user,sysUser <!-- 表示訪(fǎng)問(wèn)該地址的用戶(hù)是身份驗(yàn)證通過(guò)或RememberMe登錄的都可以 --> 
        <!-- /** = authc 表示訪(fǎng)問(wèn)該地址用戶(hù)必須身份驗(yàn)證通過(guò)--> 
      </value> 
    </property> 
  </bean> 
   
  <!-- Post processor that automatically invokes init() and destroy() methods --> 
  <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> 
   
</beans> 

上面的

/static/** = anon,/login.jsp = anon...這些等于anon的就是默認(rèn)不做權(quán)限驗(yàn)證的,我們的登錄,注冊(cè),靜態(tài)資源等,不需要權(quán)限驗(yàn)證。

權(quán)限緩存的配置(如果不用緩存的話(huà),每次請(qǐng)求都要去訪(fǎng)問(wèn)數(shù)據(jù)庫(kù)查詢(xún)權(quán)限)ehcache-shiro.xml:

<?xml version="1.0" encoding="UTF-8"?> 
<ehcache name="shirocache"> 
 
  <diskStore path="java.io.tmpdir/yfkj-shiro-ehcache"/> 
   
  <!-- 默認(rèn)緩存 --> 
  <defaultCache maxElementsInMemory="1000" eternal="false" 
    overflowToDisk="true" timeToIdleSeconds="300" timeToLiveSeconds="180" 
    diskPersistent="false" diskExpiryThreadIntervalSeconds="120" /> 
   
  <!-- 登錄記錄緩存 --> 
  <cache name="passwordRetryCache" 
      maxEntriesLocalHeap="2000" 
      eternal="false" 
      timeToIdleSeconds="3600" 
      timeToLiveSeconds="0" 
      overflowToDisk="false" 
      statistics="true"> 
  </cache> 
 
  <!-- 授權(quán)緩存 --> 
  <cache name="authorizationCache" 
      maxEntriesLocalHeap="2000" 
      eternal="false" 
      timeToIdleSeconds="3600" 
      timeToLiveSeconds="0" 
      overflowToDisk="false" 
      statistics="true"> 
  </cache> 
 
  <!-- 認(rèn)證緩存 --> 
  <cache name="authenticationCache" 
      maxEntriesLocalHeap="2000" 
      eternal="false" 
      timeToIdleSeconds="3600" 
      timeToLiveSeconds="0" 
      overflowToDisk="false" 
      statistics="true"> 
  </cache> 
 
  <cache name="shiro-activeSessionCache" 
      maxEntriesLocalHeap="2000" 
      eternal="false" 
      timeToIdleSeconds="3600" 
      timeToLiveSeconds="0" 
      overflowToDisk="false" 
      statistics="true"> 
  </cache> 
   
  <cache name="shiro-kickout-session" 
      maxEntriesLocalHeap="2000" 
      eternal="false" 
      timeToIdleSeconds="3600" 
      timeToLiveSeconds="0" 
      overflowToDisk="false" 
      statistics="true"> 
  </cache> 
 
</ehcache> 

自定義用戶(hù)過(guò)濾類(lèi)SysUserFilter:

import yfkj.gz.task.service.ISysUserService; 
 
import org.apache.shiro.web.filter.PathMatchingFilter; 
 
import javax.annotation.Resource; 
import javax.servlet.ServletRequest; 
import javax.servlet.ServletResponse; 
 
/** 
 * 自定義用戶(hù)過(guò)濾器 
 * @author 胡漢三 
 * 
 */ 
public class SysUserFilter extends PathMatchingFilter { 
   
  @Resource 
  private ISysUserService sysUserService; 
 
  @Override 
  protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { 
    //可以參考http://jinnianshilongnian.iteye.com/blog/2025656 
    return true; 
  } 
} 

權(quán)限認(rèn)證類(lèi)ShiroSecurityRealm:

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.UsernamePasswordToken; 
import org.apache.shiro.authc.credential.Sha256CredentialsMatcher; 
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.stereotype.Component; 
 
import yfkj.gz.task.dao.ISysUserDao; 
import yfkj.gz.task.entity.SysRole; 
import yfkj.gz.task.entity.SysUser; 
import yfkj.gz.task.service.ISysUserService; 
 
/** 
 * 權(quán)限認(rèn)證 
 * @author 胡漢三 
 * @date  2017年1月19日 上午10:52:17 
 */ 
@SuppressWarnings("deprecation") 
@Component 
public class ShiroSecurityRealm extends AuthorizingRealm { 
   
  @Resource 
  private ISysUserService userService; 
 
  @Resource 
  private ISysUserDao sysUserDao; 
 
  public ShiroSecurityRealm() { 
    setName("ShiroSecurityRealm"); // This name must match the name in the SysUser class's getPrincipals() method 
    setCredentialsMatcher(new Sha256CredentialsMatcher()); 
  } 
 
  /** 
   * 登錄認(rèn)證 
   */ 
  protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { 
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken; 
    SysUser user = userService.getByProerties(new String[]{"loginAccount"}, new String[]{token.getUsername()},null); 
    if (user != null) { 
      return new SimpleAuthenticationInfo(user.getUserId(), user.getLoginPass(), getName()); 
    } else { 
      return null; 
    } 
  } 
 
 
  /** 
   * 權(quán)限認(rèn)證 
   */ 
  protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { 
    Long userId = (Long) principals.fromRealm(getName()).iterator().next(); 
    SysUser user = userService.get(userId); 
    if (user != null) { 
      SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); 
      for (SysRole role : user.getRoles()) { 
        info.addRole(role.getRoleKey()); 
        info.addStringPermissions(role.getPermissions()); 
      } 
      return info; 
    } else { 
      return null; 
    } 
  } 
 
} 

在web.xml加入:

<!-- 加載spring配置文件 --> 
  <context-param> 
    <param-name>contextConfigLocation</param-name> 
    <param-value>classpath:spring.xml,classpath:spring-hibernate.xml,classpath:spring-shiro.xml</param-value> 
  </context-param> 
   
  <!-- shiro權(quán)限過(guò)濾器 --> 
  <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>shiroFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
  </filter-mapping> 

在登錄方法中加上權(quán)限的登錄(構(gòu)造方法參數(shù):登錄賬號(hào),登錄密碼,記住我):

//存入session 
    Subject subject = SecurityUtils.getSubject(); 
    //記得傳入明文密碼 
    subject.login(new UsernamePasswordToken(userInfo.getLoginAccount(), user.getLoginPass(), rememberMe)); 
完整的登錄方法:
[java] view plain copy 在CODE上查看代碼片派生到我的代碼片
/** 
   * 用戶(hù)登錄 
   * @param response 
   * @param user 
   * @throws IOException 
   */ 
  @RequestMapping(value = "/login", method = { RequestMethod.POST, RequestMethod.GET }) 
  public void login(SysUser user,boolean rememberMe) throws IOException{ 
    //用戶(hù)登錄 
    SysUser userInfo = userService.getByProerties(new String[]{"loginAccount"}, new String[]{user.getLoginAccount()},null); 
    if(userInfo==null){ 
      result.setMessage("用戶(hù)名錯(cuò)誤"); 
      super.writeJSON(result); 
      return; 
    } 
    if(!userInfo.getLoginPass().equals(new Sha256Hash(user.getLoginPass()).toHex())){ 
      result.setMessage("密碼錯(cuò)誤"); 
      super.writeJSON(result); 
      return; 
    } 
    //存入session 
    Subject subject = SecurityUtils.getSubject(); 
    //記得傳入明文密碼 
    subject.login(new UsernamePasswordToken(userInfo.getLoginAccount(), user.getLoginPass(), rememberMe)); 
    session.setAttribute(USER_SESSION, userInfo); 
    result.setMessage("登錄成功"); 
    result.setSuccess(true); 
    super.writeJSON(result); 
  } 

數(shù)據(jù)庫(kù)也設(shè)計(jì)好啦,該整合的也整合了,怎么來(lái)實(shí)現(xiàn)呢,這里先說(shuō)一點(diǎn)點(diǎn),詳細(xì)的等下一篇說(shuō):

jsp頁(yè)面引入page指令:

<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %> 

在要做驗(yàn)證的按鈕上加上shiro標(biāo)簽的判斷:

<shiro:hasPermission name="${ROLE_KEY}:role:role_add"> 
          <button id="btn_add" type="button" class="btn btn-default"> 
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增 
          </button> 
          </shiro:hasPermission> 

${ROLE_KEY}:role:role_add的意思就是:

${ROLE_KEY}角色

role是指菜單(頁(yè)面)

role_add指的功能

聯(lián)合起來(lái)就是,當(dāng)前角色在role菜單(頁(yè)面)中有沒(méi)有role_add新增的功能,如果有就會(huì)顯示,沒(méi)有就不顯示這個(gè)按鈕啦。

在后臺(tái)方法中驗(yàn)證:

在對(duì)應(yīng)的方法中加入代碼:

Subject subject = SecurityUtils.getSubject(); 
subject.checkPermission(getCurrentRoleKey()+":role:role_add"); 

如果沒(méi)有通過(guò)checkPermission,則會(huì)直接返回錯(cuò)誤,不執(zhí)行下面的代碼啦。

實(shí)體Base類(lèi)BaseEntity:

import java.io.Serializable; 
import java.util.LinkedHashMap; 
import java.util.Map; 
 
/** 
 * 實(shí)體父類(lèi) 
 * @author 胡漢三 
 * @date  2017年1月18日 上午11:03:11 
 */ 
public class BaseEntity implements Serializable{ 
   
  /** 
   * 
   */ 
  private static final long serialVersionUID = 3730369554400423966L; 
   
  /** 
   * 排序 
   */ 
  private Map<String, String> sortedConditions = new LinkedHashMap<String, String>(); 
 
  public Map<String, String> getSortedConditions() { 
    return sortedConditions; 
  } 
  public void setSortedConditions(Map<String, String> sortedConditions) { 
    this.sortedConditions = sortedConditions; 
  } 
   
   
} 

用戶(hù)實(shí)體SysUser:

import java.util.HashSet; 
import java.util.Set; 
 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.FetchType; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.JoinTable; 
import javax.persistence.JoinColumn; 
import javax.persistence.ManyToMany; 
import javax.persistence.Table; 
 
import org.hibernate.annotations.Cache; 
import org.hibernate.annotations.CacheConcurrencyStrategy; 
 
import yfkj.gz.support.BaseEntity; 
 
 
/** 
 * 用戶(hù)的實(shí)體類(lèi) 
 */ 
@Entity 
@Table(name = "sys_user") 
public class SysUser extends BaseEntity{ 
 
  /** 
   * 
   */ 
  private static final long serialVersionUID = 2491111485758197830L; 
   
  /**主鍵**/ 
  @Id 
  @GeneratedValue 
  @Column(name = "user_id") 
  private Long userId; 
 
  /**登錄賬號(hào)**/ 
  @Column(name = "login_account" ,length = 30 , unique = true ) 
  private String loginAccount; 
 
  /**登錄密碼**/ 
  @Column(name = "login_pass" ,length = 65) 
  private String loginPass; 
 
  /**昵稱(chēng)**/ 
  @Column(name = "user_name" ,length = 20) 
  private String userName; 
 
  /**頭像**/ 
  @Column(name = "user_head" ,length = 30) 
  private String userHead; 
 
  /**手機(jī)**/ 
  @Column(name = "user_phone" ,length = 20) 
  private String userPhone; 
 
  /**郵箱**/ 
  @Column(name = "user_email" ,length = 30) 
  private String userEmail; 
 
  /**性別**/ 
  @Column(name = "user_sex") 
  private Integer userSex; 
 
  /**生日**/ 
  @Column(name = "user_birthday" ,length = 30) 
  private String userBirthday; 
 
  /**注冊(cè)時(shí)間**/ 
  @Column(name = "register_time" ,length = 30) 
  private String registerTime; 
   
  /**部門(mén)編碼**/ 
  @Column(name = "department_key" ,length = 20) 
  private String departmentKey; 
   
   
  /**用戶(hù)角色**/ 
  @ManyToMany(fetch = FetchType.EAGER) 
  @JoinTable(name = "sys_user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = { @JoinColumn(name = "role_id") }) 
  @Cache(region = "all", usage = CacheConcurrencyStrategy.READ_WRITE) 
  private Set<SysRole> roles = new HashSet<SysRole>(); 
   
   
  /**get/set**/ 
   
 
  /**主鍵**/ 
  public Long getUserId(){ 
    return userId; 
  } 
  /**主鍵**/ 
  public void setUserId(Long userId){ 
    this.userId= userId; 
  } 
  /**登錄賬號(hào)**/ 
  public String getLoginAccount(){ 
    return loginAccount; 
  } 
  /**登錄賬號(hào)**/ 
  public void setLoginAccount(String loginAccount){ 
    this.loginAccount= loginAccount; 
  } 
  /**登錄密碼**/ 
  public String getLoginPass(){ 
    return loginPass; 
  } 
  /**登錄密碼**/ 
  public void setLoginPass(String loginPass){ 
    this.loginPass= loginPass; 
  } 
  /**昵稱(chēng)**/ 
  public String getUserName(){ 
    return userName; 
  } 
  /**昵稱(chēng)**/ 
  public void setUserName(String userName){ 
    this.userName= userName; 
  } 
  /**頭像**/ 
  public String getUserHead(){ 
    return userHead; 
  } 
  /**頭像**/ 
  public void setUserHead(String userHead){ 
    this.userHead= userHead; 
  } 
  /**手機(jī)**/ 
  public String getUserPhone(){ 
    return userPhone; 
  } 
  /**手機(jī)**/ 
  public void setUserPhone(String userPhone){ 
    this.userPhone= userPhone; 
  } 
  /**郵箱**/ 
  public String getUserEmail(){ 
    return userEmail; 
  } 
  /**郵箱**/ 
  public void setUserEmail(String userEmail){ 
    this.userEmail= userEmail; 
  } 
  /**性別**/ 
  public Integer getUserSex(){ 
    return userSex; 
  } 
  /**性別**/ 
  public void setUserSex(Integer userSex){ 
    this.userSex= userSex; 
  } 
  /**生日**/ 
  public String getUserBirthday(){ 
    return userBirthday; 
  } 
  /**生日**/ 
  public void setUserBirthday(String userBirthday){ 
    this.userBirthday= userBirthday; 
  } 
  /**注冊(cè)時(shí)間**/ 
  public String getRegisterTime(){ 
    return registerTime; 
  } 
  /**注冊(cè)時(shí)間**/ 
  public void setRegisterTime(String registerTime){ 
    this.registerTime= registerTime; 
  } 
   
  public Set<SysRole> getRoles() { 
    return roles; 
  } 
  public void setRoles(Set<SysRole> roles) { 
    this.roles = roles; 
  } 
   
   
} 

角色實(shí)體SysRole:

import java.util.Set; 
 
import javax.persistence.Column; 
import javax.persistence.ElementCollection; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.JoinColumn; 
import javax.persistence.JoinTable; 
import javax.persistence.Table; 
 
import org.hibernate.annotations.Cache; 
import org.hibernate.annotations.CacheConcurrencyStrategy; 
 
 
import yfkj.gz.support.BaseEntity; 
 
/** 
 * 角色的實(shí)體類(lèi) 
 */ 
@Entity 
@Table(name = "sys_role") 
@Cache(region = "all", usage = CacheConcurrencyStrategy.READ_WRITE) 
public class SysRole extends BaseEntity{ 
 
  // 各個(gè)字段的含義請(qǐng)查閱文檔的數(shù)據(jù)庫(kù)結(jié)構(gòu)部分 
  private static final long serialVersionUID = 6019103858711599150L; 
  @Id 
  @GeneratedValue 
  @Column(name = "role_id") 
  private Long roleId; 
  @Column(name = "role_key", length = 40, nullable = false, unique = true) 
  private String roleKey; 
  @Column(name = "role_value", length = 40, nullable = false) 
  private String roleValue; 
  @Column(name = "create_time", length = 30) 
  private String createTime; 
  @Column(name = "description", length = 200) 
  private String description; 
   
  @ElementCollection 
  @JoinTable(name = "sys_role_permission", joinColumns = { @JoinColumn(name = "role_id") }) 
  @Cache(region = "all", usage = CacheConcurrencyStrategy.READ_WRITE) 
  private Set<String> permissions; 
 
  @Column(name="company_id") 
  private Long companyId; 
   
  public SysRole() { 
 
  } 
 
   
 
  public Long getRoleId() { 
    return roleId; 
  } 
 
  public void setRoleId(Long roleId) { 
    this.roleId = roleId; 
  } 
 
  public String getRoleKey() { 
    return roleKey; 
  } 
 
  public void setRoleKey(String roleKey) { 
    this.roleKey = roleKey; 
  } 
 
  public String getRoleValue() { 
    return roleValue; 
  } 
 
  public void setRoleValue(String roleValue) { 
    this.roleValue = roleValue; 
  } 
 
  public String getCreateTime() { 
    return createTime; 
  } 
 
  public void setCreateTime(String createTime) { 
    this.createTime = createTime; 
  } 
   
  public String getDescription() { 
    return description; 
  } 
 
  public void setDescription(String description) { 
    this.description = description; 
  } 
 
  public Set<String> getPermissions() { 
    return permissions; 
  } 
 
  public void setPermissions(Set<String> permissions) { 
    this.permissions = permissions; 
  } 
 
  public Long getCompanyId() { 
    return companyId; 
  } 
 
  public void setCompanyId(Long companyId) { 
    this.companyId = companyId; 
  } 
 
} 

項(xiàng)目結(jié)構(gòu)圖:

 

源碼地址:spring-shiro_jb51.rar

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java中的ThreadLocalMap源碼解讀

    Java中的ThreadLocalMap源碼解讀

    這篇文章主要介紹了Java中的ThreadLocalMap源碼解讀,ThreadLocalMap是ThreadLocal的內(nèi)部類(lèi),是一個(gè)key-value數(shù)據(jù)形式結(jié)構(gòu),也是ThreadLocal的核心,需要的朋友可以參考下
    2023-09-09
  • Maven及Springboot配置JDK版本,編碼,源碼打包等方式

    Maven及Springboot配置JDK版本,編碼,源碼打包等方式

    這篇文章主要介紹了Maven及Springboot配置JDK版本,編碼,源碼打包等方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • Java獲取e.printStackTrace()打印的信息方式

    Java獲取e.printStackTrace()打印的信息方式

    這篇文章主要介紹了Java獲取e.printStackTrace()打印的信息方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • java項(xiàng)目中使用 Lombok遇到的問(wèn)題小結(jié)

    java項(xiàng)目中使用 Lombok遇到的問(wèn)題小結(jié)

    這篇文章主要介紹了java項(xiàng)目中使用 Lombok遇到的問(wèn)題小結(jié),需要的朋友可以參考下
    2018-07-07
  • Java Unsafe學(xué)習(xí)筆記分享

    Java Unsafe學(xué)習(xí)筆記分享

    今天小編就為大家分享一篇Java Unsafe學(xué)習(xí)筆記,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • JAVAEE Filter 過(guò)濾器設(shè)置是否緩存實(shí)例詳解

    JAVAEE Filter 過(guò)濾器設(shè)置是否緩存實(shí)例詳解

    網(wǎng)頁(yè)中,每次的客戶(hù)端訪(fǎng)問(wèn)服務(wù)器,有部分不用重復(fù)請(qǐng)求的,這樣可以減輕服務(wù)器的工作量。那么如何設(shè)置客戶(hù)端是否都緩存呢?接下來(lái)通過(guò)本文給大家介紹JAVAEE Filter 過(guò)濾器設(shè)置是否緩存的實(shí)例,感興趣的朋友一起學(xué)習(xí)吧
    2016-05-05
  • Java工廠(chǎng)模式用法之如何動(dòng)態(tài)選擇對(duì)象詳解

    Java工廠(chǎng)模式用法之如何動(dòng)態(tài)選擇對(duì)象詳解

    工廠(chǎng)設(shè)計(jì)模式可能是最常用的設(shè)計(jì)模式之一,我想大家在自己的項(xiàng)目中都用到過(guò)。本文不僅僅是關(guān)于工廠(chǎng)模式的基本知識(shí),更是討論如何在運(yùn)行時(shí)動(dòng)態(tài)選擇不同的方法進(jìn)行執(zhí)行,你們可以看看是不是和你們項(xiàng)目中用的一樣
    2023-03-03
  • Guava的注解處理機(jī)制全面講解

    Guava的注解處理機(jī)制全面講解

    這篇文章主要為大家介紹了Guava的注解處理機(jī)制全面講解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-12-12
  • SpringBoot集成JWT令牌詳細(xì)說(shuō)明

    SpringBoot集成JWT令牌詳細(xì)說(shuō)明

    這篇文章主要介紹了SpringBoot集成JWT令牌詳細(xì)說(shuō)明,JWT方式校驗(yàn)方式更加簡(jiǎn)單便捷化,無(wú)需通過(guò)redis緩存,而是直接根據(jù)token取出保存的用戶(hù)信息,以及對(duì)token可用性校驗(yàn),單點(diǎn)登錄,驗(yàn)證token更為簡(jiǎn)單,需要的朋友可以參考下
    2023-10-10
  • Java語(yǔ)言基于無(wú)向有權(quán)圖實(shí)現(xiàn)克魯斯卡爾算法代碼示例

    Java語(yǔ)言基于無(wú)向有權(quán)圖實(shí)現(xiàn)克魯斯卡爾算法代碼示例

    這篇文章主要介紹了Java語(yǔ)言基于無(wú)向有權(quán)圖實(shí)現(xiàn)克魯斯卡爾算法代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。
    2017-11-11

最新評(píng)論