SSM整合shiro
1.添加依赖
<packaging>war</packaging>
<properties>
<!--统一管理spring所有的版本-->
<spring-version>4.3.6.RELEASE</spring-version>
</properties>
<dependencies>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope> <!--避免冲突-->
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope> <!--避免冲突-->
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--springmvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!--rest风格使用-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!--mybatis spring的插件,将mybatis交给spring来管理-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--spring的单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!--spring jdbc,包含事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- spring aop的面向切面的配置-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<!--日志信息-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--lombok,特别注意,与maven的tomcat插件冲突时,将scope设置为provided-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<!--为了使用@Resource注解-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<!--shiro-web依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.2</version>
</dependency>
<!--shiro-spring的依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.2</version>
</dependency>
</dependencies>
- 添加依赖后的pom文件
<?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>com.ym</groupId>
<artifactId>shiroSSM</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!--统一管理spring所有的版本-->
<spring-version>4.3.6.RELEASE</spring-version>
</properties>
<dependencies>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope> <!--避免冲突-->
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope> <!--避免冲突-->
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--springmvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!--rest风格使用-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<!--mybatis spring的插件,将mybatis交给spring来管理-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<!--spring的单元测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!--spring jdbc,包含事务-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- spring aop的面向切面的配置-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<!--日志信息-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--lombok,特别注意,与maven的tomcat插件冲突时,将scope设置为provided-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.6</version>
<scope>provided</scope>
</dependency>
<!--为了使用@Resource注解-->
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
<!--shiro-web依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.4.2</version>
</dependency>
<!--shiro-spring的依赖-->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.2</version>
</dependency>
</dependencies>
<build>
<!--不过滤java下的xml文件-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.修改web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<!--
将过滤器的生命周期从出生到死亡完全交给Spring来管理
-->
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--
使用springk框架写好的中文乱码过滤器来实现乱码的处理
-->
<filter>
<filter-name>encode</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>encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3.配置文件db.properties ; shiro-spring.xml ; spring-mvc.xml
- db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3307/rbac?useSSL=true&serverTimezone=UTC&characterEncoding=UTF-8
uname=root
upass=root
- shiro-spring.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="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="filterChainDefinitions">
<!--对页面角色权限的指定-->
<value>
/index.html=anon <!--匿名用户可以访问-->
/main.jsp=authc <!--认证之后的用户可以访问-->
/manager.jsp=authc,roles[manager] <!--认证后,且角色是manger的可以访问-->
/guest.jsp=authc,roles[guest] <!--认证后,且角色是guest的可以访问-->
/select.jsp=perms[select] <!--权限是select的可以访问-->
/delete.jsp=perms[delete] <!--权限是delete的可以访问-->
</value>
</property>
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myRealm" />
</bean>
<bean id="myRealm" class="com.ym.shiro.MyRealm" />
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>
- spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--引入数据库的配置文件信息-->
<context:property-placeholder location="classpath:db.properties" />
<!--注解驱动-->
<mvc:annotation-driven />
<!--配置默认资源可以被访问-->
<mvc:default-servlet-handler />
<!--设置包扫描-->
<context:component-scan base-package="com.ym.controller" />
<context:component-scan base-package="com.ym.service" />
<context:component-scan base-package="com.ym.dao" />
<!--druid数据源-->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${url}" />
<property name="driverClassName" value="${driver}" />
<property name="username" value="${uname}" />
<property name="password" value="${upass}" />
</bean>
<bean id="sf" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="ds" />
<property name="typeAliasesPackage" value="com.ym.entity" />
<property name="mapperLocations" value="classpath:mapper/*Mapper.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ym.dao" />
<property name="sqlSessionFactoryBeanName" value="sf" />
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
4MyRealm.java
package com.ym.shiro;
import com.ym.entity.Permission;
import com.ym.entity.Role;
import com.ym.entity.User;
import com.ym.service.IUserService;
import org.apache.shiro.authc.*;
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 javax.annotation.Resource;
import java.util.List;
public class MyRealm extends AuthorizingRealm {
@Resource
private IUserService userService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
String username = getAvailablePrincipal(principalCollection).toString();
List<Role> roles = userService.getAllRolesByUsername(username);
for (Role role : roles) {
info.addRole(role.getRname());
}
List<Permission> permissions = userService.getAllPermissionsByUsername(username);
for (Permission permission : permissions) {
info.addStringPermission(permission.getPname());
}
return info;
}
//认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
AuthenticationInfo info=null;
UsernamePasswordToken token=(UsernamePasswordToken) authenticationToken;
String username = token.getUsername();
char[] password = token.getPassword();
String pass=new String(password);
User u = userService.login(username, pass);
if (u!=null && u.getUid()!=0){
String name = getName();
info =new SimpleAuthenticationInfo(username,pass,name);
}
return info;
}
}
5.entity层的Javabean
- User.java : 用户
package com.ym.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
@Data
public class User implements Serializable {
private static final long serialVersionUID = 617289138502785533L;
private Integer uid;
private String username;
private String password;
private String tel;
private String addr;
private Set<Role> rs;
}
- Role.java : 角色
package com.ym.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
@Data
public class Role implements Serializable {
private static final long serialVersionUID = -74163700661732397L;
private Integer rid;
private String rname;
private String rdesc;
private Set<Permission> ps;
}
- Permission.java : 权限
package com.ym.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class Permission implements Serializable {
private static final long serialVersionUID = 581645870054218482L;
private Integer pid;
private String pname;
private String pdesc;
}
6.dao层接口IUserDao
package com.ym.dao;
import com.ym.entity.Permission;
import com.ym.entity.Role;
import com.ym.entity.User;
import java.util.List;
public interface IUserDao {
User login(User user);
List<Role> getAllRolesByUsername(String username);
List<Permission> getAllPermissionsByUsername(String username);
}
7.与dao层接口对应的mapper文件
- 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.ym.dao.IUserDao">
<select id="login" resultType="User">
select * from user where username=#{username} and password=#{password}
</select>
<select id="getAllRolesByUsername" resultType="Role">
select r.* from user u
inner JOIN user_role ur on u.uid = ur.uid
inner join Role r on r.rid=ur.rid
where u.username=#{username};
</select>
<select id="getAllPermissionsByUsername" resultType="Permission">
select p.* from user u
inner JOIN user_role ur on u.uid = ur.uid
inner join Role r on r.rid=ur.rid
INNER JOIN role_perms rp on r.rid = rp.rid
INNER JOIN permission p on p.pid = rp.pid
where u.username=#{username};
</select>
</mapper>
8.service层接口与实现类
- 接口 IUserService.java
package com.ym.service;
import com.ym.entity.Permission;
import com.ym.entity.Role;
import com.ym.entity.User;
import java.util.List;
public interface IUserService {
User login(String username, String pass);
List<Role> getAllRolesByUsername(String username);
List<Permission> getAllPermissionsByUsername(String username);
}
- 实现类UserServiceImpl.java
package com.ym.service.impl;
import com.ym.dao.IUserDao;
import com.ym.entity.Permission;
import com.ym.entity.Role;
import com.ym.entity.User;
import com.ym.service.IUserService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Resource
private IUserDao userDao;
@Override
public User login(String username, String pass) {
User u=new User();
u.setUsername(username);
u.setPassword(pass);
return userDao.login(u);
}
@Override
public List<Role> getAllRolesByUsername(String username) {
return userDao.getAllRolesByUsername(username);
}
@Override
public List<Permission> getAllPermissionsByUsername(String username) {
return userDao.getAllPermissionsByUsername(username);
}
}
9.controller层UserService.java
package com.ym.controller;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
@PostMapping("/login")
public String login(@RequestParam("username") String username,@RequestParam("password") String password){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(username,password);
try {
subject.login(token);
return "main.jsp";
} catch (AuthenticationException e) {
e.printStackTrace();
return "index.html";
}
}
}
10.前端页面
登陆成功之后,看是否拥有访问delete.jsp ; select.jsp ; manager.jsp ; guest.jsp的权限
index.html : 匿名用户访问
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1>this is index page.</h1>
<form action="UserServlet" method="post">
username:<input type="text" name="username" /><p />
password:<input type="text" name="password" /><p />
<input type="submit" value="submit" /><p />
</form>
</body>
</html>
- main.jsp : 认证之后的用户才可以访问
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<html>
<head>
<title>main</title>
</head>
<body>
<h1>this is main page.</h1>
<shiro:authenticated>i am login successfully.</shiro:authenticated><p />
<shiro:hasRole name="manager">i am a manager</shiro:hasRole><p /> <%--manager角色才会显示--%>
<shiro:hasRole name="guest">i am a guest</shiro:hasRole><p /> <%--guest角色才会显示--%>
<shiro:user>
welcome back zhenfu!
Not zhenfu? Click <a href="index.html">here</a> to login
</shiro:user><p />
<shiro:hasPermission name="select">i can select</shiro:hasPermission><p /> <%--select权限才可以显示--%>
<shiro:hasPermission name="delete">i can delete</shiro:hasPermission><p /> <%--delete权限才可以显示--%>
</body>
</html>
- manager.jsp : 用户角色是manager的用户才可以访问
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>manager</title>
</head>
<body>
<h1>i am a manager</h1>
</body>
</html>
- guest.jsp : 用户角色是guest的用户才可以访问
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>guest</title>
</head>
<body>
<h1>i am a guest</h1>
</body>
</html>
- select.jsp : 拥有select权限的用户才可以访问
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>select</title>
</head>
<body>
<h1>select</h1>
</body>
</html>
- delete.jsp : 拥有delete权限的用户才可以访问
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>delete</title>
</head>
<body>
<h1>delete</h1>
</body>
</html>