文章目录
- 一、数据库
- 二、搭建ssm的环境
- 三、集成shiro
- 四、使用shiro完成用户权限的开发
- 1 修改UserRealm
- 2.1 创建UserService
- 2.2 创建UserServiceImpl
- 2.3 修改UserMapper
- 2.4 修改UserMapper.xml
- 3.1 创建RoleService
- 3.2 创建RoleServiceImpl
- 3.3 修改RoleMapper
- 3.4修改RoleMapper.xml
- 4.1 创建PermissionService
- 4.2 创建PermissionServiceImpl
- 4.3 修改PermissionMapper
- 4.4 修改PermissionMapper.xml
- 5. 创建index.jsp
- 6.创建WEB-INF/view/login.jsp
- 7. 创建LoginController
- 8. UserController
- 9. WEB-INF/view/list.jsp
- 10.目录结构
一、数据库
1、准备数据库
2、数据结构
张三 -----》user:query user:add user:update user:delete
李四 -----》user:query user:add user:update
王五 -----》user:query user:export
二、搭建ssm的环境
1、创建项目
2、修改pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--<servlet.version>3.1.0</servlet.version>-->
<!--<jsp.version>2.3.1</jsp.version>-->
<!--<spring.version>4.3.24.RELEASE</spring.version>-->
<!--<mybatis.version>3.5.1</mybatis.version>-->
<!--<mybatis.spring.version>2.0.1</mybatis.spring.version>-->
<!--<mysql.version>8.0.17</mysql.version>-->
<!--<pagehelper.version>5.1.10</pagehelper.version>-->
<!--<druid.version>1.1.19</druid.version>-->
<!--<log4j.version>1.2.17</log4j.version>-->
<!--<slf4j.version>1.7.26</slf4j.version>-->
<!--<jackson.version>2.9.9</jackson.version>-->
<!--<shiro.version>1.4.1</shiro.version>-->
</properties>
<!--声明常量-->
<!---->
<dependencies>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!--spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.10</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.19</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.26</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.1</version>
</dependency>
</dependencies>
<build>
<finalName>ssm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!--<plugin>-->
<!-- <!– https://mvnrepository.com/artifact/org.apache.tomcat.maven/tomcat7-maven-plugin –>-->
<!-- <groupId>org.apache.tomcat.maven</groupId>-->
<!-- <artifactId>tomcat7-maven-plugin</artifactId>-->
<!-- <version>2.2</version>-->
<!-- <configuration>-->
<!-- <!– 配置urlencoding–>-->
<!-- <uriEncoding>UTF-8</uriEncoding>-->
<!-- <!– 配置urlencoding–>-->
<!-- <port>8081</port>-->
<!-- <!– 配置urlencoding–>-->
<!-- <path>/bjsxt</path>-->
<!-- </configuration>-->
<!--</plugin>-->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
3、创建包
4、创建db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shiro?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=password
maxActive=20
initialSize=1
maxWait=60000
minIdle=1
filters=stat,log4j,wall
5、创建application-dao.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.xsd">
<!--解析配置文件-->
<context:property-placeholder location="classpath:db.properties" system-properties-mode="FALLBACK"></context:property-placeholder>
<!--声明数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="maxActive" value="${maxActive}"></property><!--最大活动连接数-->
<property name="initialSize" value="${initialSize}"></property><!--初始连接数-->
<property name="maxWait" value="${maxWait}"></property><!--最大等待时间-->
<property name="minIdle" value="${minIdle}"></property><!--最少活跃连接数-->
<property name="filters" value="${filters}"></property><!--最少活跃连接数-->
</bean>
<!--创建mybatis的configration对象-->
<bean id="configuration" class="org.apache.ibatis.session.Configuration">
<property name="logImpl" value="org.apache.ibatis.logging.stdout.StdOutImpl"></property>
</bean>
<!--创建SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据元-->
<property name="dataSource" ref="dataSource"></property>
<!--注入配置类-->
<property name="configuration" ref="configuration"></property>
<!--扫描mapper.xml-->
<property name="mapperLocations">
<array>
<value>classpath:mapper/*Mapper.xml</value>
</array>
</property>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor"></bean>
</array>
</property>
</bean>
<!--配置mapper接口的扫描-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.sxt.mapper"></property>
<!--<property name="basePackage">
<value>
com.sxt.mapper
com.bjsxt.mapper
</value>
</property>-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean>
</beans>
6、创建db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/shiro?useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=password
#最大连接数
maxActive=20
#初始连接数
initialSize=1
#最大等待时间
maxWait=60000
#初始活跃数
minIdle=1
filters=stat,log4j,wall
7、创建application-service.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--扫描-->
<context:component-scan base-package="com.sxt.service.impl"></context:component-scan>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务的传播特性-->
<tx:advice transaction-manager="transactionManager" id="advise">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="save" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="reset*" propagation="REQUIRED"/>
<tx:method name="change*" propagation="REQUIRED"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!--配置aop-->
<aop:config>
<aop:pointcut id="pc" expression="execution(* com.sxt.service.impl.*.*(..))"/>
<!--注入操作-->
<aop:advisor advice-ref="advise" pointcut-ref="pc"></aop:advisor>
</aop:config>
</beans>
8、创建applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<import resource="classpath:application-dao.xml"></import>
<import resource="classpath:application-service.xml"></import>
</beans>
9、创建springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--扫包-->
<context:component-scan base-package="com.sxt.controller"></context:component-scan>
<!--配置适配器和映射器-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--指定前缀后缀-->
<property name="suffix" value=".jsp"></property>
<property name="prefix" value="/WEB-INF/view/"></property>
</bean>
<!--配置文件上传-->
<!--配置拦截器-->
<!--配置静态资源放行-->
<mvc:default-servlet-handler/>
</beans>
10、配置web.xml
<?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"
version="3.1">
<!--配置编码过滤器 开始-->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/</url-pattern>
<!--<url-pattern>springmvc</url-pattern>-->
</filter-mapping>
<!--配置编码过滤器 结束-->
<!--配置spring的监听器加载applicationContext.xml-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!--配置前端控制器 开始-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--注入springmvc.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!--启动创建-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!--配置前端控制器 结束-->
<!--配置欢迎页面-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
三、集成shiro
1、生成User UserMapper UserMapper.xml
public class User {
private Integer userid;
private String username;
private String userpwd;
private String sex;
private String address;
package com.sxt.mapper;
import org.apache.ibatis.annotations.Param;
import com.sxt.domain.User;
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);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sxt.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.sxt.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="com.sxt.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="com.sxt.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="com.sxt.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="com.sxt.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
<include refid="Base_Column_List" />
from user
where username=#{username}
</select>
</mapper>
2、生成Role RoleMapper RoleMapper.xml
public class Role {
private Integer roleid;
private String rolename;
package com.sxt.mapper;
import java.util.List;
import com.sxt.domain.Role;
public interface RoleMapper {
int deleteByPrimaryKey(Integer roleid);
int insert(Role record);
int insertSelective(Role record);
Role selectByPrimaryKey(Integer roleid);
int updateByPrimaryKeySelective(Role record);
int updateByPrimaryKey(Role record);
/**
* 查询用户ID查询角色
* @param userId
* @return
*/
List<Role> queryRolesByUserId(Integer userId);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sxt.mapper.RoleMapper">
<resultMap id="BaseResultMap" type="com.sxt.domain.Role">
<id column="roleid" jdbcType="INTEGER" property="roleid" />
<result column="rolename" jdbcType="VARCHAR" property="rolename" />
</resultMap>
<sql id="Base_Column_List">
roleid, rolename
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from role
where roleid = #{roleid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from role
where roleid = #{roleid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.sxt.domain.Role">
insert into role (roleid, rolename)
values (#{roleid,jdbcType=INTEGER}, #{rolename,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.sxt.domain.Role">
insert into role
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="roleid != null">
roleid,
</if>
<if test="rolename != null">
rolename,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="roleid != null">
#{roleid,jdbcType=INTEGER},
</if>
<if test="rolename != null">
#{rolename,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.sxt.domain.Role">
update role
<set>
<if test="rolename != null">
rolename = #{rolename,jdbcType=VARCHAR},
</if>
</set>
where roleid = #{roleid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.sxt.domain.Role">
update role
set rolename = #{rolename,jdbcType=VARCHAR}
where roleid = #{roleid,jdbcType=INTEGER}
</update>
<!-- 根据用户名查询角色 -->
<select id="queryRolesByUserId" resultMap="BaseResultMap" >
select t1.* from role t1 inner join user_role t2 on(t1.roleid=t2.roleid)
where t2.userid=#{value}
</select>
</mapper>
3、生成Permission Permission Mapper PermissionMapper.xml
public class Permission {
private Integer perid;
private String pername;
private String percode;
package com.sxt.mapper;
import java.util.List;
import com.sxt.domain.Permission;
public interface PermissionMapper {
int deleteByPrimaryKey(Integer perid);
int insert(Permission record);
int insertSelective(Permission record);
Permission selectByPrimaryKey(Integer perid);
int updateByPrimaryKeySelective(Permission record);
int updateByPrimaryKey(Permission record);
List<Permission> queryPermissionByUserId(Integer userId);
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.sxt.mapper.PermissionMapper">
<resultMap id="BaseResultMap" type="com.sxt.domain.Permission">
<id column="perid" jdbcType="INTEGER" property="perid" />
<result column="pername" jdbcType="VARCHAR" property="pername" />
<result column="percode" jdbcType="VARCHAR" property="percode" />
</resultMap>
<sql id="Base_Column_List">
perid, pername, percode
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from permission
where perid = #{perid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from permission
where perid = #{perid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.sxt.domain.Permission">
insert into permission (perid, pername, percode
)
values (#{perid,jdbcType=INTEGER}, #{pername,jdbcType=VARCHAR}, #{percode,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.sxt.domain.Permission">
insert into permission
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="perid != null">
perid,
</if>
<if test="pername != null">
pername,
</if>
<if test="percode != null">
percode,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="perid != null">
#{perid,jdbcType=INTEGER},
</if>
<if test="pername != null">
#{pername,jdbcType=VARCHAR},
</if>
<if test="percode != null">
#{percode,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.sxt.domain.Permission">
update permission
<set>
<if test="pername != null">
pername = #{pername,jdbcType=VARCHAR},
</if>
<if test="percode != null">
percode = #{percode,jdbcType=VARCHAR},
</if>
</set>
where perid = #{perid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.sxt.domain.Permission">
update permission
set pername = #{pername,jdbcType=VARCHAR},
percode = #{percode,jdbcType=VARCHAR}
where perid = #{perid,jdbcType=INTEGER}
</update>
<!-- 根据用户ID查询权限 -->
<select id="queryPermissionByUserId" resultMap="BaseResultMap">
select distinct t1.* from permission t1 inner join role_permission
t2 inner join user_role t3
on(t1.perid=t2.perid and t2.roleid=t3.roleid)
where t3.userid=#{value}
</select>
</mapper>
4、创建UserRealm
public class UserRealm extends AuthorizingRealm {
//做认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
return null;
}
//做授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
return null;
}
}
5、创建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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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="com.sxt.realm.UserRealm">
<!--注入凭证匹配器-->
<property name="credentialsMatcher" ref="credentialsMatcher"></property>
</bean>
<!--配置SecurityMannager-->
<bean id="securityMannager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--注入realm-->
<property name="realm" ref="userRealm"></property>
</bean>
<!--配置shiro的过滤器链,这里的id必须和web.xml里面的配置一样-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--注入安全管理器链-->
<property name="securityManager" ref="securityMannager"></property>
<!--注入未登录的跳转页面,默认的是webapp/login.jsp-->
<property name="loginUrl" value="/index.jsp"></property>
<!--注入未授权的访问页面-->
<property name="unauthorizedUrl" value="/unauthorized.jsp"></property>
<!--配置过滤器链-->
<property name="filterChainDefinitions">
<value>
<!--放行index.jsp-->
/index.jsp*=anon
<!--放行跳转到登录页面的路径-->
/login/toLogin*=anon
<!--放行登录的请求-->
/login/login*=anon
<!--设置登出的路径-->
/login/logout*=logout
<!--设置其他路径都拦截-->
/**=authc
</value>
</property>
</bean>
</beans>
6、修改applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:application-dao.xml"></import>
<import resource="classpath:application-service.xml"></import>
<import resource="classpath:application-shiro.xml"></import>
</beans>
7、修改web.xml
<?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"
version="3.1">
<!-- 配置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>
<!-- 这里面的shiroFilter必须和application-shiro.xml里面的
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean" >id 一样 -->
<param-name>targetBeanName</param-name>
<param-value>shiroFilter</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<servlet-name>dispatcherServlet</servlet-name>
</filter-mapping>
<!-- 配置shiro的集成结束 -->
<!--配置编码过滤器 开始-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<servlet-name>dispatcherServlet</servlet-name>
</filter-mapping>
<!--配置编码过滤器 结束-->
<!--配置spring的监听器加载applicationContext.xml-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext.xml</param-value>
</context-param>
<!--配置前端控制器 开始-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--注入springmvc.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:springmvc.xml</param-value>
</init-param>
<!--启动创建-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!--配置前端控制器 结束-->
<!--配置欢迎页面-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
四、使用shiro完成用户权限的开发
1 修改UserRealm
public class UserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private PermissionService permissionService;
@Override
public String getName() {
return this.getClass().getSimpleName();
}
//做认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获取用户输入的姓名
String username = token.getPrincipal().toString();
User user = userService.queryUserByUserName(username);
if (null!=user){
//封装ActiveUser:根据姓名查询角色和权限,封装到ActiveUser
List<String> roles = roleService.queryRolesByUserId(user.getUserid());
List<String> permission = permissionService.queryPermissionByUserId(user.getUserid());
ActiveUser activeUser = new ActiveUser(user,roles,permission);
//创建盐
ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername()+user.getAddress());
//创建对象
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser,user.getUserid(),credentialsSalt,this.getName());
return info;
}
return null;
}
//做授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
List<String> roles = activeUser.getRoles();
List<String> permissions = activeUser.getPermissions();
if (null!=roles&&roles.size()>0){
info.addRoles(roles);
}
if (null!=permissions&&permissions.size()>0){
info.addStringPermissions(permissions);
}
return info;
}
}
2.1 创建UserService
public interface UserService {
/**
* 根据用户名查询用户对象
*/
public User queryUserByUserName(String username);
}
2.2 创建UserServiceImpl
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User queryUserByUserName(String username) {
return userMapper.queryUserByUserName(username);
}
}
2.3 修改UserMapper
package com.sxt.mapper;
import com.sxt.domain.User;
import org.apache.ibatis.annotations.Param;
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);
//User queryUserByUserName(String username);
}
2.4 修改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="com.sxt.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.sxt.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="queryUserByUserName" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where username=#{username}
</select>
</mapper>
3.1 创建RoleService
public interface RoleService {
/**
* 根据用户ID查询角色
*
*/
public List<String> queryRolesByUserId(Integer userId);
}
3.2 创建RoleServiceImpl
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Override
public List<String> queryRolesByUserId(Integer userId) {
List<Role> list = roleMapper.queryRolesByUserId(userId);
List<String> roles=new ArrayList<String>();
for (Role role : list) {
roles.add(role.getRolename());
}
return roles;
}
}
3.3 修改RoleMapper
public interface RoleMapper {
int deleteByPrimaryKey(Integer roleid);
int insert(Role record);
int insertSelective(Role record);
Role selectByPrimaryKey(Integer roleid);
int updateByPrimaryKeySelective(Role record);
int updateByPrimaryKey(Role record);
/**
* 查询用户ID查询角色
* @param userId
* @return
*/
List<Role> queryRolesByUserId(Integer userId);
}
3.4修改RoleMapper.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="com.sxt.mapper.RoleMapper">
<resultMap id="BaseResultMap" type="com.sxt.domain.Role">
<id column="roleid" jdbcType="INTEGER" property="roleid" />
<result column="rolename" jdbcType="VARCHAR" property="rolename" />
</resultMap>
<sql id="Base_Column_List">
roleid, rolename
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from role
where roleid = #{roleid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from role
where roleid = #{roleid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.sxt.domain.Role">
insert into role (roleid, rolename)
values (#{roleid,jdbcType=INTEGER}, #{rolename,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.sxt.domain.Role">
insert into role
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="roleid != null">
roleid,
</if>
<if test="rolename != null">
rolename,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="roleid != null">
#{roleid,jdbcType=INTEGER},
</if>
<if test="rolename != null">
#{rolename,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.sxt.domain.Role">
update role
<set>
<if test="rolename != null">
rolename = #{rolename,jdbcType=VARCHAR},
</if>
</set>
where roleid = #{roleid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.sxt.domain.Role">
update role
set rolename = #{rolename,jdbcType=VARCHAR}
where roleid = #{roleid,jdbcType=INTEGER}
</update>
<!-- 根据用户名查询角色 -->
<select id="queryRolesByUserId" resultMap="BaseResultMap" >
select t1.* from role t1
inner join user_role t2 on(t1.roleid=t2.roleid)
where t2.userid=#{value}
</select>
</mapper>
4.1 创建PermissionService
public interface PermissionService {
/**
* 根据用户ID查询权限
*/
public List<String> queryPermissionByUserId(Integer userId);
}
4.2 创建PermissionServiceImpl
@Service
public class PermissionServiceImpl implements PermissionService {
@Autowired
private PermissionMapper permissionMapper;
@Override
public List<String> queryPermissionByUserId(Integer userId) {
List<Permission> list = permissionMapper.queryPermissionByUserId(userId);
List<String> perimssions = new ArrayList<>();
for (Permission permission : list) {
perimssions.add(permission.getPercode());
}
return perimssions;
}
}
4.3 修改PermissionMapper
public interface PermissionMapper {
int deleteByPrimaryKey(Integer perid);
int insert(Permission record);
int insertSelective(Permission record);
Permission selectByPrimaryKey(Integer perid);
int updateByPrimaryKeySelective(Permission record);
int updateByPrimaryKey(Permission record);
List<Permission> queryPermissionByUserId(Integer userId);
}
4.4 修改PermissionMapper.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="com.sxt.mapper.PermissionMapper">
<resultMap id="BaseResultMap" type="com.sxt.domain.Permission">
<id column="perid" jdbcType="INTEGER" property="perid" />
<result column="pername" jdbcType="VARCHAR" property="pername" />
<result column="percode" jdbcType="VARCHAR" property="percode" />
</resultMap>
<sql id="Base_Column_List">
perid, pername, percode
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from permission
where perid = #{perid,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from permission
where perid = #{perid,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.sxt.domain.Permission">
insert into permission (perid, pername, percode
)
values (#{perid,jdbcType=INTEGER}, #{pername,jdbcType=VARCHAR}, #{percode,jdbcType=VARCHAR}
)
</insert>
<insert id="insertSelective" parameterType="com.sxt.domain.Permission">
insert into permission
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="perid != null">
perid,
</if>
<if test="pername != null">
pername,
</if>
<if test="percode != null">
percode,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="perid != null">
#{perid,jdbcType=INTEGER},
</if>
<if test="pername != null">
#{pername,jdbcType=VARCHAR},
</if>
<if test="percode != null">
#{percode,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.sxt.domain.Permission">
update permission
<set>
<if test="pername != null">
pername = #{pername,jdbcType=VARCHAR},
</if>
<if test="percode != null">
percode = #{percode,jdbcType=VARCHAR},
</if>
</set>
where perid = #{perid,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.sxt.domain.Permission">
update permission
set pername = #{pername,jdbcType=VARCHAR},
percode = #{percode,jdbcType=VARCHAR}
where perid = #{perid,jdbcType=INTEGER}
</update>
<!-- 根据用户ID查询权限 -->
<select id="queryPermissionByUserId" resultMap="BaseResultMap">
select distinct t1.* from permission t1
inner join role_permission t2
inner join user_role t3
on(t1.perid=t2.perid and t2.roleid=t3.roleid)
where t3.userid=#{value}
</select>
</mapper>
5. 创建index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>asd</h1>
<jsp:forward page="login/toLogin.action"></jsp:forward>
</body>
</html>
6.创建WEB-INF/view/login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2 align="center">用户登陆</h2>
<form action="${pageContext.request.contextPath}/login/login.action" method="post">
<table width="30%" align="center" border="1" cellpadding="2" cellspacing="2">
<tr>
<td align="right">用户名:</td>
<td>
<input type="text" name="username" >
</td>
</tr>
<tr>
<td align="right">密码:</td>
<td>
<input type="password" name="pwd" >
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" value="登陆">
</td>
</tr>
</table>
</form>
</body>
</html>
7. 创建LoginController
@Controller
@RequestMapping("login")
public class LoginController {
/**
* 跳转到登录页面
*/
@RequestMapping("toLogin")
public String toLogin(){
return "login";
}
/**
* 做登录
*/
@RequestMapping("login")
public String login(String username, String pwd, HttpSession session){
//得到主体
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username,pwd);
try{
subject.login(token);
ActiveUser activeUser = (ActiveUser) subject.getPrincipal();
session.setAttribute("user",activeUser.getUser());
return "redirect:/user/toUserManager.action";
}catch (AuthenticationException e){
e.printStackTrace();//重定向不走视图解析器
return "redirect:/index.jsp";
}
}
}
8. UserController
package com.sxt.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@Controller
@RequestMapping("user")
public class UserController {
@RequestMapping("toUserManager")
public String toUserManager(){
return "list";
}
@RequestMapping("query")
@ResponseBody
public Map<String,Object> query(){
Map<String,Object> map = new HashMap<>();
map.put("msg","query");
return map;
}
@RequestMapping("add")
@ResponseBody
public Map<String,Object> add(){
Map<String,Object> map = new HashMap<>();
map.put("msg","add");
return map;
}
@RequestMapping("update")
@ResponseBody
public Map<String,Object> update(){
Map<String,Object> map = new HashMap<>();
map.put("msg","update");
return map;
}
@RequestMapping("export")
@ResponseBody
public Map<String,Object> export(){
Map<String,Object> map = new HashMap<>();
map.put("msg","export");
return map;
}
@RequestMapping("delete")
@ResponseBody
public Map<String,Object> delete(){
Map<String,Object> map = new HashMap<>();
map.put("msg","delete");
return map;
}
}
9. WEB-INF/view/list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<shiro:hasPermission name="user:query">
<h1><a href="user/query.action">查询用户</a></h1>
</shiro:hasPermission>
<shiro:hasPermission name="user:add">
<h1><a href="user/add.action">添加用户</a></h1>
</shiro:hasPermission>
<shiro:hasPermission name="user:update">
<h1><a href="user/update.action">修改用户</a></h1>
</shiro:hasPermission>
<shiro:hasPermission name="user:delete">
<h1><a href="user/delete.action">删除用户</a></h1>
</shiro:hasPermission>
<shiro:hasPermission name="user:export">
<h1><a href="user/export.action">导出用户</a></h1>
</shiro:hasPermission>
</body>
</html>