首先需要添加shiro的spring整合包。

要想在WEB应用中整合Spring和Shiro的话,首先需要添加一个由spring代理的过滤器如下:

<!-- 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>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter> ... <!-- Make sure any request you want accessible to Shiro is filtered. /* catches all -->
<!-- requests. Usually this filter mapping is defined first (before all others) to -->
<!-- ensure that Shiro works in subsequent filters in the filter chain: -->
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

其次,就是在spring的配置文件中,加入shiro的配置。

<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>
# some example chain definitions:
/admin/** = authc, roles[admin]
/docs/** = authc, perms[document:read]
/** = authc
# more URL-to-FilterChain definitions here
</value>
</property>
</bean> <!-- Define any javax.servlet.Filter beans you want anywhere in this application context. -->
<!-- They will automatically be acquired by the 'shiroFilter' bean above and made available -->
<!-- to the 'filterChainDefinitions' property. Or you can manually/explicitly add them -->
<!-- to the shiroFilter's 'filters' Map if desired. See its JavaDoc for more details. -->
<bean id="someFilter" class="..."/>
<bean id="anotherFilter" class="..."> ... </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 id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- Define the Shiro Realm implementation you want to use to connect to your back-end -->
<!-- security datasource: -->
<bean id="myRealm" class="...">
...
</bean>

下面就通过一个简单的实例来说明下shiro和spring的整合。

首先,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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>spring-shiro</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!-- 定义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>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 配置spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 编码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<async-supported>true</async-supported>
<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>
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 添加对springmvc的支持 -->
<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>
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>

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: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"> <!-- 自动扫描 -->
<context:component-scan base-package="com.fuwh.dao" />
<context:component-scan base-package="com.fuwh.service" /> <!-- 配置数据源 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_shiro"/>
<property name="username" value="root"/>
<property name="password" value="rootadmin"/>
</bean> <!-- 自定义Realm -->
<bean id="myJdbcRealm" class="com.fuwh.realm.MyJdbcRealm"/> <!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="myJdbcRealm"/>
</bean> <!-- Shiro过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- Shiro的核心安全接口,这个属性是必须的 -->
<property name="securityManager" ref="securityManager"/>
<!-- 身份认证失败,则跳转到登录页面的配置 -->
<property name="loginUrl" value="/login.jsp"/>
<!-- Shiro过滤链的定义 -->
<property name="filterChainDefinitions">
<value>
/user/login**=anon
/user/info=perms["bumen:*"]
/**=authc
</value>
</property>
</bean> <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> <!-- 开启Shiro注解 -->
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean> </beans>

自定义的realm如下:

package com.fuwh.realm;

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;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component; import com.fuwh.entity.User;
import com.fuwh.service.UserService; @Component
public class MyJdbcRealm extends AuthorizingRealm{ @Autowired
private UserService userService; @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// TODO Auto-generated method stub
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
info.setRoles(userService.getRoles(principals.getPrimaryPrincipal().toString()));
info.setStringPermissions(userService.getPermissions(info.getRoles()));
return info;
} @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
// TODO Auto-generated method stub
User user=new User();
user.setUsername(token.getPrincipal().toString());
User currUser=userService.getUser(user);
if(currUser!=null) {
SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(currUser.getUsername(),currUser.getPassword(),"xx");
return info;
}else{
return null;
}
} }

dao层如下:

package com.fuwh.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashSet;
import java.util.Set; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.stereotype.Component; import com.fuwh.dao.UserDao;
import com.fuwh.entity.User; @Component("userDao")
public class UserDaoImpl implements UserDao{ @Autowired
DriverManagerDataSource dataSource; private Connection conn;
private PreparedStatement ps;
private ResultSet rs; public User getUser(User user) {
// TODO Auto-generated method stub
User currUser=new User();
String sql="select * from users where username=?";
try {
conn=dataSource.getConnection();
ps=conn.prepareStatement(sql);
ps.setString(1, user.getUsername());
rs=ps.executeQuery();
while(rs.next()) {
currUser.setUsername(rs.getString("username"));
currUser.setPassword(rs.getString("password"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
rs.close();
ps.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return currUser;
} public Set<String> getRoles(String username) {
// TODO Auto-generated method stub
Set<String> roleSet=new LinkedHashSet<String>();
String sql="select role_name from user_roles where username=?";
try {
conn=dataSource.getConnection();
ps=conn.prepareStatement(sql);
ps.setString(1, username);
rs=ps.executeQuery();
while(rs.next()) {
roleSet.add(rs.getString("role_name"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
rs.close();
ps.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return roleSet;
} public Set<String> getPermissions(Set<String> roles) {
// TODO Auto-generated method stub
Set<String> permissionSet=new LinkedHashSet<String>();
String sql="select permission from roles_permissions where role_name=?"; try {
conn=dataSource.getConnection();
ps=conn.prepareStatement(sql);
for (String role : roles) {
ps.setString(1, role);
rs=ps.executeQuery();
while(rs.next()) {
permissionSet.add(rs.getString("role_name"));
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
rs.close();
ps.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return permissionSet;
} }

controller层如下:

package com.fuwh.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import com.fuwh.entity.User; @Controller
@RequestMapping("/user")
public class UserController { @RequestMapping("/login")
public String login(User user,HttpServletRequest request) {
Subject subject=SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(), user.getPassword());
subject.login(token);
return "redirect:/static/success.jsp";
} @RequestMapping("/info")
public String info() {
return "redirect:/static/info.jsp";
}
}

详细代码可以参考:https://github.com/oukafu/shiro

Shiro整合Spring的更多相关文章

  1. apache shiro整合spring(一)

    apache shiro整合spring 将shiro配置文件整合到spring体系中 方式一:直接在spring的配置文件中import shiro的配置文件 方式二:直接在web.xml中配置sh ...

  2. Shiro第四篇【Shiro与Spring整合、快速入门、Shiro过滤器、登陆认证】

    Spring与Shiro整合 导入jar包 shiro-web的jar. shiro-spring的jar shiro-code的jar 快速入门 shiro也通过filter进行拦截.filter拦 ...

  3. Shiro与Spring、Springmvc的整合

    1.在web.xml中配置Shiro的filter 在web系统中,shiro也通过filter进行拦截.filter拦截后将操作权交给spring中配置的filterChain(过虑链儿) shir ...

  4. 项目一:第十四天 1.在realm中动态授权 2.Shiro整合ehcache 缓存realm中授权信息 3.动态展示菜单数据 4.Quartz定时任务调度框架—Spring整合javamail发送邮件 5.基于poi实现分区导出

    1 Shiro整合ehCache缓存授权信息 当需要进行权限校验时候:四种方式url拦截.注解.页面标签.代码级别,当需要验证权限会调用realm中的授权方法   Shiro框架内部整合好缓存管理器, ...

  5. Spring与Shiro整合

    Spring整合篇--Shiro 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 什么是Shiro? 链接:https://www.cnblogs.com/StanleyBlogs/ ...

  6. Spring与Shiro整合 登陆操作

    Spring与Shiro整合 登陆操作 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 编写登陆Controller方法  讲解: 首先,如果你登陆失败的时候,它会把你的异常信息丢到 ...

  7. Spring与Shiro整合 加载权限表达式

    Spring与Shiro整合 加载权限表达式 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 如何加载权限表达式  我们在上章内容中画了一张图,里面有三个分项,用户 角色 权限: 那 ...

  8. Spring与Shiro整合 静态注解授权

    Spring与Shiro整合 静态注解授权 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 使用Shiro的种类 首先,Shiro的授权方式共有三种: 1.编程式授权(不推荐) 2. ...

  9. Spring+SpringMVC+Hibernate 与 shiro 整合步骤

    目录 1. 业务需求分析 2. 创建数据库 3. 创建 maven webapp 工程 4. 创建实体类(POJO) 5. 配置 Hibernate 和 Mapping 5.1 Hibernate 主 ...

随机推荐

  1. qt中控件的使用函数

    1.Text Edit编辑框 //将编辑框中的内容转化成Utf8编码 ui->textEdit->toPlainText().toUtf8(); 2.Combo Box下拉框的应用 (1) ...

  2. 如何在jenkins上新建一个项目及其简单配置

    1.首先,点击[新建]进入选择页面,如下图(一般选择"构建一个自由风格的软件项目")     2.填好项目名称后,点击ok,跳转至如下页面,可以在这个页面进行项目的配置(包括拉源码 ...

  3. C语言程序设计(基础)- 第6周作业

    一.PTA作业 完成PTA第六周作业中4个题目的思路列在博客中. 1.7-1 高速公路超速处罚 2.7-2 计算油费 3.7-3 比较大小 4.7-4 两个数的简单计算器 (必须使用switch结构实 ...

  4. C语言第一周作业

    题目一:7-3 温度转换 本题要求编写程序,计算华氏温度150°F对应的摄氏温度.计算公式:C=5×(F−32)/9,式中:C表示摄氏温度,F表示华氏温度,输出数据要求为整型. 1.实验代码 2.设计 ...

  5. C语言博客作业—一二维数组

    一.PTA实验作业 题目1:7-2 求整数序列中出现次数最多的数 1. 本题PTA提交列表 2. 设计思路 Begin 输入整数个数N 定义数组a[N] 输入数组a for(i 0 to N-1){/ ...

  6. 作业01-Java基本概念

    1.本周学习总结 本周学习了JVM,JDK,JRE三者之间的区别及联系,知道JDK包括JRE,JRE包括JVM,知道java语言与C语言的不同之处在于java语言可以依赖于虚拟机实现"编译一 ...

  7. 201621123040《Java程序设计》第5周学习总结

    1.本周学习总结 1.1写出你认为本周学习中比较重要的知识点关键词 关键词:接口 Comparable Comparator 比较排序 1.2尝试使用思维导图将这些关键词组织起来.注:思维导图一般不需 ...

  8. Mybatis学习日志

    在Mybatis深入学习的一周中,总感觉跟着师傅的视屏讲解什么都能懂,但实际自己操作的时候才发现自己一脸懵逼,不知道从何入手.但还好自己做了点笔记.在此记录一下自己浅度学习Mybatis遇到几个小问题 ...

  9. jquery ajax file upload NET MVC 无刷新文件上传

    网上有各种各样的文件上传方法,有基于JS框架的.也有基于flash swf插件的. 这次分享一个比较简单而且实用能快速上手的文件上传方法,主要步骤: 1.引用Jquery包,我用的是jquery-1. ...

  10. mqtt paho ssl java端代码

    参考链接:http://blog.csdn.net/lingshi210/article/details/52439050 mqtt 的ssl配置可以参阅 http://houjixin.blog.1 ...