在做网站开发中,用户权限必须要考虑的,权限这个东西很重要,它规定了用户在使用中能进行哪 些操作,和不能进行哪些操作;我们完全可以使用过滤器来进行权限的操作,但是有了权限框架之后,使用起来会非常的方便,一般在公司里面做网站开发常用的权 限框架有Spring的Security框架,和Apache的Shiro框架;Spring Security框架在使用上相比Shiro来说要更复杂一些,并且它限制了数据库该怎么去建表,只有按它的要求去建表,才能达到你想要的效果。下面我主 要介绍一下Shiro框架的使用,由于本人也是初学者,所写难免会有些不合理的地方,望各位指正;

使用Apache Shiro框架的步骤:

1.导入相应的jar包,我使用的是maven来管理的,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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kaishengit</groupId>
<artifactId>springmvctest</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springmvctest Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>
<dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.4.RELEASE</version> </dependency>
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.10</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>3.2.4.RELEASE</version> </dependency> <!-- Hibernate --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.5.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.2.5.Final</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.7.2</version> </dependency> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.0.1.Final</version> </dependency>
<!--Apache Shiro所需的jar包--> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.2</version> </dependency> </dependencies>
<build>
<finalName>springmvctest</finalName>
<plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <configuration> <scanIntervalSeconds>10</scanIntervalSeconds> <webApp> <contextPath>/</contextPath> </webApp> <connectors> <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector"> <port>80</port> <maxIdleTime>60000</maxIdleTime> </connector> </connectors> </configuration> </plugin>
</plugins>
</build>
</project>

2.在web.xml中进行配置:

