一、pom.xml添加依赖
<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>sdm.cn</groupId>
<artifactId>sdm-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.8</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.1</version>
</dependency>
</dependencies>
</project>
二、web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>sdm-web</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:application-*.xml,
classpath:spring-shiro.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<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>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</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>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<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>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
三、spring-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/user/showLogin.do" />
<property name="successUrl" value="/dormitory/showIndex.do" />
<property name="unauthorizedUrl" value="/unauthorized" />
<property name="filters">
<util:map>
<entry key="logout" value-ref="logoutFilter" />
</util:map>
</property>
<property name="filterChainDefinitions">
<value>
/css/**=anon
/images/**=anon
/js/**=anon
/user/showLogin.do=anon
/user/login.do=anon
/user/exit.do = logout
/** = authc
</value>
</property>
</bean>
<bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
<property name="redirectUrl" value="/user/showLogin.do" />
</bean>
<bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="sid" />
<property name="httpOnly" value="true" />
<property name="maxAge" value="-1" />
</bean>
<bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<property name="sessionIdGenerator" ref="sessionIdGenerator" />
</bean>
<bean name="sessionValidationScheduler" class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
<property name="interval" value="1800000" />
<property name="sessionManager" ref="sessionManager" />
</bean>
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="globalSessionTimeout" value="1800000" />
<property name="deleteInvalidSessions" value="true" />
<property name="sessionValidationSchedulerEnabled" value="true" />
<property name="sessionValidationScheduler" ref="sessionValidationScheduler" />
<property name="sessionDAO" ref="sessionDAO" />
<property name="sessionIdCookieEnabled" value="true" />
<property name="sessionIdCookie" ref="sessionIdCookie" />
</bean>
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myUserRealm" />
<property name="sessionManager" ref="sessionManager" />
</bean>
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"
value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean>
<bean id="myUserRealm" class="cn.sdm.shiro.MyUserRealm">
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>
四、Controller 添加异步提交登录请求方法
@RequestMapping("/login.do")
@ResponseBody
public ResponseResult<Void> login(String username, String password, String inputCaptcha){
Subject subject = SecurityUtils.getSubject();
Session session=subject.getSession();
ResponseResult<Void> rr = null;
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
rr = new ResponseResult<Void>(1,"登录成功");
System.out.println("登录成功");
} catch (AuthenticationException e) {
rr = new ResponseResult<Void>(0,"用户名或密码错误");
System.out.println("登录失败: "+e.getMessage());
}
return rr;
}
五、MyUserRealm
package cn.shiro;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.ObjectUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import cn.bean.User;
import cn.mapper.UserMapper;
import cn.service.UserService;
import cn.service.ex.PasswordNotMatchException;
public class MyUserRealm extends AuthorizingRealm {
@Autowired
private UserService userService;
@Autowired
private UserMapper userMapper;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
String username =(String) principalCollection.getPrimaryPrincipal();
System.out.println("username:"+username);
List<Map<String,Object>> permissionsList = userService.selectPermissionsByUsername(username);
Set<String> permissions = new HashSet<String>();
for(Map<String,Object> map : permissionsList){
permissions.add(ObjectUtils.toString(map.get("permissionCode")));
}
List<Map<String,Object>> rolesList = userService.selectRolesByUsername(username);
Set<String> roles = new HashSet<String>();
for(Map<String,Object> map : rolesList){
roles.add(ObjectUtils.toString(map.get("roleName")));
}
System.out.println("roles: "+roles.toString());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.setStringPermissions(permissions);
info.setRoles(roles);
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken t = (UsernamePasswordToken) token;
String username= token.getPrincipal().toString();
String password= new String(t.getPassword());
User user = userMapper.selectByUsername(username);
String passwordInDB = user.getPassword();
SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(username,passwordInDB,this.getName());
Session session=SecurityUtils.getSubject().getSession();
session.setAttribute("user", user);
return info;
}
}
六、前端部分
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<%@ taglib prefix="shiroextend" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8" />
<title>XXX管理平台</title>
<script src="../js/jquery-3.1.1.min.js"></script>
<script src="../js/jquery.cookie.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div class="left-container">
<ul class="left-menu" onclick="">
<li class="big-menu" id="">
<img class="icon1" src="../images/icon/dormitory.png"/>
<a href="#" class="menu1">宿舍管理<img class="icon2" src="../images/icon/tobottom.png"/></a>
<ul class="small-menu">
<li class="menu2" id="" onclick="">
<a href="../dormitory/showIndex.do"> 宿舍查看</a>
</li>
<%-- <shiro:hasRole name="管理员"> --%>
<shiro:hasPermission name="dormitory_manage">
<li class="menu2" id="" onclick="">
<a href="../dormitory/dormitoryManage.do"> 宿舍调整</a>
</li>
</shiro:hasPermission>
<%-- </shiro:hasRole> --%>
</ul>
</li>
<shiroextend:hasAnyPermissions name="dormitory_cost,apartment_cost">
<li class="big-menu" id="">
<img class="icon1" src="../images/icon/cost.png"/>
<a href="#" class="menu1">费用管理<img class="icon2" src="../images/icon/tobottom.png"/></a>
<ul class="small-menu">
<shiro:hasPermission name="dormitory_cost">
<li class="menu2" id="" onclick="">
<a href="../cost/dormitoryCost.do"> 宿舍费用</a>
</li>
</shiro:hasPermission>
<shiro:hasPermission name="apartment_cost">
<li class="menu2" id="" onclick="">
<a href="../cost/apartmentCost.do"> 公寓物品费用</a>
</li>
</shiro:hasPermission>
</ul>
</li>
</shiroextend:hasAnyPermissions>
<shiroextend:hasAnyPermissions name="role_manage,account_manage">
<li class="big-menu" id="">
<img class="icon1" src="../images/icon/user.png"/>
<a href="#" class="menu1">用户管理<img class="icon2" src="../images/icon/tobottom.png"/></a>
<ul class="small-menu">
<shiro:hasPermission name="role_manage">
<li class="menu2" id="" onclick="">
<a href="../user/roleManage.do"> 角色管理</a>
</li>
</shiro:hasPermission>
<shiro:hasPermission name="account_manage">
<li class="menu2" id="" onclick="">
<a href="../user/accountManage.do"> 账号管理</a>
</li>
</shiro:hasPermission>
</ul>
</li>
</shiroextend:hasAnyPermissions>
</ul>
</div>
<%@ include file="update_password.jsp" %>
</body>
</html>