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>com.me</groupId>
<artifactId>shiro-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- 添加Servlet支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!-- 添加jtl支持 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- 添加Spring支持 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.1.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
<!-- 添加日志支持 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- 添加mybatis支持 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- jdbc驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.4</version>
</dependency>
</dependencies>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<span> </span>xmlns="http://java.sun.com/xml/ns/javaee"
<span> </span>xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
<span> </span>id="WebApp_ID" version="3.0">
<span> </span><display-name>shiro-web</display-name>
<span> </span><welcome-file-list>
<span> </span><welcome-file>index.jsp</welcome-file>
<span> </span></welcome-file-list>
<span> </span>
<span> </span>
<span> </span><!-- Spring监听器 -->
<span> </span><context-param>
<span> </span><param-name>contextConfigLocation</param-name>
<span> </span><!-- Spring配置文件 -->
<span> </span><param-value>classpath:spring/applicationContext.xml</param-value>
<span> </span></context-param>
<span> </span><listener>
<span> </span><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
<span> </span></listener>
<span> </span>
<span> </span><!-- shiro的filter -->
<span> </span><!-- shiro过虑器,DelegatingFilterProxy通过代理模式将spring容器中的bean和filter关联起来 -->
<span> </span><filter>
<span> </span><filter-name>shiroFilter</filter-name>
<span> </span><filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<span> </span><!-- 设置true由servlet容器控制filter的生命周期 -->
<span> </span><init-param>
<span> </span><param-name>targetFilterLifecycle</param-name>
<span> </span><param-value>true</param-value>
<span> </span></init-param>
<span> </span><!-- 设置spring容器filter的bean id,如果不设置则找与filter-name一致的bean-->
<span> </span><init-param>
<span> </span><param-name>targetBeanName</param-name>
<span> </span><param-value>shiroFilter</param-value>
<span> </span></init-param>
<span> </span></filter>
<span> </span><filter-mapping>
<span> </span><filter-name>shiroFilter</filter-name>
<span> </span><url-pattern>/*</url-pattern>
<span> </span></filter-mapping>
<span> </span>
<span> </span><!-- 添加对springmvc的支持 -->
<span> </span><servlet>
<span> </span><servlet-name>springMVC</servlet-name>
<span> </span><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<span> </span><init-param>
<span> </span><param-name>contextConfigLocation</param-name>
<span> </span><param-value>classpath:spring/spring-mvc.xml</param-value>
<span> </span></init-param>
<span> </span><load-on-startup>1</load-on-startup>
<span> </span><async-supported>true</async-supported>
<span> </span></servlet>
<span> </span><servlet-mapping>
<span> </span><servlet-name>springMVC</servlet-name>
<span> </span><url-pattern>*.do</url-pattern>
<span> </span></servlet-mapping>
<span> </span>
<span> </span><!-- post乱码处理 -->
<span> </span><filter>
<span> </span><filter-name>CharacterEncodingFilter</filter-name>
<span> </span><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<span> </span><init-param>
<span> </span><param-name>encoding</param-name>
<span> </span><param-value>utf-8</param-value>
<span> </span></init-param>
<span> </span></filter>
<span> </span><filter-mapping>
<span> </span><filter-name>CharacterEncodingFilter</filter-name>
<span> </span><url-pattern>/*</url-pattern>
<span> </span></filter-mapping>
<span> </span>
<span> </span>
</web-app>
applicationContext-shiro.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
<span> </span>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
<span> </span>xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
<span> </span>xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
<span> </span>xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<span> </span><!-- 自定义Realm -->
<span> </span><bean id="customRealm" class="cn.me.ssm.shiro.CustomRealm"/>
<span> </span>
<span> </span><!-- 安全管理器 -->
<span> </span><bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<span> </span> <property name="realm" ref="customRealm"/>
<span> </span></bean>
<span> </span>
<span> </span><!-- Shiro过滤器 -->
<span> </span><bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<span> </span> <!-- Shiro的核心安全接口,这个属性是必须的 -->
<span> </span> <property name="securityManager" ref="securityManager"/>
<span> </span> <!-- 身份认证失败,则跳转到登录页面的配置 -->
<span> </span> <property name="loginUrl" value="/user/login.do"/>
<span> </span> <!-- 认证成功统一跳转到/success.do,shiro认证成功自动到上一个请求路径 -->
<span> </span> <property name="successUrl" value="/success.do"/>
<span> </span> <!-- 权限认证失败,则跳转到指定页面 -->
<span> </span> <property name="unauthorizedUrl" value="/unauthor.jsp"/>
<span> </span> <!-- Shiro连接约束配置,即过滤链的定义 -->
<span> </span> <property name="filterChainDefinitions">
<span> </span> <value>
<span> </span> /**=authc
<span> </span> </value>
<span> </span> </property>
<span> </span></bean>
<span> </span>
<span> </span><!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<span> </span><bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<import resource="classpath:spring/applicationContext-*.xml"/>
</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: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-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
<!-- 使用spring组件扫描 -->
<context:component-scan base-package="cn.me.ssm.controller" />
<mvc:annotation-driven/>
<!-- 配置视图解析器 要求将jstl的包加到classpath -->
<!-- ViewResolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
自定义realm
package cn.me.ssm.shiro;
import java.util.ArrayList;
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.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
/**
* 自定义realm
* @author Administrator
*
*/
public class CustomRealm extends AuthorizingRealm{
@Override
public void setName(String name) {
// TODO Auto-generated method stub
super.setName("customRealm");
}
//用于认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//token是用户输入的
//第一步从token中取出身份信息
String userCode = (String) token.getPrincipal();
//第二步:根据用户输入的userCode从数据库查询
//...
//如果查询不到返回null
//数据库中用户帐号是zhangsan
if(!"zhangsan".equals(userCode)){
return null;
}
//模拟从数据库查询到密码
String password = "111111";
//如果查询到返回认证信息AuthenticationInfo
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userCode, password, this.getName());
return authenticationInfo;
}
//用于授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
//从principals获取主身份信息
//将getPrimaryPrincipal方法返回值转为真实身份类型
//(在上边doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中的身份类型)
String userCode = (String) principals.getPrimaryPrincipal();
//根据身份信息获取权限信息
//连接数据库.....
//模拟从数据库获取到数据
ArrayList<String> permissions= new ArrayList<>();
permissions.add("user:create");//用户的创建
permissions.add("items:add");//商品添加权限
//...
//将查询到授权信息填充到simpleAuthorizationInfo对象中
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
simpleAuthorizationInfo.addStringPermissions(permissions);
ArrayList<String> roles= new ArrayList<>();
roles.add("admin");//admin角色
roles.add("teacher");//teacher角色
simpleAuthorizationInfo.addRoles(roles);
//返回授权信息
return simpleAuthorizationInfo;
}
}
</pre><pre name="code" class="html">package cn.me.ssm.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import cn.me.ssm.exception.CustomException;
@Controller
public class LoginController {
@RequestMapping("/login")
public String first(){
return "login";
}
@RequestMapping("/user/login")
public String login(String username, String password, HttpServletRequest request) throws Exception {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
try {
subject.login(token);
Session session = subject.getSession();
System.out.println("sessionId:"+session.getId());
System.out.println("sessionHost:"+session.getHost());
System.out.println("sessionTimeout:"+session.getTimeout());
session.setAttribute("info", username);
return "redirect:/success.do";
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("password", password);
request.setAttribute("username", username);
request.setAttribute("errorMsg", "用户名或密码错误");
return "login";
}
}
@RequestMapping("/success")
public String success(){
return "success";
}
}
</pre>login.jsp<div></div><p></p><pre name="code" class="html"><%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
<form action="${pageContext.request.contextPath }/user/login.do" method="post">
userName:<input type="text" name="username" value="${username }"/><br/>
password:<input type="password" name="password" value="${password }"><br/>
<input type="submit" value="login"/><font color="red">${errorMsg }</font>
</form>
</body>
</html>
sucess.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>
${info }
欢迎你!
<br>
<shiro:hasRole name="admin">
欢迎有admin角色的用户!<shiro:principal/>
</shiro:hasRole>
<br>
<shiro:hasPermission name="user:create">
欢迎有user:create权限的用户!<shiro:principal/>
</shiro:hasPermission>
</body>
</html>
index.jsp
<%
response.sendRedirect("login.do");
%>