<?xml version="1.0"encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Archetype Created Web Application</display-name> <!-- OpenSessionInView -->
<filter> <filter-name>opensessioninview</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
</filter>
<filter-mapping> <filter-name>opensessioninview</filter-name> <url-pattern>/*</url-pattern>
</filter-mapping> <!-- SpringMVC中央控制器 -->
<servlet> <servlet-name>mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping> <servlet-name>mvc</servlet-name> <url-pattern>/</url-pattern>
</servlet-mapping> <!-- Spring监听器 -->
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Shiro配置 -->
<filter> <filter-name>shiroFilter</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping> <filter-name>shiroFilter</filter-name> <url-pattern>/*</url-pattern>
</filter-mapping> </web-app>

3.使用SpringMVC:在/WEB-INF/路径下配置springmvc-servlet.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" 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-3.0.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.kaishengit.controller"> <context:include-filter type="annotation"expression="org.springframework.stereotype.Controller"/> </context:component-scan> <mvc:annotation-driven/> <!-- 静态资源访问 --> <mvc:resources location="/static/"mapping="/static/**"/> <!-- 视图解析器 --> <bean id="viewResolver"class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass"value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix"value="/WEB-INF/views/"/> <property name="suffix"value=".jsp"/> </bean> <!-- 文件上传解析器 --> <bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 配置最大上传文件的大小 --> <property name="maxUploadSize"value="1000000"/> </bean> <!-- 拦截器 --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <bean class="com.kaishengit.controller.MyInterceptor"> <property name="excluedUrls"> <list> <value>/home</value> </list> </property> </bean> </mvc:interceptor> </mvc:interceptors> <!-- 异常 --> <bean id="handlerExceptionResolver"class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"> <property name="exceptionMappings"> <props> <prop key="com.kaishengit.exception.AuthorizationException">redirect:/home</prop> </props> </property> </bean>
</beans>

4.配置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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 自动扫描所有的注解,排除掉controller不扫描 --> <context:component-scan base-package="com.kaishengit"> <context:exclude-filter type="annotation"expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 加载ClassPath中的properties文件 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 基于Hibernate的事务管理器 --> <bean id="transactionManager"class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory"ref="sessionFactory"></property> </bean> <!-- 配置数据源 --> <bean id="dataSource"class="org.apache.commons.dbcp.BasicDataSource"destroy-method="close"> <property name="driverClassName"value="${jdbc.driver}"/> <property name="url"value="${jdbc.url}"/> <property name="username"value="${jdbc.username}"/> <property name="password"value="${jdbc.password}"/> </bean> <!-- 基于注解 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- SessionFactory --> <bean id="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource"ref="dataSource"/> <!-- 实体类pojo所在的包 --> <property name="packagesToScan"value="com.kaishengit.pojo"/> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop> </props> </property> </bean>
</beans>

5.将配置在applicationContext.xml中的shiro独立出来,新建applicationContext-shiro.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"
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"> <bean id="securityManager"class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <property name="realm"ref="myShiro"/> <property name="cacheManager"ref="cacheManager"/> </bean> <bean id="shiroFilter"class="org.apache.shiro.spring.web.ShiroFilterFactoryBean"> <property name="securityManager"ref="securityManager"/> <property name="loginUrl"value="/login"/> <property name="successUrl"value="/user"/> <property name="unauthorizedUrl"value="/403"/> <property name="filterChainDefinitions"> <value>
<!--静态资源直接通过--> /static/** =anon
<!--只有admin角色才能访问/user/save--> /user/save =roles[admin]
<!--具有user:add权限的用户可以访问/user/save--> <!--/user/save =perms[user:add]-->
<!--所有的请求都要通过验证--> /** = authc </value> </property> </bean> <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager"/> <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/> </beans>

6.实现MyRealm:继承AuthorizingRealm,并重写认证授权方法

package com.kaishengit.service;

import java.util.List;

import javax.inject.Inject;

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.subject.PrincipalCollection;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.kaishengit.pojo.Role;
import com.kaishengit.pojo.User; @Service
@Transactional
public class MyRealm extends AuthorizingRealm{ @Inject private UserService userService; /** * 权限认证 */ @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { //获取登录的用户名 String loginName=(String) principalCollection.fromRealm(getName()).iterator().next(); User user=userService.findByName(loginName); if(user!=null){ SimpleAuthorizationInfo info=new SimpleAuthorizationInfo(); //登录的用户有多少个角色 info.setRoles(user.getRolesName()); List<Role> roleList=user.getRoleList(); for(Role role:roleList){ //角色有多少个权限 info.addStringPermissions(role.getPermissionNames()); } return info; } return null; } /** * 登录认证 */ @Override protected AuthenticationInfo doGetAuthenticationInfo( AuthenticationToken authenticationToken) throws AuthenticationException { UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; User user = userService.findByName(token.getUsername()); if(user != null) { return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName()); } return null; } }

7.HomeController.java

package com.kaishengit.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.kaishengit.pojo.User; @Controller
public class HomeController { @RequestMapping(value="/login",method=RequestMethod.GET) public String loginForm(){ return"/login"; } @RequestMapping(value="/login",method=RequestMethod.POST) public String login(User user,RedirectAttributes redirectAttributes){ try { SecurityUtils.getSubject().login(new UsernamePasswordToken(user.getUsername(), user.getPassword())); return"redirect:/user"; } catch (AuthenticationException e) { redirectAttributes.addFlashAttribute("message","用户名或密码错误"); return"redirect:/login"; } } @RequestMapping(value="/logout",method=RequestMethod.GET) public String logout(RedirectAttributes redirectAttributes ){ SecurityUtils.getSubject().logout(); redirectAttributes.addFlashAttribute("message","您已安全退出"); return"redirect:/login"; }
}

8.在jsp中使用Shiro标签库:

<%@ taglib prefix="shiro"uri="http://shiro.apache.org/tags"%>

<html>

<head>

<title>page</title>

</head>

<body>

<!--显示登录的用户名-->

<h2>welcome!<shiro:principal/></h2>

<a href="/logout">安全退出</a>

<!--角色为manager的用户登录后会显示添加按钮,否则不显示-->

<shiro:hasRole name="manager">

<a href="/user/save">添加</a>

</shiro:hasRole>

</body>

</html>

9.数据库中建表,E-R图如下:

Apache Shiro权限框架在SpringMVC+Hibernate中的应用的更多相关文章

  1. Shiro权限框架与SpringMVC集成

    1.Shiro整合SpringMVC 我们学习Shiro框架肯定是要应用到Web项目上的,所以我们需要整合Shiro和SpringMVC 整合步骤: 第一步:SpringMVC框架的配置 spring ...

  2. Apache Shiro 权限框架

    分享一个视屏教程集合 http://www.tudou.com/home/konghao/item 1.Shiro Apache Shiro是一个强大且易用的Java安全框架,执行身份验证.授权.密码 ...

  3. 关于Apache Shiro权限框架的一些使用误区的解释

