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>com.qfedu</groupId>
<artifactId>ssm_shiro</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!--统一管理spring所有的版本-->
<spring-version>4.3.6.RELEASE</spring-version>
</properties>
<dependencies>
<!--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>5.1.44</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.0</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.6.8</version>
</dependency>
<!--druid数据源-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</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>
<!--jsp-->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!--serlvet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!--jstl-->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<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>8889</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
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">
<!-- The filter-name matches name of a 'shiroFilter' bean inside applicationContext.xml -->
<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>
<!--配置Springmvc-->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring-mvc.xml
<!-- classpath:spring-mybatis.xml-->
</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
db.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/rbac?useSSL=false
user=root
pass=wangwei
shiro-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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" 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/>
<!--使用默认的Servlet来响应静态文件-->
<mvc:default-servlet-handler/>
<!--包扫描-->
<context:component-scan base-package="com.qfedu"/>
<!--
druid数据源
-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${user}"/>
<!--<property name="password" value="${password}"/>-->
<property name="password" value="${pass}"/>
</bean>
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.qfedu.entity"/>
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.qfedu.dao"/>
<property name="sqlSessionFactoryBeanName" value="sessionFactory" />
</bean>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
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"/>
<!-- override these for application-specific URLs if you like:
<property name="loginUrl" value="/login.jsp"/>
<property name="successUrl" value="/home.jsp"/>
<property name="unauthorizedUrl" value="/unauthorized.jsp"/> -->
<!-- The 'filters' property is not necessary since any declared javax.servlet.Filter bean -->
<!-- defined will be automatically acquired and available via its beanName in chain -->
<!-- definitions, but you can perform instance overrides or name aliases here if you like: -->
<!-- <property name="filters">
<util:map>
<entry key="anAlias" value-ref="someFilter"/>
</util:map>
</property> -->
<property name="filterChainDefinitions">
<value>
/login.jsp=anon
/main.jsp=authc
/manager.jsp=roles[manager]
/guest.jsp=roles[guest]
</value>
</property>
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!-- Single realm app. If you have multiple realms, use the 'realms' property instead. -->
<property name="realm" ref="myRealm"/>
<!-- By default the servlet container sessions will be used. Uncomment this line
to use shiro's native sessions (see the JavaDoc for more): -->
<!-- <property name="sessionMode" value="native"/> -->
</bean>
<bean class="com.qfedu.shiro.MyRealm" id="myRealm" />
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>
entity类
user.java
package com.qfedu.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
/**
* (User)实体类
*
* @author makejava
* @since 2020-04-14 11:06:42
*/
@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.qfedu.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
/**
* (Role)实体类
*
* @author makejava
* @since 2020-04-14 11:06:42
*/
@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.qfedu.entity;
import lombok.Data;
import java.io.Serializable;
import java.util.Set;
/**
* (Permission)实体类
*
* @author makejava
* @since 2020-04-14 11:06:42
*/
@Data
public class Permission implements Serializable {
private static final long serialVersionUID = 581645870054218482L;
private Integer pid;
private String pname;
private String pdesc;
}
dao
IUserDao.java
package com.qfedu.dao;
import com.qfedu.entity.Permission;
import com.qfedu.entity.Role;
import com.qfedu.entity.User;
import java.util.List;
public interface IUserDao {
User login(User user);
List<Role> getAllRolesByUsername(String username);
List<Permission> getAllPermissionsByUsername(String username);
}
service
IUserService.java
package com.qfedu.service;
import com.qfedu.entity.Permission;
import com.qfedu.entity.Role;
import com.qfedu.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);
}
service.impl
UserServiceImpl.java
package com.qfedu.service.impl;
import com.qfedu.dao.IUserDao;
import com.qfedu.entity.Permission;
import com.qfedu.entity.Role;
import com.qfedu.entity.User;
import com.qfedu.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);
}
}
controller
UserController.java
package com.qfedu.controller;
import com.qfedu.service.IUserService;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
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;
import javax.annotation.Resource;
@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 {
System.out.println(111);
subject.login(token);
System.out.println(000);
return "main.jsp";
} catch (AuthenticationException e) {
System.out.println(222);
e.printStackTrace();
return "login.jsp";
}
}
}
shiro
MyRealm.java
package com.qfedu.shiro;
import com.qfedu.entity.Permission;
import com.qfedu.entity.Role;
import com.qfedu.entity.User;
import com.qfedu.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 principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
String username = getAvailablePrincipal(principals).toString();
List<Role> list = userService.getAllRolesByUsername(username);
for (Role r : list) {
info.addRole(r.getRname());
}
List<Permission> permissionList = userService.getAllPermissionsByUsername(username);
for (Permission p : permissionList) {
info.addStringPermission(p.getPname());
}
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
AuthenticationInfo info = null;
UsernamePasswordToken tk = (UsernamePasswordToken) token;
String username = tk.getUsername();
char[] password = tk.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;
}
}
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 />
<shiro:hasRole name="guest">i am a guest</shiro:hasRole><p />
<shiro:user>
welcome back <shiro:principal/>!
Not <shiro:principal/>? Click <a href="index.html">here</a> to login
</shiro:user><p />
<shiro:hasPermission name="select">i can select</shiro:hasPermission><p />
<shiro:hasPermission name="delete">i can delete</shiro:hasPermission><p />
</body>
</html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
<form action="login" method="post" >
username: <input type="text" name="username" /><p />
password: <input type="text" name="password" /><p />
<input type="submit" name="submit" /><p />
</form>
</body>
</html>