搭建Maven、SSM、shiro框架詳細步驟

上一篇搭建Maven、SSM框架詳細步驟,然後本文在此基礎上,集成shiro框架

一、創建數據庫(數據庫名:shiro,多對多關係)

在這裏插入圖片描述

  • 運行 shiro.sql 腳本添加數據庫
/*
Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50528
Source Host           : localhost:3306
Source Database       : shiro

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

Date: 2019-07-28 21:21:26
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
  `perid` int(11) NOT NULL AUTO_INCREMENT,
  `pername` varchar(255) DEFAULT NULL,
  `percode` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`perid`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES ('1', '用戶查詢', 'user:query');
INSERT INTO `permission` VALUES ('2', '用戶添加', 'user:add');
INSERT INTO `permission` VALUES ('3', '用戶修改', 'user:update');
INSERT INTO `permission` VALUES ('4', '用戶刪除', 'user:delete');
INSERT INTO `permission` VALUES ('5', '導出用戶', 'user:export');

-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
  `roleid` int(11) NOT NULL AUTO_INCREMENT,
  `rolename` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`roleid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', '超級管理員');
INSERT INTO `role` VALUES ('2', 'CEO');
INSERT INTO `role` VALUES ('3', '保安');

-- ----------------------------
-- Table structure for role_permission
-- ----------------------------
DROP TABLE IF EXISTS `role_permission`;
CREATE TABLE `role_permission` (
  `perid` int(255) DEFAULT NULL,
  `roleid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `userpwd` varchar(255) DEFAULT NULL,
  `sex` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user   md5加密 鹽是姓名加地址,散列2次
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '639ffb0cbcca39d4fff8348844b1974e', '男', '武漢');
INSERT INTO `user` VALUES ('2', 'lisi', '0d303fa8e2e2ca98555f23a731a58dd9', '女', '北京');
INSERT INTO `user` VALUES ('3', 'wangwu', '473c41db9af5cc0d90e7adfd2b6d9180', '女', '成都');

-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
  `userid` int(11) DEFAULT NULL,
  `roleid` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

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

二、修改pom.xml引入shiro包

<shiro.version>1.4.1</shiro.version>


<!-- 依賴shiro -->
		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-spring</artifactId>
			<version>${shiro.version}</version>
		</dependency>

三、創建domain下的類,mapper接口,mapper.xml 文件

1.創建User類、 UserMapper接口、UserMapper.xml

2.創建Role類、 RoleMapper接口、RoleMapper.xml

3.創建Permission類、PermissionMapper接口、 PermissionMapper.xml

以user爲例

  • 創建User類、
public class User implements Serializable{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private Integer userid;

    private String username;

    private String userpwd;

    private String sex;

    private String address;

    public Integer getUserid() {
        return userid;
    }

    public void setUserid(Integer userid) {
        this.userid = userid;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getUserpwd() {
        return userpwd;
    }

    public void setUserpwd(String userpwd) {
        this.userpwd = userpwd == null ? null : userpwd.trim();
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex == null ? null : sex.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }
}
  • UserMapper接口、
public interface UserMapper {
    int deleteByPrimaryKey(Integer userid);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer userid);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    /**
     * 根據用戶名查詢用戶
     * @param username
     * @return
     */
	User queryUserByUserName(@Param("username")String username);
}
  • UserMapper.xml
