idea ssm整合shiro shiro的基本用法

来源:互联网 发布:debian java 编辑:程序博客网 时间:2024/05/01 17:14

http://www.jianshu.com/p/6786ddf54582
参照此篇文章进行设置,此篇文章介绍了一个基本的shiro进行身份验证和权限验证的方法,实测可用,写这篇博客的目的为了复习自己配置shiro的基本流程
首先我们要有一个ssm maven项目,搭建ssm项目参照之前的博客
1.加入pom.xml
http://mvnrepository.com/ maven仓库的地址

 <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>      <dependency>        <groupId>org.apache.shiro</groupId>        <artifactId>shiro-ehcache</artifactId>        <version>1.2.3</version>      </dependency>

2.在mybatis配置文件中进行配置

<?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:context="http://www.springframework.org/schema/context"      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.1.xsd                            http://www.springframework.org/schema/context                            http://www.springframework.org/schema/context/spring-context-3.1.xsd                            http://www.springframework.org/schema/tx                         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd                       ">    <!-- 自动扫描 -->      <context:component-scan base-package="com.pack" />    <!-- 引入配置文件 -->      <bean id="propertyConfigurer"          class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">          <property name="location" value="classpath:jdbc.properties" />      </bean>      <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"          destroy-method="close">          <property name="driverClassName" value="${driver}" />          <property name="url" value="${url}" />          <property name="username" value="${username}" />          <property name="password" value="${password}" />      </bean>      <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->      <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">          <property name="dataSource" ref="dataSource" />          <!-- 自动扫描mapping.xml文件 -->          <property name="mapperLocations" value="classpath:mapping/*.xml"></property>    </bean>      <!-- DAO接口所在包名,Spring会自动查找其下的类 -->      <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">          <property name="basePackage" value="com.pack.dao" />        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>      </bean>      <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->      <bean id="transactionManager"          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">          <property name="dataSource" ref="dataSource" />      </bean>     <tx:annotation-driven transaction-manager="transactionManager" />    <!-- 配置自定义Realm -->    <bean id="myRealm" class="com.pack.shiro.ShiroManager"/>    <!-- 安全管理器 -->    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">        <property name="realm" ref="myRealm"/>    </bean>    <!-- Shiro过滤器 核心-->    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">        <!-- Shiro的核心安全接口,这个属性是必须的 -->        <property name="securityManager" ref="securityManager"/>        <!-- 身份认证失败,则跳转到登录页面的配置 -->        <property name="loginUrl" value="/login"/>        <!-- 权限认证失败,则跳转到指定页面 -->        <property name="unauthorizedUrl" value="/angu.jsp"/>        <!-- Shiro连接约束配置,即过滤链的定义 -->        <property name="filterChainDefinitions">            <value>                <!--anon 表示匿名访问,不需要认证以及授权-->                /loginAdmin=anon                <!--authc表示需要认证 没有进行身份认证是不能进行访问的-->                /admin*=authc                /student=roles[teacher]                /teacher=perms["user:create"]            </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>  

3.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"         version="3.0">  <display-name>Archetype Created Web Application</display-name>  <!-- Spring和mybatis的配置文件 -->  <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:spring-mybatis.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>  <!-- shiro过滤器定义 -->  <filter>    <filter-name>shiroFilter</filter-name>    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>    <init-param>      <!-- 该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 -->      <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监听器 -->  <listener>    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  </listener>  <!-- 防止Spring内存溢出监听器 -->  <listener>    <listener-class>org.springframework.web.util.IntrospectorCleanupListener</listener-class>  </listener>  <!-- Spring MVC servlet -->  <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>    <!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->    <url-pattern>/</url-pattern>  </servlet-mapping>  <context-param>    <param-name>log4jConfigLocation</param-name>    <param-value>classpath:log4j.properties</param-value>  </context-param>  <session-config>    <session-timeout>15</session-timeout>  </session-config>  <listener>    <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  </listener></web-app>

4.建立登录页面
这里使用了bootstrap以及一个生成svg图像的插件trianglify,以及弹出框的layer

