Shiro集成SSM基于URL权限管理(一)
学习了shiro之后,我们就可以说尝试把shiro加入ssm中,并做一套基于url的权限管理。
其他的准备工作就不多说了,直接动手操作,看到效果再去理解。
表结构
执行如下,数据库名字可以自行修改,不过要和自己手动创建的数据库名字以及之后代码中的数据库名字保持一致。
1 drop database if exists shiro; 2 create database shiro default character set utf8; 3 use shiro; 4 5 drop table if exists user; 6 drop table if exists role; 7 drop table if exists permission; 8 drop table if exists user_role; 9 drop table if exists role_permission; 10 11 create table user ( 12 id bigint auto_increment, 13 name varchar(100), 14 password varchar(100), 15 salt varchar(100), 16 constraint pk_users primary key(id) 17 ) charset=utf8 engine=innodb; 18 19 create table role ( 20 id bigint auto_increment, 21 name varchar(100), 22 desc_ varchar(100), 23 constraint pk_roles primary key(id) 24 ) charset=utf8 engine=innodb; 25 26 create table permission ( 27 id bigint auto_increment, 28 name varchar(100), 29 desc_ varchar(100), 30 url varchar(100), 31 constraint pk_permissions primary key(id) 32 ) charset=utf8 engine=innodb; 33 34 create table user_role ( 35 id bigint auto_increment, 36 uid bigint, 37 rid bigint, 38 constraint pk_users_roles primary key(id) 39 ) charset=utf8 engine=innodb; 40 41 create table role_permission ( 42 id bigint auto_increment, 43 rid bigint, 44 pid bigint, 45 constraint pk_roles_permissions primary key(id) 46 ) charset=utf8 engine=innodb;
表数据
1 insert into `permission` values (1,'addproduct','增加产品','/addproduct'); 2 insert into `permission` values (2,'deleteproduct','删除产品','/deleteproduct'); 3 insert into `permission` values (3,'editeproduct','编辑产品','/editeproduct'); 4 insert into `permission` values (4,'updateproduct','修改产品','/updateproduct'); 5 insert into `permission` values (5,'listproduct','查看产品','/listproduct'); 6 insert into `permission` values (6,'addorder','增加订单','/addorder'); 7 insert into `permission` values (7,'deleteorder','删除订单','/deleteorder'); 8 insert into `permission` values (8,'editeorder','编辑订单','/editeorder'); 9 insert into `permission` values (9,'updateorder','修改订单','/updateorder'); 10 insert into `permission` values (10,'listorder','查看订单','/listorder'); 11 insert into `role` values (1,'admin','超级管理员'); 12 insert into `role` values (2,'productmanager','产品管理员'); 13 insert into `role` values (3,'ordermanager','订单管理员'); 14 insert into `role_permission` values (1,1,1); 15 insert into `role_permission` values (2,1,2); 16 insert into `role_permission` values (3,1,3); 17 insert into `role_permission` values (4,1,4); 18 insert into `role_permission` values (5,1,5); 19 insert into `role_permission` values (6,1,6); 20 insert into `role_permission` values (7,1,7); 21 insert into `role_permission` values (8,1,8); 22 insert into `role_permission` values (9,1,9); 23 insert into `role_permission` values (10,1,10); 24 insert into `role_permission` values (11,2,1); 25 insert into `role_permission` values (12,2,2); 26 insert into `role_permission` values (13,2,3); 27 insert into `role_permission` values (14,2,4); 28 insert into `role_permission` values (15,2,5); 29 insert into `role_permission` values (50,3,10); 30 insert into `role_permission` values (51,3,9); 31 insert into `role_permission` values (52,3,8); 32 insert into `role_permission` values (53,3,7); 33 insert into `role_permission` values (54,3,6); 34 insert into `role_permission` values (55,3,1); 35 insert into `role_permission` values (56,5,11); 36 insert into `user` values (1,'zhang3','a7d59dfc5332749cb801f86a24f5f590','e5ykfinwshfcxvbrpr3wxg=='); 37 insert into `user` values (2,'li4','43e28304197b9216e45ab1ce8dac831b','jpz19y7arvyighuujsb6sq=='); 38 insert into `user_role` values (43,2,2); 39 insert into `user_role` values (45,1,1);
和我们正常创建ssm项目,一样。
web.xml
web.xml做了如下几件事情
1. 指定spring的配置文件有两个
applicationcontext.xml: 用于链接数据库的
applicationcontext-shiro.xml: 用于配置shiro的。
2. 指定springmvc的配置文件
springmvc.xml
3. 使用shiro过滤器
<filter-class>org.springframework.web.filter.delegatingfilterproxy</filter-class>
代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:web="http://java.sun.com/xml/ns/javaee" 5 xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> 6 7 <!-- 中文过滤器 --> 8 <filter> 9 <filter-name>characterencodingfilter</filter-name> 10 <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> 11 <init-param> 12 <param-name>encoding</param-name> 13 <param-value>utf-8</param-value> 14 </init-param> 15 </filter> 16 <filter-mapping> 17 <filter-name>characterencodingfilter</filter-name> 18 <url-pattern>/*</url-pattern> 19 </filter-mapping> 20 21 <!-- spring的配置文件--> 22 <context-param> 23 <param-name>contextconfiglocation</param-name> 24 <param-value> 25 classpath:applicationcontext.xml, 26 classpath:applicationcontext-shiro.xml 27 </param-value> 28 </context-param> 29 <listener> 30 <listener-class>org.springframework.web.context.contextloaderlistener</listener-class> 31 </listener> 32 33 <!-- spring mvc核心:分发servlet --> 34 <servlet> 35 <servlet-name>mvc-dispatcher</servlet-name> 36 <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> 37 <!-- spring mvc的配置文件 --> 38 <init-param> 39 <param-name>contextconfiglocation</param-name> 40 <param-value>classpath:springmvc.xml</param-value> 41 </init-param> 42 <load-on-startup>1</load-on-startup> 43 </servlet> 44 <servlet-mapping> 45 <servlet-name>mvc-dispatcher</servlet-name> 46 <url-pattern>/</url-pattern> 47 </servlet-mapping> 48 49 <!-- shiro配置 --> 50 <filter> 51 <filter-name>shirofilter</filter-name> 52 <filter-class>org.springframework.web.filter.delegatingfilterproxy</filter-class> 53 <init-param> 54 <param-name>targetfilterlifecycle</param-name> 55 <param-value>true</param-value> 56 </init-param> 57 </filter> 58 <filter-mapping> 59 <filter-name>shirofilter</filter-name> 60 <url-pattern>/*</url-pattern> 61 </filter-mapping> 62 63 </web-app>
applicationcontext.xml
1.配置数据库的相关信息(这些配置根据自己的需要自行修改)
2. 扫描mybatis的mapper之类的
代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:mvc="http://www.springframework.org/schema/mvc" 7 xsi:schemalocation=" 8 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 9 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 10 http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd 11 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 12 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 13 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> 14 15 16 17 18 <context:annotation-config /> 19 <context:component-scan base-package="com.how2java.service" /> 20 21 <bean id="datasource" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> 22 <property name="driverclassname"> 23 <value>com.mysql.jdbc.driver</value> 24 </property> 25 <property name="url"> 26 <value>jdbc:mysql://localhost:3306/shiroweb?characterencoding=utf-8</value> 27 28 </property> 29 <property name="username"> 30 <value>root</value> 31 </property> 32 <property name="password"> 33 <value>root</value> 34 </property> 35 </bean> 36 37 38 <bean id="sqlsession" class="org.mybatis.spring.sqlsessionfactorybean"> 39 <property name="typealiasespackage" value="com.how2java.pojo" /> 40 <property name="datasource" ref="datasource"/> 41 <property name="mapperlocations" value="classpath:com/how2java/mapper/*.xml"/> 42 </bean> 43 44 <bean class="org.mybatis.spring.mapper.mapperscannerconfigurer"> 45 <property name="basepackage" value="com.how2java.mapper"/> 46 </bean> 47 48 49 50 </beans>
applicationcontext-shiro.xml
提供shiro的相关配置,简单的说,就是把我们之前做练习的shiro.ini里的内容搬到这个xml文件里面来了,只是写法不同。
配合databaserealm,做了 shiro教程中的shiro.ini 中做的事情
设置密码匹配器
<!-- 密码匹配器 -->
<bean id="credentialsmatcher" class="org.apache.shiro.authc.credential.hashedcredentialsmatcher">
<property name="hashalgorithmname" value="md5"/>
<property name="hashiterations" value="2"/>
<property name="storedcredentialshexencoded" value="true"/>
</bean>
让databaserealm使用这个密码匹配器
<bean id="databaserealm" class="com.how2java.realm.databaserealm">
<property name="credentialsmatcher" ref="credentialsmatcher"/>
</bean>
代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <beans xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" 3 xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util" 4 xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xmlns:aop="http://www.springframework.org/schema/aop" 7 xsi:schemalocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx 9 http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc 11 http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/util 13 http://www.springframework.org/schema/util/spring-util.xsd"> 14 15 <!-- 配置shiro的过滤器工厂类,id- shirofilter要和我们在web.xml中配置的过滤器一致 --> 16 <bean id="shirofilter" class="org.apache.shiro.spring.web.shirofilterfactorybean"> 17 <!-- 调用我们配置的权限管理器 --> 18 <property name="securitymanager" ref="securitymanager" /> 19 <!-- 配置我们的登录请求地址 --> 20 <property name="loginurl" value="/login" /> 21 <!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 --> 22 <property name="unauthorizedurl" value="/unauthorized" /> 23 <!-- 退出 --> 24 <property name="filters"> 25 <util:map> 26 <entry key="logout" value-ref="logoutfilter" /> 27 </util:map> 28 </property> 29 <!-- 权限配置 --> 30 <property name="filterchaindefinitions"> 31 <value> 32 <!-- anon表示此地址不需要任何权限即可访问 --> 33 /login=anon 34 /index=anon 35 /static/**=anon 36 <!-- 只对业务功能进行权限管理,权限配置本身不需要没有做权限要求,这样做是为了不让初学者混淆 --> 37 /config/**=anon 38 /dologout=logout 39 <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login --> 40 /** = authc 41 </value> 42 </property> 43 </bean> 44 <!-- 退出过滤器 --> 45 <bean id="logoutfilter" class="org.apache.shiro.web.filter.authc.logoutfilter"> 46 <property name="redirecturl" value="/index" /> 47 </bean> 48 49 <!-- 会话id生成器 --> 50 <bean id="sessionidgenerator" 51 class="org.apache.shiro.session.mgt.eis.javauuidsessionidgenerator" /> 52 <!-- 会话cookie模板 关闭浏览器立即失效 --> 53 <bean id="sessionidcookie" class="org.apache.shiro.web.servlet.simplecookie"> 54 <constructor-arg value="sid" /> 55 <property name="httponly" value="true" /> 56 <property name="maxage" value="-1" /> 57 </bean> 58 <!-- 会话dao --> 59 <bean id="sessiondao" 60 class="org.apache.shiro.session.mgt.eis.enterprisecachesessiondao"> 61 <property name="sessionidgenerator" ref="sessionidgenerator" /> 62 </bean> 63 <!-- 会话验证调度器,每30分钟执行一次验证 ,设定会话超时及保存 --> 64 <bean name="sessionvalidationscheduler" 65 class="org.apache.shiro.session.mgt.executorservicesessionvalidationscheduler"> 66 <property name="interval" value="1800000" /> 67 <property name="sessionmanager" ref="sessionmanager" /> 68 </bean> 69 <!-- 会话管理器 --> 70 <bean id="sessionmanager" 71 class="org.apache.shiro.web.session.mgt.defaultwebsessionmanager"> 72 <!-- 全局会话超时时间(单位毫秒),默认30分钟 --> 73 <property name="globalsessiontimeout" value="1800000" /> 74 <property name="deleteinvalidsessions" value="true" /> 75 <property name="sessionvalidationschedulerenabled" value="true" /> 76 <property name="sessionvalidationscheduler" ref="sessionvalidationscheduler" /> 77 <property name="sessiondao" ref="sessiondao" /> 78 <property name="sessionidcookieenabled" value="true" /> 79 <property name="sessionidcookie" ref="sessionidcookie" /> 80 </bean> 81 82 <!-- 安全管理器 --> 83 <bean id="securitymanager" class="org.apache.shiro.web.mgt.defaultwebsecuritymanager"> 84 <property name="realm" ref="databaserealm" /> 85 <property name="sessionmanager" ref="sessionmanager" /> 86 </bean> 87 <!-- 相当于调用securityutils.setsecuritymanager(securitymanager) --> 88 <bean 89 class="org.springframework.beans.factory.config.methodinvokingfactorybean"> 90 <property name="staticmethod" 91 value="org.apache.shiro.securityutils.setsecuritymanager" /> 92 <property name="arguments" ref="securitymanager" /> 93 </bean> 94 95 <!-- 密码匹配器 --> 96 <bean id="credentialsmatcher" class="org.apache.shiro.authc.credential.hashedcredentialsmatcher"> 97 <property name="hashalgorithmname" value="md5"/> 98 <property name="hashiterations" value="2"/> 99 <property name="storedcredentialshexencoded" value="true"/> 100 </bean> 101 102 <bean id="databaserealm" class="com.how2java.realm.databaserealm"> 103 <property name="credentialsmatcher" ref="credentialsmatcher"/> 104 </bean> 105 106 <!-- 保证实现了shiro内部lifecycle函数的bean执行 --> 107 <bean id="lifecyclebeanpostprocessor" class="org.apache.shiro.spring.lifecyclebeanpostprocessor" /> 108 </beans>
springmvc.xml
1.springmvc的基本配置
2. 增加了对shiro的支持
这样可以在控制器controller上,使用像@requirerole 这样的注解,来表示某个方法必须有相关的角色才能访问
3. 指定了异常处理类defaultexceptionhandler,这样当访问没有权限的资源的时候,就会跳到统一的页面去显示错误信息
代码如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xmlns:mvc="http://www.springframework.org/schema/mvc" 7 xsi:schemalocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd 8 http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 9 http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 10 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd 11 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd 12 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> 13 14 15 16 <context:annotation-config/> 17 18 <context:component-scan base-package="com.how2java.controller"> 19 <context:include-filter type="annotation" 20 expression="org.springframework.stereotype.controller"/> 21 </context:component-scan> 22 23 <mvc:annotation-driven /> 24 25 <mvc:default-servlet-handler /> 26 27 28 <bean 29 class="org.springframework.web.servlet.view.internalresourceviewresolver"> 30 <property name="viewclass" 31 value="org.springframework.web.servlet.view.jstlview" /> 32 <property name="prefix" value="/web-inf/jsp/" /> 33 <property name="suffix" value=".jsp" /> 34 </bean> 35 36 <!--启用shiro注解 --> 37 <bean 38 class="org.springframework.aop.framework.autoproxy.defaultadvisorautoproxycreator" 39 depends-on="lifecyclebeanpostprocessor"> 40 <property name="proxytargetclass" value="true" /> 41 </bean> 42 <bean 43 class="org.apache.shiro.spring.security.interceptor.authorizationattributesourceadvisor"> 44 <property name="securitymanager" ref="securitymanager" /> 45 </bean> 46 47 <!-- 控制器异常处理 --> 48 <bean id="exceptionhandlerexceptionresolver" class="org.springframework.web.servlet.mvc.method.annotation.exceptionhandlerexceptionresolver"> 49 </bean> 50 <bean class="com.how2java.exception.defaultexceptionhandler"/> 51 52 </beans>
log4j.properties
代码如下:
1 # global logging configuration 2 log4j.rootlogger=error, stdout 3 # mybatis logging configuration... 4 log4j.logger.com.how2java=trace 5 # console output... 6 log4j.appender.stdout=org.apache.log4j.consoleappender 7 log4j.appender.stdout.layout=org.apache.log4j.patternlayout 8 log4j.appender.stdout.layout.conversionpattern=%5p [%t] - %m%n
pagecontroller.java
因为使用 ssm,所以jsp通常都会放在web-inf/jsp 下面,而这个位置是无法通过浏览器直接访问的,所以就会专门做这么一个类,便于访问这些jsp。
比如要访问web-inf/jsp/index.jsp文件,那么就通过/index 这个路径来访问。
这个类还有两点需要注意:
1. /login 只支持get方式。 post方式是后续用来进行登录行为的,这里的get方式仅仅用于显示登录页面
2. 权限注解:
通过注解: @requiresroles("admin") 指明了 访问 deleteproduct 需要角色"admin"
通过注解:@requirespermissions("deleteorder") 指明了 访问 deleteorder 需要权限"deleteorder"
我们在哪里需要使用权限,就在哪里加上对应注解,但是当我们的权限配置关系发生改变的时候,我们不得不修改代码,这在实际项目中是不可能的。为了解决这一问题我们引入了url配置权限。
代码如下:
1 package com.how2java.controller; 2 3 4 import org.apache.shiro.authz.annotation.requirespermissions; 5 import org.apache.shiro.authz.annotation.requiresroles; 6 import org.springframework.stereotype.controller; 7 import org.springframework.web.bind.annotation.requestmapping; 8 import org.springframework.web.bind.annotation.requestmethod; 9 10 //专门用于显示页面的控制器 11 @controller 12 @requestmapping("") 13 public class pagecontroller { 14 15 @requestmapping("index") 16 public string index(){ 17 return "index"; 18 } 19 20 @requirespermissions("deleteorder") 21 @requestmapping("deleteorder") 22 public string deleteorder(){ 23 return "deleteorder"; 24 } 25 @requiresroles("productmanager") 26 @requestmapping("deleteproduct") 27 public string deleteproduct(){ 28 return "deleteproduct"; 29 } 30 @requestmapping("listproduct") 31 public string listproduct(){ 32 return "listproduct"; 33 } 34 35 @requestmapping(value="/login",method=requestmethod.get) 36 public string login(){ 37 return "login"; 38 } 39 @requestmapping("unauthorized") 40 public string noperms(){ 41 return "unauthorized"; 42 }
view层的各个页面
直接贴出结构图和代码
index页面
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8"%> 3 <html> 4 <head> 5 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 6 7 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 8 9 <link rel="stylesheet" type="text/css" href="static/css/style.css" /> 10 11 12 </head> 13 <body> 14 15 16 17 <div class="workingroom"> 18 <div class="logindiv"> 19 20 21 22 <c:if test="${empty subject.principal}"> 23 <a href="login">登录</a><br> 24 </c:if> 25 <c:if test="${!empty subject.principal}"> 26 <span class="desc">你好,${subject.principal},</span> 27 <a href="dologout">退出</a><br> 28 </c:if> 29 30 <a href="listproduct">查看产品</a><span class="desc">(登录后才可以查看) </span><br> 31 <a href="deleteproduct">删除产品</a><span class="desc">(要有产品管理员角色, zhang3没有,li4 有) </span><br> 32 <a href="deleteorder">删除订单</a><span class="desc">(要有删除订单权限, zhang3有,li4没有) </span><br> 33 </div> 34 35 36 37 38 39 40 41 42 43 </body> 44 </html>
login.jsp登陆页面
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8" import="java.util.*"%> 3 4 <!doctype html> 5 6 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 7 <link rel="stylesheet" type="text/css" href="static/css/style.css" /> 8 9 10 <div class="workingroom"> 11 12 <div class="errorinfo">${error}</div> 13 <form action="login" method="post"> 14 账号: <input type="text" name="name"> <br> 15 密码: <input type="password" name="password"> <br> 16 <br> 17 <input type="submit" value="登录"> 18 <br> 19 <br> 20 <div> 21 <span class="desc">账号:zhang3 密码:12345 角色:admin</span><br> 22 <span class="desc">账号:li4 密码:abcde 角色:productmanager</span><br> 23 </div> 24 25 26 </form> 27 </div>
listproduct.jsp 需要登录才能访问的页面
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8" import="java.util.*"%> 3 4 <!doctype html> 5 6 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 7 <link rel="stylesheet" type="text/css" href="static/css/style.css" /> 8 9 10 <div class="workingroom"> 11 12 listproduct.jsp ,能进来,就表示已经登录成功了 13 <br> 14 <a href="#" onclick="javascript:history.back()">返回</a> 15 </div>
deleteproduct.jsp 需要角色才能访问的页面
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8" import="java.util.*"%> 3 4 <!doctype html> 5 6 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 7 <link rel="stylesheet" type="text/css" href="static/css/style.css" /> 8 9 10 <div class="workingroom"> 11 12 deleteproduct.jsp,能进来<br>就表示拥有 productmanager 角色 13 <br> 14 <a href="#" onclick="javascript:history.back()">返回</a> 15 </div>
deleteorder.jsp 需要权限deleteorder 才能访问的页面
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8" import="java.util.*"%> 3 4 <!doctype html> 5 6 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 7 <link rel="stylesheet" type="text/css" href="static/css/style.css" /> 8 9 <div class="workingroom"> 10 11 deleteorder.jsp ,能进来,就表示有deleteorder权限 12 <br> 13 <a href="#" onclick="javascript:history.back()">返回</a> 14 </div>
unauthorized.jsp没有角色,没有权限都会跳转到这个页面来
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8" import="java.util.*"%> 3 4 <!doctype html> 5 6 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 7 <link rel="stylesheet" type="text/css" href="static/css/style.css" /> 8 9 10 <div class="workingroom"> 11 12 13 14 15 权限不足,具体原因:${ex.message} 16 <br> 17 <a href="#" onclick="javascript:history.back()">返回</a> 18 </div>
menu.jsp
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8"%> 3 <div class="menu"> 4 <a href="listuser">用户管理</a> 5 <a href="listrole">角色管理</a> 6 <a href="listpermission">权限管理</a> 7 </div>
style.css
1 span.desc{ 2 margin-left:20px; 3 color:gray; 4 } 5 div.workingroom{ 6 margin:200px auto; 7 width:600px; 8 position:relative; 9 } 10 div.workingroom a{ 11 /* display:inline-block; */ 12 /* margin-top:20px; */ 13 } 14 div.logindiv{ 15 text-align: left; 16 } 17 div.errorinfo{ 18 color:red; 19 font-size:0.65em; 20 } 21 div.workingroom td{ 22 border:1px solid black; 23 } 24 div.workingroom table{ 25 border-collapse:collapse; 26 width:100%; 27 } 28 29 div.workingroom td{ 30 border:1px solid black; 31 } 32 33 div.workingroom div.menu{ 34 position:absolute; 35 left:-160px; 36 top:-20px; 37 } 38 div.workingroom div.menu a{ 39 display:block; 40 margin-top:20px; 41 } 42 43 div.workingroom div.addoredit{ 44 margin:20px; 45 text-align:center; 46 }
listuser.jsp
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8"%> 3 <html> 4 <head> 5 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 6 7 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 8 <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> 9 10 <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> 11 </head> 12 <body> 13 14 <div class="workingroom"> 15 <%@include file="include/menu.jsp" %> 16 <table> 17 <tr> 18 <td>id</td> 19 <td>用户名称</td> 20 <td>用户密码</td> 21 <td>加密盐</td> 22 <td>角色</td> 23 <td>编辑</td> 24 <td>删除</td> 25 </tr> 26 <c:foreach items="${us}" var="u"> 27 <tr> 28 <td>${u.id}</td> 29 <td>${u.name}</td> 30 <td>${fn:substring(u.password, 0, 5)}...</td> 31 <td>${fn:substring(u.salt, 0, 5)}...</td> 32 <td> 33 <c:foreach items="${user_roles[u]}" var="r"> 34 ${r.name} <br> 35 </c:foreach> 36 </td> 37 <td><a href="edituser?id=${u.id}">编辑</a></td> 38 <td><a href="deleteuser?id=${u.id}">删除</a></td> 39 </tr> 40 </c:foreach> 41 </table> 42 43 <div class="addoredit" > 44 <form action="adduser" method="post"> 45 用户名: <input type="text" name="name"> <br> 46 密码: <input type="password" name="password"> <br><br> 47 <input type="submit" value="增加"> 48 </form> 49 </div> 50 </div> 51 </body> 52 </html>
edituser.jsp
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8"%> 3 <html> 4 <head> 5 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 6 7 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 8 9 <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> 10 11 </head> 12 <body> 13 14 <div class="workingroom"> 15 16 <%@include file="include/menu.jsp" %> 17 18 <div class="addoredit" > 19 <form action="updateuser" method="post"> 20 用户名: <input type="text" name="name" value="${user.name}"> <br><br> 21 密码: <input type="password" name="password" value="" placeholder="留空就表示不修改密码"> <br><br> 22 配置角色:<br> 23 <div style="text-align:left;width:300px;margin:0px auto;padding-left:50px"> 24 <c:foreach items="${rs}" var="r"> 25 <c:set var="hasrole" value="false" /> 26 <c:foreach items="${currentroles}" var="currentrole"> 27 <c:if test="${r.id==currentrole.id}"> 28 <c:set var="hasrole" value="true" /> 29 </c:if> 30 </c:foreach> 31 <input type="checkbox" ${hasrole?"checked='checked'":"" } name="roleids" value="${r.id}"> ${r.name}<br> 32 </c:foreach> 33 </div> 34 35 <br> 36 <input type="hidden" name="id" value="${user.id}"> 37 <input type="submit" value="修改"> 38 </form> 39 </div> 40 </div> 41 <script> 42 </script> 43 </body> 44 </html>
listrole.jsp
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8"%> 3 <html> 4 <head> 5 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 6 7 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 8 9 <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> 10 11 </head> 12 <body> 13 14 <div class="workingroom"> 15 16 <%@include file="include/menu.jsp" %> 17 18 <table> 19 <tr> 20 <td>id</td> 21 <td>角色名称</td> 22 <td>角色描述</td> 23 <td>权限</td> 24 <td>编辑</td> 25 <td>删除</td> 26 </tr> 27 <c:foreach items="${rs}" var="r"> 28 <tr> 29 <td>${r.id}</td> 30 <td>${r.name}</td> 31 <td>${r.desc_}</td> 32 <td> 33 <c:foreach items="${role_permissions[r]}" var="p"> 34 ${p.name} <br> 35 </c:foreach> 36 </td> 37 38 <td><a href="editrole?id=${r.id}">编辑</a></td> 39 <td><a href="deleterole?id=${r.id}">删除</a></td> 40 </tr> 41 </c:foreach> 42 </table> 43 44 <div class="addoredit" > 45 <form action="addrole" method="post"> 46 角色名称: <input type="text" name="name"> <br> 47 角色描述: <input type="text" name="desc_"> <br><br> 48 <input type="submit" value="增加"> 49 </form> 50 </div> 51 </div> 52 </body> 53 </html>
editrole.jsp
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8"%> 3 <html> 4 <head> 5 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 6 7 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 8 9 <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> 10 11 </head> 12 <body> 13 14 <div class="workingroom"> 15 16 <%@include file="include/menu.jsp" %> 17 18 <div class="addoredit" > 19 <form action="updaterole" method="post"> 20 角色名: <input type="text" name="name" value="${role.name}"> <br> 21 角色描述: <input type="text" name="desc_" value="${role.desc_}" > <br><br> 22 配置权限:<br> 23 <div style="text-align:left;width:300px;margin:0px auto;padding-left:50px"> 24 <c:foreach items="${ps}" var="p"> 25 <c:set var="haspermission" value="false" /> 26 <c:foreach items="${currentpermissions}" var="currentpermission"> 27 <c:if test="${p.id==currentpermission.id}"> 28 <c:set var="haspermission" value="true" /> 29 </c:if> 30 </c:foreach> 31 <input type="checkbox" ${haspermission?"checked='checked'":"" } name="permissionids" value="${p.id}"> ${p.name}<br> 32 </c:foreach> 33 </div> 34 35 <input type="hidden" name="id" value="${role.id}"> 36 <input type="submit" value="修改"> 37 </form> 38 </div> 39 </div> 40 </body> 41 </html>
listpermission.jsp
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8"%> 3 <html> 4 <head> 5 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 6 7 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 8 9 <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> 10 11 </head> 12 <body> 13 14 <div class="workingroom"> 15 16 <%@include file="include/menu.jsp" %> 17 18 <table> 19 <tr> 20 <td>id</td> 21 <td>权限名称</td> 22 <td>权限描述</td> 23 <td>权限对应的路径</td> 24 <td>编辑</td> 25 <td>删除</td> 26 </tr> 27 <c:foreach items="${ps}" var="p"> 28 <tr> 29 <td>${p.id}</td> 30 <td>${p.name}</td> 31 <td>${p.desc_}</td> 32 <td>${p.url}</td> 33 <td><a href="editpermission?id=${p.id}">编辑</a></td> 34 <td><a href="deletepermission?id=${p.id}">删除</a></td> 35 </tr> 36 </c:foreach> 37 </table> 38 39 <div class="addoredit" > 40 <form action="addpermission" method="post"> 41 权限名称: <input type="text" name="name"> <br> 42 权限描述: <input type="text" name="desc_"> <br> 43 权限对应的url: <input type="text" name="url"> <br><br> 44 <input type="submit" value="增加"> 45 </form> 46 </div> 47 </div> 48 </body> 49 </html>
editpermission.jsp
1 <%@ page language="java" contenttype="text/html; charset=utf-8" 2 pageencoding="utf-8"%> 3 <html> 4 <head> 5 <meta http-equiv="content-type" content="text/html; charset=utf-8"> 6 7 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 8 9 <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> 10 11 </head> 12 <body> 13 14 <div class="workingroom"> 15 16 <%@include file="include/menu.jsp" %> 17 18 <div class="addoredit" > 19 <form action="updatepermission" method="post"> 20 权限名称: <input type="text" name="name" value="${permission.name}"> <br> 21 权限描述: <input type="text" name="desc_" value="${permission.desc_}"> <br> 22 权限对应的url: <input type="text" name="url" value="${permission.url}"> <br><br> 23 <input type="hidden" name="id" value="${permission.id}"> 24 <input type="submit" value="修改"> 25 </form> 26 </div> 27 </div> 28 </body> 29 </html>
overismergeableplugin.java
这个类的解释见,解决mybatisgenerator多次运行mapper生成重复内容。
代码如下:
1 package com.how2java.util; 2 3 import org.mybatis.generator.api.generatedxmlfile; 4 5 import org.mybatis.generator.api.introspectedtable; 6 import org.mybatis.generator.api.pluginadapter; 7 8 import java.lang.reflect.field; 9 import java.util.list; 10 11 public class overismergeableplugin extends pluginadapter { 12 @override 13 public boolean validate(list<string> warnings) { 14 return true; 15 } 16 17 @override 18 public boolean sqlmapgenerated(generatedxmlfile sqlmap, introspectedtable introspectedtable) { 19 try { 20 field field = sqlmap.getclass().getdeclaredfield("ismergeable"); 21 field.setaccessible(true); 22 field.setboolean(sqlmap, false); 23 } catch (exception e) { 24 e.printstacktrace(); 25 } 26 return true; 27 } 28 }
generatorconfig.xml
目录如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <!doctype generatorconfiguration 3 public "-//mybatis.org//dtd mybatis generator configuration 1.0//en" 4 "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd"> 5 <generatorconfiguration> 6 7 <context id="db2tables" targetruntime="mybatis3"> 8 <!--避免生成重复代码的插件--> 9 <plugin type="com.how2java.util.overismergeableplugin" /> 10 11 <!--是否在代码中显示注释--> 12 <commentgenerator> 13 <property name="suppressdate" value="true" /> 14 <property name="suppressallcomments" value="true" /> 15 </commentgenerator> 16 17 <!--数据库链接地址账号密码--> 18 <jdbcconnection driverclass="com.mysql.jdbc.driver" connectionurl="jdbc:mysql://localhost/shiro" userid="root" password="admin"> 19 </jdbcconnection> 20 <!--不知道做什么用的。。。反正贴上来了~--> 21 <javatyperesolver> 22 <property name="forcebigdecimals" value="false"/> 23 </javatyperesolver> 24 <!--生成pojo类存放位置--> 25 <javamodelgenerator targetpackage="com.how2java.pojo" targetproject="src"> 26 <property name="enablesubpackages" value="true"/> 27 <property name="trimstrings" value="true"/> 28 </javamodelgenerator> 29 <!--生成xml映射文件存放位置--> 30 <sqlmapgenerator targetpackage="com.how2java.mapper" targetproject="src"> 31 <property name="enablesubpackages" value="true"/> 32 </sqlmapgenerator> 33 <!--生成mapper类存放位置--> 34 <javaclientgenerator type="xmlmapper" targetpackage="com.how2java.mapper" targetproject="src"> 35 <property name="enablesubpackages" value="true"/> 36 </javaclientgenerator> 37 38 <!--生成对应表及类名--> 39 <table tablename="user" domainobjectname="user" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="true" selectbyexamplequeryid="false"> 40 <property name="my.isgen.usekeys" value="true"/> 41 <property name="useactualcolumnnames" value="true"/> 42 <generatedkey column="id" sqlstatement="jdbc"/> 43 </table> 44 <table tablename="role" domainobjectname="role" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="true" selectbyexamplequeryid="false"> 45 <property name="my.isgen.usekeys" value="true"/> 46 <property name="useactualcolumnnames" value="true"/> 47 <generatedkey column="id" sqlstatement="jdbc"/> 48 </table> 49 <table tablename="permission" domainobjectname="permission" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="true" selectbyexamplequeryid="false"> 50 <property name="my.isgen.usekeys" value="true"/> 51 <property name="useactualcolumnnames" value="true"/> 52 <generatedkey column="id" sqlstatement="jdbc"/> 53 </table> 54 <table tablename="user_role" domainobjectname="userrole" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="true" selectbyexamplequeryid="false"> 55 <property name="my.isgen.usekeys" value="true"/> 56 <property name="useactualcolumnnames" value="true"/> 57 <generatedkey column="id" sqlstatement="jdbc"/> 58 </table> 59 <table tablename="role_permission" domainobjectname="rolepermission" enablecountbyexample="false" enableupdatebyexample="false" enabledeletebyexample="false" enableselectbyexample="true" selectbyexamplequeryid="false"> 60 <property name="my.isgen.usekeys" value="true"/> 61 <property name="useactualcolumnnames" value="true"/> 62 <generatedkey column="id" sqlstatement="jdbc"/> 63 </table> 64 65 </context> 66 </generatorconfiguration>
mybatisgenerator.java
代码如下:
1 package com.how2java.util; 2 3 import org.mybatis.generator.api.mybatisgenerator; 4 import org.mybatis.generator.config.configuration; 5 import org.mybatis.generator.config.xml.configurationparser; 6 import org.mybatis.generator.internal.defaultshellcallback; 7 8 import java.io.inputstream; 9 import java.text.simpledateformat; 10 import java.util.arraylist; 11 import java.util.date; 12 import java.util.list; 13 14 public class mybatisgenerator { 15 16 public static void main(string[] args) throws exception { 17 string today = "2018-5-21"; 18 19 simpledateformat sdf =new simpledateformat("yyyy-mm-dd"); 20 date now =sdf.parse(today); 21 date d = new date(); 22 23 if(d.gettime()>now.gettime()+1000*60*60*24){ 24 system.err.println("——————未成成功运行——————"); 25 system.err.println("——————未成成功运行——————"); 26 system.err.println("本程序具有破坏作用,应该只运行一次,如果必须要再运行,需要修改today变量为今天,如:" + sdf.format(new date())); 27 return; 28 } 29 30 if(false) 31 return; 32 list<string> warnings = new arraylist<string>(); 33 boolean overwrite = true; 34 inputstream is= mybatisgenerator.class.getclassloader().getresource("generatorconfig.xml").openstream(); 35 configurationparser cp = new configurationparser(warnings); 36 configuration config = cp.parseconfiguration(is); 37 is.close(); 38 defaultshellcallback callback = new defaultshellcallback(overwrite); 39 mybatisgenerator mybatisgenerator = new mybatisgenerator(config, callback, warnings); 40 mybatisgenerator.generate(null); 41 42 system.out.println("生成代码成功,只能执行一次,以后执行会覆盖掉mapper,pojo,xml 等文件上做的修改"); 43 44 } 45 }
运行 mybatisgenerator 以获取自动生成 pojo、example 和 mapper
记得刷新一下项目。
service层
permissionservice
1 package com.how2java.service; 2 3 import java.util.list; 4 import java.util.set; 5 6 import com.how2java.pojo.permission; 7 import com.how2java.pojo.role; 8 9 public interface permissionservice { 10 public set<string> listpermissions(string username); 11 12 public list<permission> list(); 13 public void add(permission permission); 14 public void delete(long id); 15 public permission get(long id); 16 public void update(permission permission); 17 18 public list<permission> list(role role); 19 20 }
rolepermissionservice
1 package com.how2java.service; 2 3 import com.how2java.pojo.role; 4 5 public interface rolepermissionservice { 6 public void setpermissions(role role, long[] permissionids); 7 public void deletebyrole(long roleid); 8 public void deletebypermission(long permissionid); 9 }
roleservice
1 package com.how2java.service; 2 3 import java.util.list; 4 import java.util.set; 5 6 import com.how2java.pojo.role; 7 import com.how2java.pojo.user; 8 9 public interface roleservice { 10 public set<string> listrolenames(string username); 11 public list<role> listroles(string username); 12 public list<role> listroles(user user); 13 14 public list<role> list(); 15 public void add(role role); 16 public void delete(long id); 17 public role get(long id); 18 public void update(role role); 19 20 }
userroleservice
1 package com.how2java.service; 2 3 import com.how2java.pojo.user; 4 5 public interface userroleservice { 6 7 public void setroles(user user, long[] roleids); 8 public void deletebyuser(long userid); 9 public void deletebyrole(long roleid); 10 11 }
userservice
package com.how2java.service; import java.util.list; import com.how2java.pojo.user; public interface userservice { public string getpassword(string name); public user getbyname(string name); public list<user> list(); public void add(user user); public void delete(long id); public user get(long id); public void update(user user); }
service实现层
permissionserviceimpl
1 package com.how2java.service.impl; 2 3 import java.util.arraylist; 4 import java.util.hashset; 5 import java.util.list; 6 import java.util.set; 7 8 import org.springframework.beans.factory.annotation.autowired; 9 import org.springframework.stereotype.service; 10 11 import com.how2java.mapper.permissionmapper; 12 import com.how2java.mapper.rolepermissionmapper; 13 import com.how2java.pojo.permission; 14 import com.how2java.pojo.permissionexample; 15 import com.how2java.pojo.role; 16 import com.how2java.pojo.rolepermission; 17 import com.how2java.pojo.rolepermissionexample; 18 import com.how2java.service.permissionservice; 19 import com.how2java.service.roleservice; 20 import com.how2java.service.userservice; 21 22 @service 23 public class permissionserviceimpl implements permissionservice{ 24 25 @autowired permissionmapper permissionmapper; 26 @autowired userservice userservice; 27 @autowired roleservice roleservice; 28 @autowired rolepermissionmapper rolepermissionmapper; 29 30 @override 31 public set<string> listpermissions(string username) { 32 set<string> result = new hashset<>(); 33 list<role> roles = roleservice.listroles(username); 34 35 list<rolepermission> rolepermissions = new arraylist<>(); 36 37 for (role role : roles) { 38 rolepermissionexample example = new rolepermissionexample(); 39 example.createcriteria().andridequalto(role.getid()); 40 list<rolepermission> rps= rolepermissionmapper.selectbyexample(example); 41 rolepermissions.addall(rps); 42 } 43 44 for (rolepermission rolepermission : rolepermissions) { 45 permission p = permissionmapper.selectbyprimarykey(rolepermission.getpid()); 46 result.add(p.getname()); 47 } 48 49 return result; 50 } 51 @override 52 public void add(permission u) { 53 permissionmapper.insert(u); 54 } 55 56 @override 57 public void delete(long id) { 58 permissionmapper.deletebyprimarykey(id); 59 } 60 61 @override 62 public void update(permission u) { 63 permissionmapper.updatebyprimarykeyselective(u); 64 } 65 66 @override 67 public permission get(long id) { 68 return permissionmapper.selectbyprimarykey(id); 69 } 70 71 @override 72 public list<permission> list(){ 73 permissionexample example =new permissionexample(); 74 example.setorderbyclause("id desc"); 75 return permissionmapper.selectbyexample(example); 76 77 } 78 @override 79 public list<permission> list(role role) { 80 list<permission> result = new arraylist<>(); 81 rolepermissionexample example = new rolepermissionexample(); 82 example.createcriteria().andridequalto(role.getid()); 83 list<rolepermission> rps = rolepermissionmapper.selectbyexample(example); 84 for (rolepermission rolepermission : rps) { 85 result.add(permissionmapper.selectbyprimarykey(rolepermission.getpid())); 86 } 87 88 return result; 89 } 90 91 }
rolepermissionserviceimpl
1 package com.how2java.service.impl; 2 3 import java.util.list; 4 5 import org.springframework.beans.factory.annotation.autowired; 6 import org.springframework.stereotype.service; 7 8 import com.how2java.mapper.rolepermissionmapper; 9 import com.how2java.pojo.permission; 10 import com.how2java.pojo.role; 11 import com.how2java.pojo.rolepermission; 12 import com.how2java.pojo.rolepermissionexample; 13 import com.how2java.service.rolepermissionservice; 14 15 @service 16 public class rolepermissionserviceimpl implements rolepermissionservice{ 17 18 @autowired rolepermissionmapper rolepermissionmapper; 19 20 @override 21 public void setpermissions(role role, long[] permissionids) { 22 //删除当前角色所有的权限 23 rolepermissionexample example= new rolepermissionexample(); 24 example.createcriteria().andridequalto(role.getid()); 25 list<rolepermission> rps= rolepermissionmapper.selectbyexample(example); 26 for (rolepermission rolepermission : rps) 27 rolepermissionmapper.deletebyprimarykey(rolepermission.getid()); 28 29 //设置新的权限关系 30 if(null!=permissionids) 31 for (long pid : permissionids) { 32 rolepermission rolepermission = new rolepermission(); 33 rolepermission.setpid(pid); 34 rolepermission.setrid(role.getid()); 35 rolepermissionmapper.insert(rolepermission); 36 } 37 } 38 39 @override 40 public void deletebyrole(long roleid) { 41 rolepermissionexample example= new rolepermissionexample(); 42 example.createcriteria().andridequalto(roleid); 43 list<rolepermission> rps= rolepermissionmapper.selectbyexample(example); 44 for (rolepermission rolepermission : rps) 45 rolepermissionmapper.deletebyprimarykey(rolepermission.getid()); 46 } 47 48 @override 49 public void deletebypermission(long permissionid) { 50 rolepermissionexample example= new rolepermissionexample(); 51 example.createcriteria().andpidequalto(permissionid); 52 list<rolepermission> rps= rolepermissionmapper.selectbyexample(example); 53 for (rolepermission rolepermission : rps) 54 rolepermissionmapper.deletebyprimarykey(rolepermission.getid()); 55 } 56 57 }
roleserviceimpl
1 package com.how2java.service.impl; 2 3 import java.util.arraylist; 4 import java.util.hashset; 5 import java.util.list; 6 import java.util.set; 7 8 import org.springframework.beans.factory.annotation.autowired; 9 import org.springframework.stereotype.service; 10 11 import com.how2java.mapper.rolemapper; 12 import com.how2java.mapper.userrolemapper; 13 import com.how2java.pojo.role; 14 import com.how2java.pojo.roleexample; 15 import com.how2java.pojo.user; 16 import com.how2java.pojo.userrole; 17 import com.how2java.pojo.userroleexample; 18 import com.how2java.service.roleservice; 19 import com.how2java.service.userservice; 20 21 @service 22 public class roleserviceimpl implements roleservice{ 23 @autowired rolemapper rolemapper; 24 @autowired userrolemapper userrolemapper; 25 @autowired userservice userservice; 26 27 @override 28 public set<string> listrolenames(string username) { 29 set<string> result = new hashset<>(); 30 list<role> roles = listroles(username); 31 for (role role : roles) { 32 result.add(role.getname()); 33 } 34 return result; 35 } 36 37 @override 38 public list<role> listroles(string username) { 39 list<role> roles = new arraylist<>(); 40 user user = userservice.getbyname(username); 41 if(null==user) 42 return roles; 43 44 roles = listroles(user); 45 return roles; 46 } 47 48 @override 49 public void add(role u) { 50 rolemapper.insert(u); 51 } 52 53 @override 54 public void delete(long id) { 55 rolemapper.deletebyprimarykey(id); 56 } 57 58 @override 59 public void update(role u) { 60 rolemapper.updatebyprimarykeyselective(u); 61 } 62 63 @override 64 public role get(long id) { 65 return rolemapper.selectbyprimarykey(id); 66 } 67 68 @override 69 public list<role> list(){ 70 roleexample example =new roleexample(); 71 example.setorderbyclause("id desc"); 72 return rolemapper.selectbyexample(example); 73 74 } 75 76 @override 77 public list<role> listroles(user user) { 78 list<role> roles = new arraylist<>(); 79 80 userroleexample example = new userroleexample(); 81 82 example.createcriteria().anduidequalto(user.getid()); 83 list<userrole> userroles= userrolemapper.selectbyexample(example); 84 85 for (userrole userrole : userroles) { 86 role role=rolemapper.selectbyprimarykey(userrole.getrid()); 87 roles.add(role); 88 } 89 return roles; 90 } 91 92 }
userroleserviceimpl
1 package com.how2java.service.impl; 2 3 import java.util.list; 4 5 import org.springframework.beans.factory.annotation.autowired; 6 import org.springframework.stereotype.service; 7 8 import com.how2java.mapper.userrolemapper; 9 import com.how2java.pojo.role; 10 import com.how2java.pojo.user; 11 import com.how2java.pojo.userrole; 12 import com.how2java.pojo.userroleexample; 13 import com.how2java.service.userroleservice; 14 15 @service 16 public class userroleserviceimpl implements userroleservice{ 17 18 @autowired userrolemapper userrolemapper; 19 @override 20 public void setroles(user user, long[] roleids) { 21 //删除当前用户所有的角色 22 userroleexample example= new userroleexample(); 23 example.createcriteria().anduidequalto(user.getid()); 24 list<userrole> urs= userrolemapper.selectbyexample(example); 25 for (userrole userrole : urs) 26 userrolemapper.deletebyprimarykey(userrole.getid()); 27 28 //设置新的角色关系 29 if(null!=roleids) 30 for (long rid : roleids) { 31 userrole userrole = new userrole(); 32 userrole.setrid(rid); 33 userrole.setuid(user.getid()); 34 userrolemapper.insert(userrole); 35 } 36 } 37 @override 38 public void deletebyuser(long userid) { 39 userroleexample example= new userroleexample(); 40 example.createcriteria().anduidequalto(userid); 41 list<userrole> urs= userrolemapper.selectbyexample(example); 42 for (userrole userrole : urs) { 43 userrolemapper.deletebyprimarykey(userrole.getid()); 44 } 45 } 46 @override 47 public void deletebyrole(long roleid) { 48 userroleexample example= new userroleexample(); 49 example.createcriteria().andridequalto(roleid); 50 list<userrole> urs= userrolemapper.selectbyexample(example); 51 for (userrole userrole : urs) { 52 userrolemapper.deletebyprimarykey(userrole.getid()); 53 } 54 } 55 56 }
userserviceimpl
1 package com.how2java.service.impl; 2 3 import java.util.list; 4 5 import org.springframework.beans.factory.annotation.autowired; 6 import org.springframework.stereotype.service; 7 8 import com.how2java.mapper.usermapper; 9 import com.how2java.pojo.user; 10 import com.how2java.pojo.userexample; 11 import com.how2java.service.userroleservice; 12 import com.how2java.service.userservice; 13 14 @service 15 public class userserviceimpl implements userservice{ 16 17 @autowired usermapper usermapper; 18 @autowired userroleservice userroleservice; 19 20 @override 21 public string getpassword(string name) { 22 user user = getbyname(name); 23 if(null==user) 24 return null; 25 return user.getpassword(); 26 } 27 28 @override 29 public user getbyname(string name) { 30 userexample example = new userexample(); 31 example.createcriteria().andnameequalto(name); 32 list<user> users = usermapper.selectbyexample(example); 33 if(users.isempty()) 34 return null; 35 return users.get(0); 36 } 37 38 @override 39 public void add(user u) { 40 usermapper.insert(u); 41 } 42 43 @override 44 public void delete(long id) { 45 usermapper.deletebyprimarykey(id); 46 userroleservice.deletebyuser(id); 47 } 48 49 @override 50 public void update(user u) { 51 usermapper.updatebyprimarykeyselective(u); 52 } 53 54 @override 55 public user get(long id) { 56 return usermapper.selectbyprimarykey(id); 57 } 58 59 @override 60 public list<user> list(){ 61 userexample example =new userexample(); 62 example.setorderbyclause("id desc"); 63 return usermapper.selectbyexample(example); 64 65 } 66 67 }
controller 层
logincontroller
1 package com.how2java.controller; 2 3 4 import org.apache.shiro.securityutils; 5 import org.apache.shiro.authc.authenticationexception; 6 import org.apache.shiro.authc.usernamepasswordtoken; 7 import org.apache.shiro.session.session; 8 import org.apache.shiro.subject.subject; 9 import org.springframework.stereotype.controller; 10 import org.springframework.ui.model; 11 import org.springframework.web.bind.annotation.requestmapping; 12 import org.springframework.web.bind.annotation.requestmethod; 13 14 @controller 15 @requestmapping("") 16 public class logincontroller { 17 @requestmapping(value="/login",method=requestmethod.post) 18 public string login(model model,string name, string password) { 19 subject subject = securityutils.getsubject(); 20 usernamepasswordtoken token = new usernamepasswordtoken(name, password); 21 try { 22 subject.login(token); 23 session session=subject.getsession(); 24 session.setattribute("subject", subject); 25 return "redirect:index"; 26 27 } catch (authenticationexception e) { 28 model.addattribute("error", "验证失败"); 29 return "login"; 30 } 31 } 32 33 34 35 }
pagecontroller
上面已贴
permissioncontroller
1 package com.how2java.controller; 2 3 import java.util.list; 4 5 import org.springframework.beans.factory.annotation.autowired; 6 import org.springframework.stereotype.controller; 7 import org.springframework.ui.model; 8 import org.springframework.web.bind.annotation.requestmapping; 9 10 import com.how2java.pojo.permission; 11 import com.how2java.service.permissionservice; 12 13 @controller 14 @requestmapping("config") 15 public class permissioncontroller { 16 @autowired permissionservice permissionservice; 17 18 @requestmapping("listpermission") 19 public string list(model model){ 20 list<permission> ps= permissionservice.list(); 21 model.addattribute("ps", ps); 22 return "listpermission"; 23 } 24 @requestmapping("editpermission") 25 public string list(model model,long id){ 26 permission permission =permissionservice.get(id); 27 model.addattribute("permission", permission); 28 return "editpermission"; 29 } 30 @requestmapping("updatepermission") 31 public string update(permission permission){ 32 33 permissionservice.update(permission); 34 return "redirect:listpermission"; 35 } 36 37 @requestmapping("addpermission") 38 public string list(model model,permission permission){ 39 system.out.println(permission.getname()); 40 system.out.println(permission.getdesc_()); 41 permissionservice.add(permission); 42 return "redirect:listpermission"; 43 } 44 @requestmapping("deletepermission") 45 public string delete(model model,long id){ 46 permissionservice.delete(id); 47 return "redirect:listpermission"; 48 } 49 50 }
rolecontroller
1 package com.how2java.controller; 2 3 import java.util.arrays; 4 import java.util.hashmap; 5 import java.util.list; 6 import java.util.map; 7 8 import org.springframework.beans.factory.annotation.autowired; 9 import org.springframework.stereotype.controller; 10 import org.springframework.ui.model; 11 import org.springframework.web.bind.annotation.requestmapping; 12 13 import com.how2java.pojo.permission; 14 import com.how2java.pojo.role; 15 import com.how2java.service.permissionservice; 16 import com.how2java.service.rolepermissionservice; 17 import com.how2java.service.roleservice; 18 19 @controller 20 @requestmapping("config") 21 public class rolecontroller { 22 @autowired roleservice roleservice; 23 @autowired rolepermissionservice rolepermissionservice; 24 @autowired permissionservice permissionservice; 25 26 @requestmapping("listrole") 27 public string list(model model){ 28 list<role> rs= roleservice.list(); 29 model.addattribute("rs", rs); 30 31 map<role,list<permission>> role_permissions = new hashmap<>(); 32 33 for (role role : rs) { 34 list<permission> ps = permissionservice.list(role); 35 role_permissions.put(role, ps); 36 } 37 model.addattribute("role_permissions", role_permissions); 38 39 return "listrole"; 40 } 41 @requestmapping("editrole") 42 public string list(model model,long id){ 43 role role =roleservice.get(id); 44 model.addattribute("role", role); 45 46 list<permission> ps = permissionservice.list(); 47 model.addattribute("ps", ps); 48 49 list<permission> currentpermissions = permissionservice.list(role); 50 model.addattribute("currentpermissions", currentpermissions); 51 52 return "editrole"; 53 } 54 @requestmapping("updaterole") 55 public string update(role role,long[] permissionids){ 56 rolepermissionservice.setpermissions(role, permissionids); 57 roleservice.update(role); 58 return "redirect:listrole"; 59 } 60 61 @requestmapping("addrole") 62 public string list(model model,role role){ 63 system.out.println(role.getname()); 64 system.out.println(role.getdesc_()); 65 roleservice.add(role); 66 return "redirect:listrole"; 67 } 68 @requestmapping("deleterole") 69 public string delete(model model,long id){ 70 roleservice.delete(id); 71 return "redirect:listrole"; 72 } 73 74 }
usercontroller
1 package com.how2java.controller; 2 3 import java.util.hashmap; 4 import java.util.list; 5 import java.util.map; 6 7 import org.apache.shiro.crypto.securerandomnumbergenerator; 8 import org.apache.shiro.crypto.hash.simplehash; 9 import org.springframework.beans.factory.annotation.autowired; 10 import org.springframework.stereotype.controller; 11 import org.springframework.ui.model; 12 import org.springframework.web.bind.annotation.requestmapping; 13 14 import com.how2java.pojo.role; 15 import com.how2java.pojo.user; 16 import com.how2java.service.roleservice; 17 import com.how2java.service.userroleservice; 18 import com.how2java.service.userservice; 19 20 @controller 21 @requestmapping("config") 22 public class usercontroller { 23 @autowired userroleservice userroleservice; 24 @autowired userservice userservice; 25 @autowired roleservice roleservice; 26 27 @requestmapping("listuser") 28 public string list(model model){ 29 list<user> us= userservice.list(); 30 model.addattribute("us", us); 31 map<user,list<role>> user_roles = new hashmap<>(); 32 for (user user : us) { 33 list<role> roles=roleservice.listroles(user); 34 user_roles.put(user, roles); 35 } 36 model.addattribute("user_roles", user_roles); 37 38 return "listuser"; 39 } 40 @requestmapping("edituser") 41 public string edit(model model,long id){ 42 list<role> rs = roleservice.list(); 43 model.addattribute("rs", rs); 44 user user =userservice.get(id); 45 model.addattribute("user", user); 46 47 list<role> roles =roleservice.listroles(user); 48 model.addattribute("currentroles", roles); 49 50 return "edituser"; 51 } 52 @requestmapping("deleteuser") 53 public string delete(model model,long id){ 54 userservice.delete(id); 55 return "redirect:listuser"; 56 } 57 @requestmapping("updateuser") 58 public string update(user user,long[] roleids){ 59 userroleservice.setroles(user,roleids); 60 61 string password=user.getpassword(); 62 //如果在修改的时候没有设置密码,就表示不改动密码 63 if(user.getpassword().length()!=0) { 64 string salt = new securerandomnumbergenerator().nextbytes().tostring(); 65 int times = 2; 66 string algorithmname = "md5"; 67 string encodedpassword = new simplehash(algorithmname,password,salt,times).tostring(); 68 user.setsalt(salt); 69 user.setpassword(encodedpassword); 70 } 71 else 72 user.setpassword(null); 73 74 userservice.update(user); 75 76 return "redirect:listuser"; 77 78 } 79 80 @requestmapping("adduser") 81 public string add(model model,string name, string password){ 82 83 string salt = new securerandomnumbergenerator().nextbytes().tostring(); 84 int times = 2; 85 string algorithmname = "md5"; 86 87 string encodedpassword = new simplehash(algorithmname,password,salt,times).tostring(); 88 89 user u = new user(); 90 u.setname(name); 91 u.setpassword(encodedpassword); 92 u.setsalt(salt); 93 userservice.add(u); 94 95 return "redirect:listuser"; 96 } 97 98 }
databaserealm
代码如下:
1 package com.how2java.realm; 2 3 import java.util.set; 4 5 import org.apache.shiro.authc.authenticationexception; 6 import org.apache.shiro.authc.authenticationinfo; 7 import org.apache.shiro.authc.authenticationtoken; 8 import org.apache.shiro.authc.simpleauthenticationinfo; 9 import org.apache.shiro.authc.usernamepasswordtoken; 10 import org.apache.shiro.authz.authorizationinfo; 11 import org.apache.shiro.authz.simpleauthorizationinfo; 12 import org.apache.shiro.codec.codecexception; 13 import org.apache.shiro.crypto.unknownalgorithmexception; 14 import org.apache.shiro.crypto.hash.simplehash; 15 import org.apache.shiro.realm.authorizingrealm; 16 import org.apache.shiro.subject.principalcollection; 17 import org.apache.shiro.util.bytesource; 18 import org.springframework.beans.factory.annotation.autowired; 19 20 import com.how2java.pojo.user; 21 import com.how2java.service.permissionservice; 22 import com.how2java.service.roleservice; 23 import com.how2java.service.userservice; 24 25 public class databaserealm extends authorizingrealm { 26 27 @autowired 28 private userservice userservice; 29 @autowired 30 private roleservice roleservice; 31 @autowired 32 private permissionservice permissionservice; 33 34 @override 35 protected authorizationinfo dogetauthorizationinfo(principalcollection principalcollection) { 36 //能进入到这里,表示账号已经通过验证了 37 string username =(string) principalcollection.getprimaryprincipal(); 38 //通过service获取角色和权限 39 set<string> permissions = permissionservice.listpermissions(username); 40 set<string> roles = roleservice.listrolenames(username); 41 42 //授权对象 43 simpleauthorizationinfo s = new simpleauthorizationinfo(); 44 //把通过service获取到的角色和权限放进去 45 s.setstringpermissions(permissions); 46 s.setroles(roles); 47 return s; 48 } 49 50 @override 51 protected authenticationinfo dogetauthenticationinfo(authenticationtoken token) throws authenticationexception { 52 //获取账号密码 53 usernamepasswordtoken t = (usernamepasswordtoken) token; 54 string username= token.getprincipal().tostring(); 55 //获取数据库中的密码 56 user user =userservice.getbyname(username); 57 string passwordindb = user.getpassword(); 58 string salt = user.getsalt(); 59 //认证信息里存放账号密码, getname() 是当前realm的继承方法,通常返回当前类名 :databaserealm 60 //盐也放进去 61 //这样通过applicationcontext-shiro.xml里配置的 hashedcredentialsmatcher 进行自动校验 62 simpleauthenticationinfo a = new simpleauthenticationinfo(username,passwordindb,bytesource.util.bytes(salt),getname()); 63 return a; 64 } 65 66 } 67 defaultexceptionhandler 68 代码如下: 69 package com.how2java.exception; 70 71 import org.apache.shiro.authz.unauthorizedexception; 72 import org.springframework.http.httpstatus; 73 import org.springframework.web.bind.annotation.controlleradvice; 74 import org.springframework.web.bind.annotation.exceptionhandler; 75 import org.springframework.web.bind.annotation.responsestatus; 76 import org.springframework.web.context.request.nativewebrequest; 77 import org.springframework.web.servlet.modelandview; 78 79 @controlleradvice 80 public class defaultexceptionhandler { 81 @exceptionhandler({unauthorizedexception.class}) 82 @responsestatus(httpstatus.unauthorized) 83 public modelandview processunauthenticatedexception(nativewebrequest request, unauthorizedexception e) { 84 modelandview mv = new modelandview(); 85 mv.addobject("ex", e); 86 mv.setviewname("unauthorized"); 87 return mv; 88 } 89 }
defaultexceptionhandler
1 package com.how2java.exception; 2 3 import org.apache.shiro.authz.unauthorizedexception; 4 import org.springframework.http.httpstatus; 5 import org.springframework.web.bind.annotation.controlleradvice; 6 import org.springframework.web.bind.annotation.exceptionhandler; 7 import org.springframework.web.bind.annotation.responsestatus; 8 import org.springframework.web.context.request.nativewebrequest; 9 import org.springframework.web.servlet.modelandview; 10 11 @controlleradvice 12 public class defaultexceptionhandler { 13 @exceptionhandler({unauthorizedexception.class}) 14 @responsestatus(httpstatus.unauthorized) 15 public modelandview processunauthenticatedexception(nativewebrequest request, unauthorizedexception e) { 16 modelandview mv = new modelandview(); 17 mv.addobject("ex", e); 18 mv.setviewname("unauthorized"); 19 return mv; 20 } 21 }
http://127.0.0.1:8080/shirossm/config/listuser
项目名不一致的话自行修改。
不过此时的权限还是通过注解@requiresroles、@requirespermissions实现,而非动态url.。之后会在此基础上实现动态url了。
基本代码都贴出来了。如有需要demo源码,请留言,互相交流学习乐意分享。