上一篇搭建Maven、SSM框架详细步骤,然后本文在此基础上,集成shiro框架
文章目录
一、创建数据库(数据库名:shiro,多对多关系)二、修改pom.xml引入shiro包三、创建domain下的类,mapper接口,mapper.xml 文件1.创建User类、 UserMapper接口、UserMapper.xml2.创建Role类、 RoleMapper接口、RoleMapper.xml3.创建Permission类、PermissionMapper接口、 PermissionMapper.xml以user为例
四、创建ActiverUser五、创建UserRealm六、修改web.xml七、创建application-shiro.xml 并在applicationContext.xml 引入(import)八、创建 包.listener 下面 AppListener.java============== 未完,待续 ......=====================
一、创建数据库(数据库名:shiro,多对多关系)
运行 shiro.sql 脚本添加数据库
SET FOREIGN_KEY_CHECKS
=0;
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
;
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');
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
;
INSERT INTO `role
` VALUES ('1', '超级管理员');
INSERT INTO `role
` VALUES ('2', 'CEO');
INSERT INTO `role
` VALUES ('3', '保安');
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
;
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');
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
;
INSERT INTO `user` VALUES ('1', 'zhangsan', '639ffb0cbcca39d4fff8348844b1974e', '男', '武汉');
INSERT INTO `user` VALUES ('2', 'lisi', '0d303fa8e2e2ca98555f23a731a58dd9', '女', '北京');
INSERT INTO `user` VALUES ('3', 'wangwu', '473c41db9af5cc0d90e7adfd2b6d9180', '女', '成都');
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
;
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>
<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
);
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
);
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
);
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
<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>
<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>
七、创建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>
<bean id="userRealm" class="包.realm.UserRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"></property>
</bean>
<bean id="cookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="rememberMe"></constructor-arg>
<property name="httpOnly" value="true"></property>
<property name="maxAge" value="604800"></property>
</bean>
<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">
<property name="realm" ref="userRealm"></property>
<property name="rememberMeManager" ref="cookieManager"></property>
</bean>
<bean id="rememberMe" class="包.filter.RememberMeFilter"></bean>
<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
) {
}
}
============== 未完,待续 …=====================