<%@ page language="java" contentType="text/html; charset=utf-8"         pageEncoding="utf-8" import="java.util.*"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head>    <base href="<%=request.getContextPath()%>/" />    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    <title>Insert title here</title>    <link href="styles/bootstrap.min.css" rel="stylesheet" type="text/css">    <link href="scripts/skin/default/layer.css" rel="stylesheet" type="text/css">    <script type="text/javascript" src="scripts/jquery-1.12.0.min.js"></script>    <script type="text/javascript" src="scripts/bootstrap.min.js"></script>    <script type="text/javascript" src="scripts/bootstrap-table.min.js"></script>    <script type="text/javascript" src="scripts/trianglify.min.js"></script>    <script type="text/javascript" src="scripts/layer.js"></script>    <style>    </style></head><body><div class="container">    <form role="form" class="col-md-4 center-block" style="margin:120px auto 0 auto;float:none">        <h1>login</h1>        <div class="form-group">            <label for="username">用户名</label>            <input type="text" class="form-control" id="username" placeholder="Enter userName" style="padding:20px;">        </div>        <div class="form-group">            <label for="password">密码</label>            <input type="password" class="form-control" id="password" placeholder="Password" style="padding:20px;">        </div>        <div class="checkbox">            <label>                <input type="checkbox" id="che"> 记住密码            </label>        </div>        <div class="col-md-12" style="padding:0px;">            <button type="button" class="btn btn-default btn-block" id="sub" style="padding:10px;">Sign in</button>        </div>        <div id="cc" style="padding-top:20px;text-align: center;"> </div>    </form></div></body><script type="text/javascript">    var h = window.innerHeight, w = window.innerWidth;    // set up the base pattern    var pattern = Trianglify({        height: h,        width: w,        cell_size: 30 + Math.random() * 50});    // png    var png = document.createElement('img');    $("body")[0].background=pattern.png();    $("#sub").click(function(){        var name = $("#username").val();        var password = $("#password").val();        $.get("/login",{username:name,password:password},function (text) {                if(text==="2"){                    layer.alert('用户名或密码错误', {                        skin: 'layui-layer-lan'                        ,closeBtn: 0                        ,anim: 4 //动画类型                    });                }else{                    window.location.href="/tree";                }        });    })    var msgArr = ["有事做有所期待,日子就是幸福的。",        "生活如此难,要怎么过?一笑而过。",        "碧波荡漾一抹香,茶不醉人人自醉。",        "只要把心放宽,快乐其实很简单。",        "生活不能等待别人来安排,要自己去争取与奋斗!",        "每天都应该是有收获的,哪怕只是一句话。",        "只要路是对的,就不怕路远。",        "开心了就笑,不开心就过会再笑。",        "生活的小处,总是藏有大观。",        "总有一种期待,是家的味道。",        "学会在浮躁中思考,你才知道在喧嚣中走向哪里。",        "万家灯火中,总有一盏为你点亮。",        "有时候、宁愿像个孩子,不肯看太多的事,听太多的不是,单纯的过一辈子多好!",        "用心每一天,不忘初心,方能走远。",        "即使没有翅膀,心也要飞翔。",        "积一时之跬步,臻千里之遥程。",        "不开心时,记得要让心情转个弯。",        "偷偷挤进的一缕斜阳,送来满满的幸福。",        "只要坚持,事情再小也挡不住宏大的梦。",        "优等的心,不必华丽,但必须坚固。",        "天再高,踮起脚尖就能更接近阳光!",        "与未知的相遇,七分欢喜三分孤寂。",        "有事做有所期待,日子就是幸福的。",        "天时人事日相催,冬至阳生春又来",        "一串淡然的心情,一份纯粹的快乐。"    ];    var index = parseInt(Math.random() * (msgArr.length - 1));    var currentMsg = msgArr[index];   $("#cc").html(currentMsg);</script></html>

5.数据库结构,用户表,权限表,角色表

6.建立service,implement,dao,mapper

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" ><mapper namespace="com.pack.dao.UserDao" >  <resultMap id="BaseResultMap" type="com.pack.bean.User" >    <result column="id" property="id" jdbcType="INTEGER" />    <result column="name" property="name" jdbcType="VARCHAR" />    <result column="password" property="password" jdbcType="VARCHAR" />    <result column="age" property="age" jdbcType="INTEGER" />    <result column="roleid" property="roleid" jdbcType="INTEGER"/>  </resultMap>    <sql id="Base_Column_List" >        id, username, password,roleid    </sql>   <select id="selectByPrimaryKey" parameterType="int" resultType="com.pack.bean.User">        select * from `user` where user.id = #{id}   </select>    <select id="sele"  resultType="com.pack.bean.User" >        select * from `user` where user.name = #{name} and user.password =#{password}    </select>    <select id="getPermission" parameterType="String" resultType="String">        select p.permissionname from user u,role r,permission p        where u.roleid=r.id and p.roleid=r.id and u.name=#{name}    </select>    <select id="getRole" parameterType="String" resultType="String">        select r.rolename from user u,role r where u.roleid=r.id and u.name=#{name}    </select></mapper>

代码上传到
https://github.com/freegg/shiro

0 0
原创粉丝点击