    多了不说了,进入正题,shiro是个权限框架提供权限管理等功能,网上的教程一般都是互相抄,比如<shiro:principal property="xxx"/>这个标签 ...

  4. 在前后端分离的SpringBoot项目中集成Shiro权限框架

    参考[1].在前后端分离的SpringBoot项目中集成Shiro权限框架 参考[2]. Springboot + Vue + shiro 实现前后端分离.权限控制   以及跨域的问题也有涉及

  5. (转) shiro权限框架详解06-shiro与web项目整合(上)

    http://blog.csdn.net/facekbook/article/details/54947730 shiro和web项目整合,实现类似真实项目的应用 本文中使用的项目架构是springM ...

  6. Shiro权限框架简介

    http://blog.csdn.net/xiaoxian8023/article/details/17892041   Shiro权限框架简介 2014-01-05 23:51 3111人阅读 评论 ...

  7. SpringMVC下的Shiro权限框架的使用

    SpringMVC+Shiro权限管理 博文目录 权限的简单描述 实例表结构及内容及POJO Shiro-pom.xml Shiro-web.xml Shiro-MyShiro-权限认证,登录认证层 ...

  8. SpringMVC整合Shiro权限框架

    尊重原创:http://blog.csdn.net/donggua3694857/article/details/52157313 最近在学习Shiro,首先非常感谢开涛大神的<跟我学Shiro ...

  9. SpringBoot整合Apache Shiro权限验证框架

    比较常见的权限框架有两种,一种是Spring Security,另一种是Apache Shiro,两种框架各有优劣,个人感觉Shiro更容易使用,更加灵活,也更符合RABC规则,而且是java官方更推 ...

随机推荐

  1. ASP.NET MVC 5 学习教程:快速入门

    起飞网 ASP.NET MVC 5 学习教程目录: 添加控制器 添加视图 修改视图和布局页 控制器传递数据给视图 添加模型 创建连接字符串 通过控制器访问模型的数据 生成的代码详解 使用 SQL Se ...

  2. Emmet插件比较实用常用的写法

    看了一些关于Emmet插件写法的文档,港真,怎么可以写这么长啊.其实知道几个大概要点加上实践基本就能上手写了啊 杂话 我前面有一篇[今天发现新大陆:haml和Emmet ],其实一开始的想法是写给自己 ...

  3. Atitit.病毒木马程序的感染 传播扩散 原理

    Atitit.病毒木马程序的感染 传播扩散 原理 1. 从木马的发展史考虑,木马可以分为四代 1 2. 木马有两大类,远程控制  vs  自我复制传播1 3. 自我复制2 3.1. 需要知道当前cpu ...

  4. How To Write In Sharepoint Log File 怎么对自定义的MOSS代码写日志

    How To Write In Sharepoint Log File 怎么对自定义的MOSS代码写日志 Add Microsoft.Office.Server dll in your project ...

  5. UIButton在不同状态下显示不同背景色

    参考自:原文地址(内容与原文并无区别,只是自己以后方便使用整理了一下) 1.UIButton的background是不支持在针对不同的状态显示不同的颜色. 2.UIButton的backgroundI ...

  6. 【读书笔记】iOS-对象初始化

    一,分配对象. 分配是一个样的对象诞生的过程.最美好的时刻,是从操作系统获得一块内存并将其指定为存放对象的实例变量的位置.向某个类发送alloc消息的结果,就是为该类分配一块足够大的内存,以存放该内的 ...

  7. 我们需要专职的QA吗?

    [ 引用评论里的一句话:hurt but true  抛开作者某些偏激的想法外,作者暴露出来的问题还是需要测试思考的: 1.TestCase,TestData,TestConfiguration 没有 ...

  8. [Tomcat]如何在同一台机部署多个tomcat服务

    背景:往往不知情的同学在同一台机器上部署多个tomcat会发现第二个tomcat启动会报错.而有些同学会想到可能是端口重复,然而,在server.xml改了端口还是发现不行.其实要想实现同一台机器部署 ...

  9. Effective Java 45 Minimize the scope of local variables

    Principle The most powerful technique for minimizing the scope of a local variable is to declare it ...

  10. JavaScript Patterns 2.11 Writing Comments

    Document all functions, their arguments and return values, and also any interesting or unusual algor ...