<?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="包.mapper.UserMapper">
  <resultMap id="BaseResultMap" type="包.domain.User">
    <id column="userid" jdbcType="INTEGER" property="userid" />
    <result column="username" jdbcType="VARCHAR" property="username" />
    <result column="userpwd" jdbcType="VARCHAR" property="userpwd" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
    <result column="address" jdbcType="VARCHAR" property="address" />
  </resultMap>
  <sql id="Base_Column_List">
    userid, username, userpwd, sex, address
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from user
    where userid = #{userid,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from user
    where userid = #{userid,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="包.domain.User">
    insert into user (userid, username, userpwd, 
      sex, address)
    values (#{userid,jdbcType=INTEGER}, #{username,jdbcType=VARCHAR}, #{userpwd,jdbcType=VARCHAR}, 
      #{sex,jdbcType=VARCHAR}, #{address,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="包.domain.User">
    insert into user
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="userid != null">
        userid,
      </if>
      <if test="username != null">
        username,
      </if>
      <if test="userpwd != null">
        userpwd,
      </if>
      <if test="sex != null">
        sex,
      </if>
      <if test="address != null">
        address,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="userid != null">
        #{userid,jdbcType=INTEGER},
      </if>
      <if test="username != null">
        #{username,jdbcType=VARCHAR},
      </if>
      <if test="userpwd != null">
        #{userpwd,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        #{sex,jdbcType=VARCHAR},
      </if>
      <if test="address != null">
        #{address,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="包.domain.User">
    update user
    <set>
      <if test="username != null">
        username = #{username,jdbcType=VARCHAR},
      </if>
      <if test="userpwd != null">
        userpwd = #{userpwd,jdbcType=VARCHAR},
      </if>
      <if test="sex != null">
        sex = #{sex,jdbcType=VARCHAR},
      </if>
      <if test="address != null">
        address = #{address,jdbcType=VARCHAR},
      </if>
    </set>
    where userid = #{userid,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="包.domain.User">
    update user
    set username = #{username,jdbcType=VARCHAR},
      userpwd = #{userpwd,jdbcType=VARCHAR},
      sex = #{sex,jdbcType=VARCHAR},
      address = #{address,jdbcType=VARCHAR}
    where userid = #{userid,jdbcType=INTEGER}
  </update>
  
  <!-- 根據用戶名查詢用戶 -->
  <select id="queryUserByUserName" resultMap="BaseResultMap">
  	select * from user where username=#{username}
  </select>
</mapper>

四、創建ActiverUser

在這裏插入圖片描述

五、創建UserRealm

public class UserRealm extends AuthorizingRealm {
	@Override
	public String getName() {
		return this.getClass().getSimpleName();
	}
	@Autowired
	private UserService userService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PermissionService permssionService;
	/**
	 * 完成認證的方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = token.getPrincipal().toString();
		Object credentials = token.getCredentials();// 用戶登陸時傳過來的
		System.out.println(Arrays.toString((char[]) credentials));
		// 根據用戶名查詢用戶是否存在
		User user = this.userService.queryUserByUserName(username);
		// 返回null說明用戶不存在
		if (null != user) {
			// 根據用戶名去查詢用戶擁有哪些角色
			List<String> roles = roleService.queryRolesByUserId(user.getUserid());
			// 根據用戶名查詢用戶擁有哪些權限
			List<String> permissions = this.permssionService.queryPermissionsByUserId(user.getUserid());

			ActiveUser activeUser = new ActiveUser(user, roles, permissions);
			/**
			 * 參數1 用戶身份 參數2 用戶在數據庫裏面存放的密碼 參數3 當前類名
			 */
			// SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(activeUser,
			// user.getPassword(), this.getName());
			/**
			 * 參數1:傳到doGetAuthorizationInfo裏面getPrimaryPrincipal()的對象或者subject.getPrincipal()
			 * 參數2:hashedCredentials 加密之後的密碼 參數3:credentialsSalt 鹽
			 */
			ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername()+user.getAddress());
			SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser, user.getUserpwd(), credentialsSalt,
					this.getName());
			return info;
		}
		return null;
	}
	/**
	 * 授權
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		// 根據用戶名去查詢用戶擁有哪些角色
		List<String> roles = activeUser.getRoles();
		if (null != roles && roles.size() > 0) {
			// 添加角色
			info.addRoles(roles);
		}
		// 根據用戶名查詢用戶擁有哪些權限
		List<String> permissions = activeUser.getPermissions();
		// 添加權限
		if (null != permissions && permissions.size() > 0) {
			// 添加角色
			info.addStringPermissions(permissions);
		}
		return info;
	}
}

六、修改web.xml

	<!-- 配置shiro的代理過濾器 開始 -->
	<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>
		<init-param>
			<!-- 這裏的shrioFilter必須和application-shrio.xml裏面的  過濾器ID一致 -->
			<param-name>targetBeanName</param-name>
			<param-value>shiroFilter</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>shiroFilter</filter-name>
		<servlet-name>springmvc</servlet-name>
	</filter-mapping>
	<!-- 配置shiro的代理過濾器 結束 -->

七、創建application-shiro.xml 並在applicationContext.xml 引入(import)

  • 創建application-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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-4.3.xsd">

	<!-- 聲明憑證匹配器 -->
	<bean id="credentialsMatcher"
		class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
		<!-- 注入加密方式 -->
		<property name="hashAlgorithmName" value="md5"></property>
		<!-- 注入散列次數 -->
		<property name="hashIterations" value="2"></property>
	</bean>

	<!-- 聲明userRealm -->
	<bean id="userRealm" class="包.realm.UserRealm">
		<!-- 注入憑證匹配器 -->
		<property name="credentialsMatcher" ref="credentialsMatcher"></property>
	</bean>
	
	<!-- 聲明一個cookie的對象 -->
	<bean id="cookie" class="org.apache.shiro.web.servlet.SimpleCookie">
		<constructor-arg value="rememberMe"></constructor-arg>
		<!-- 只有http請求才會生效 -->
		<property name="httpOnly" value="true"></property>
		<!-- 設置cookie的存活時間  單位是秒 -->
		<property name="maxAge" value="604800"></property>
	</bean>
	
	<!-- 聲明一個cookie管理器 -->
	<bean id="cookieManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
		<property name="cookie" ref="cookie"></property>
	</bean>

	<!-- 聲明安全管理器 -->
	<bean id="securityManager"
		class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<!-- 注入realm -->
		<property name="realm" ref="userRealm"></property>
		
		<!-- 注入一個記住我的管理器 -->
		<property name="rememberMeManager" ref="cookieManager"></property>
	</bean>

	<!-- 聲明記住我的自定義過濾器對象 -->
	<bean id="rememberMe" class="包.filter.RememberMeFilter"></bean>

	<!-- 配置shrio的過濾器鏈 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- 注入安全管理器 -->
		<property name="securityManager" ref="securityManager"></property>
		<!-- 注入如果沒認證  跳轉的頁面 -->
		<property name="loginUrl" value="/index.jsp"></property>
		<!-- 未授權的跳轉頁 -->
		<property name="unauthorizedUrl" value="login/toUnauthorized.action"></property>
		<!-- 注入自定義的過濾器 -->
		<property name="filters">
			<map>
				<entry key="rememberMe" value-ref="rememberMe"></entry>
			</map>
		</property>
		<property name="filterChainDefinitions">
			<value>
				<!-- 放行系統首頁 -->
			    /index.jsp*=anon
			    <!-- 放行跳轉到登陸頁面的地  -->  
				/login/toLogin*=anon
				<!-- 放行登陸的方法 -->
				/login/login*=anon
				<!-- 其它的頁面都要認證 -->
				/**=rememberMe,user
				/*=authc
				/*/*=authc
			</value>
		</property>
	</bean>
</beans>
  • 在applicationContext.xml 引入(import)
    在這裏插入圖片描述

八、創建 包.listener 下面 AppListener.java

@WebListener
public class AppListener implements ServletContextListener{

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext context = sce.getServletContext();
		context.setAttribute("ctx", context.getContextPath());
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		
	}

}

============== 未完,待續 …=====================

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章