在做网站开发中,用户权限必须要考虑的,权限这个东西很重要,它规定了用户在使用中能进行哪 些操作,和不能进行哪些操作;我们完全可以使用过滤器来进行权限的操作,但是有了权限框架之后,使用起来会非常的方便,一般在公司里面做网站开发常用的权 限框架有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. Android 提供的一系列辅助系统开发工具

    除了软件本身的代码之外,Android 还提供了一系列工具来辅助系统开发,这些主要的工具包括: aapt(AndroidAssetPackagingTool):用于建立zip兼容的包(zip.jar. ...

  2. 【Android】开源项目UI控件分类汇总之Dialog

    接前文ProgressBar:Android开发的宝库越来越多,我开发中有需要的组件,主要参考Trinea的大作Android开源项目分类汇总(包含了后面的绝大多数).CSDN上直接拿来用!最火的An ...

  3. js中的浅拷贝和深拷贝

    说说最近所学:浅拷贝和深拷贝也叫做浅克隆和深克隆,深浅主要针对的是对象的"深度",常见的对象都是"浅"的,也就是对象里的属性就是单个的属性,而"深&q ...

  4. SharePoint 更新文档库文档标题(Title)字段

    前言:记录下写代码中遇到的小问题,帮同事写一个批量更新文档库标题字段的小程序,本来以为就Update一下就可以了,10分钟可以搞定.结果10分钟过去了,代码写好了,执行起来不报错,调试也没问题,只是要 ...

  5. teambition的热血团队

    一群热血年轻人开发了一套项目协作软件teambition,无意帮他们宣传,更多见网址www.teambition.com. 网站上简短的一段话,深深的打动了我.他们说teambition: 由热爱工作 ...

  6. Sharepoint学习笔记—习题系列--70-573习题解析 --索引目录

                  Sharepoint学习笔记—习题系列--70-573习题解析 为便于查阅,这里整理并列出了我前面播客中的关于70-573习题解析系列的所有问题,有些内容可能会在以后更新, ...

  7. 安卓问题集-Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED

    错误出现原因: 1.没有 AndroidManifest.xml file文件(出现几率较小) 2. 是你在外面修改了包名而在 AndroidManifest.xml file.文件中没有同步过去导致 ...

  8. Android 开发组件

    每一个应用程序都有自己独立的运行沙盒(授予应用程序代码的访问权) Android操作系统是一个多用户的Linux系统,其中的每一个应用程序都是一个独立的用户. 系统会为每一个应用程序分配一个唯一的Li ...

  9. Python学习一入门

    一.打印Hello和多行文本 print 打印 后跟单引号或者双引号 多行:3个单引号或者3个双引号 二.算术运算 2.1.加减乖法 默认1/2=0 如果需要小数运算,则需要一个运算术上加.或者.0 ...

  10. 如何让 UITableViewCell 中的 imageView 大小固定

    UITableView可以算是使用频率最高的组件之一的,在开发过程中经常需要展示一些简单的信息列表常见列表布局 如图,很多页面其实就是这种展示结果,通常需要imageView,textLabel,de ...