学习了shiro之后,我们就可以说尝试把shiro加入ssm中,并做一套基于URL的权限管理。

其他的准备工作就不多说了,直接动手操作,看到效果再去理解。

表结构

执行如下,数据库名字可以自行修改,不过要和自己手动创建的数据库名字以及之后代码中的数据库名字保持一致。

 DROP DATABASE IF EXISTS shiro;
CREATE DATABASE shiro DEFAULT CHARACTER SET utf8;
USE shiro;
   
drop table if exists user;
drop table if exists role;
drop table if exists permission;
drop table if exists user_role;
drop table if exists role_permission;
   
create table user (
  id bigint auto_increment,
  name varchar(100),
  password varchar(100),
  salt varchar(100),
  constraint pk_users primary key(id)
) charset=utf8 ENGINE=InnoDB;
   
create table role (
  id bigint auto_increment,
  name varchar(100),
  desc_ varchar(100),
  constraint pk_roles primary key(id)
) charset=utf8 ENGINE=InnoDB;
   
create table permission (
  id bigint auto_increment,
  name varchar(100),
  desc_ varchar(100),
  url varchar(100), 
  constraint pk_permissions primary key(id)
) charset=utf8 ENGINE=InnoDB;
   
create table user_role (
  id bigint auto_increment,
  uid bigint,
  rid bigint,
  constraint pk_users_roles primary key(id)
) charset=utf8 ENGINE=InnoDB;
   
create table role_permission (
  id bigint auto_increment,
  rid bigint,
  pid bigint,
  constraint pk_roles_permissions primary key(id)
) charset=utf8 ENGINE=InnoDB;

表数据

 INSERT INTO `permission` VALUES (1,'addProduct','增加产品','/addProduct');
INSERT INTO `permission` VALUES (2,'deleteProduct','删除产品','/deleteProduct');
INSERT INTO `permission` VALUES (3,'editeProduct','编辑产品','/editeProduct');
INSERT INTO `permission` VALUES (4,'updateProduct','修改产品','/updateProduct');
INSERT INTO `permission` VALUES (5,'listProduct','查看产品','/listProduct');
INSERT INTO `permission` VALUES (6,'addOrder','增加订单','/addOrder');
INSERT INTO `permission` VALUES (7,'deleteOrder','删除订单','/deleteOrder');
INSERT INTO `permission` VALUES (8,'editeOrder','编辑订单','/editeOrder');
INSERT INTO `permission` VALUES (9,'updateOrder','修改订单','/updateOrder');
INSERT INTO `permission` VALUES (10,'listOrder','查看订单','/listOrder');
INSERT INTO `role` VALUES (1,'admin','超级管理员');
INSERT INTO `role` VALUES (2,'productManager','产品管理员');
INSERT INTO `role` VALUES (3,'orderManager','订单管理员');
INSERT INTO `role_permission` VALUES (1,1,1);
INSERT INTO `role_permission` VALUES (2,1,2);
INSERT INTO `role_permission` VALUES (3,1,3);
INSERT INTO `role_permission` VALUES (4,1,4);
INSERT INTO `role_permission` VALUES (5,1,5);
INSERT INTO `role_permission` VALUES (6,1,6);
INSERT INTO `role_permission` VALUES (7,1,7);
INSERT INTO `role_permission` VALUES (8,1,8);
INSERT INTO `role_permission` VALUES (9,1,9);
INSERT INTO `role_permission` VALUES (10,1,10);
INSERT INTO `role_permission` VALUES (11,2,1);
INSERT INTO `role_permission` VALUES (12,2,2);
INSERT INTO `role_permission` VALUES (13,2,3);
INSERT INTO `role_permission` VALUES (14,2,4);
INSERT INTO `role_permission` VALUES (15,2,5);
INSERT INTO `role_permission` VALUES (50,3,10);
INSERT INTO `role_permission` VALUES (51,3,9);
INSERT INTO `role_permission` VALUES (52,3,8);
INSERT INTO `role_permission` VALUES (53,3,7);
INSERT INTO `role_permission` VALUES (54,3,6);
INSERT INTO `role_permission` VALUES (55,3,1);
INSERT INTO `role_permission` VALUES (56,5,11);
INSERT INTO `user` VALUES (1,'zhang3','a7d59dfc5332749cb801f86a24f5f590','e5ykFiNwShfCXvBRPr3wXg==');
INSERT INTO `user` VALUES (2,'li4','43e28304197b9216e45ab1ce8dac831b','jPz19y7arvYIGhuUjsb6sQ==');
INSERT INTO `user_role` VALUES (43,2,2);
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>

代码如下:

 <?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"
xmlns:web="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_2_5.xsd" version="2.5"> <!-- 中文过滤器 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- spring的配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml,
classpath:applicationContext-shiro.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- spring mvc核心:分发servlet -->
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- spring mvc的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- Shiro配置 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>

applicationContext.xml

1.配置数据库的相关信息(这些配置根据自己的需要自行修改)
2. 扫描mybatis的mapper之类的

代码如下:

 <?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:annotation-config />
<context:component-scan base-package="com.how2java.service" /> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/shiroweb?characterEncoding=UTF-8</value> </property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>root</value>
</property>
</bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.how2java.pojo" />
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:com/how2java/mapper/*.xml"/>
</bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.how2java.mapper"/>
</bean> </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>

代码如下:

 <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd"> <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 调用我们配置的权限管理器 -->
<property name="securityManager" ref="securityManager" />
<!-- 配置我们的登录请求地址 -->
<property name="loginUrl" value="/login" />
<!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->
<property name="unauthorizedUrl" value="/unauthorized" />
<!-- 退出 -->
<property name="filters">
<util:map>
<entry key="logout" value-ref="logoutFilter" />
</util:map>
</property>
<!-- 权限配置 -->
<property name="filterChainDefinitions">
<value>
<!-- anon表示此地址不需要任何权限即可访问 -->
/login=anon
/index=anon
/static/**=anon
<!-- 只对业务功能进行权限管理,权限配置本身不需要没有做权限要求,这样做是为了不让初学者混淆 -->
/config/**=anon
/doLogout=logout
<!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login -->
/** = authc
</value>
</property>
</bean>
<!-- 退出过滤器 -->
<bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
<property name="redirectUrl" value="/index" />
</bean> <!-- 会话ID生成器 -->
<bean id="sessionIdGenerator"
class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />
<!-- 会话Cookie模板 关闭浏览器立即失效 -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="sid" />
<property name="httpOnly" value="true" />
<property name="maxAge" value="-1" />
</bean>
<!-- 会话DAO -->
<bean id="sessionDAO"
class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<property name="sessionIdGenerator" ref="sessionIdGenerator" />
</bean>
<!-- 会话验证调度器,每30分钟执行一次验证 ,设定会话超时及保存 -->
<bean name="sessionValidationScheduler"
class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
<property name="interval" value="1800000" />
<property name="sessionManager" ref="sessionManager" />
</bean>
<!-- 会话管理器 -->
<bean id="sessionManager"
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- 全局会话超时时间(单位毫秒),默认30分钟 -->
<property name="globalSessionTimeout" value="1800000" />
<property name="deleteInvalidSessions" value="true" />
<property name="sessionValidationSchedulerEnabled" value="true" />
<property name="sessionValidationScheduler" ref="sessionValidationScheduler" />
<property name="sessionDAO" ref="sessionDAO" />
<property name="sessionIdCookieEnabled" value="true" />
<property name="sessionIdCookie" ref="sessionIdCookie" />
</bean> <!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="databaseRealm" />
<property name="sessionManager" ref="sessionManager" />
</bean>
<!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"
value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean> <!-- 密码匹配器 -->
<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> <bean id="databaseRealm" class="com.how2java.realm.DatabaseRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean> <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>

springMVC.xml

1.springmvc的基本配置
2. 增加了对shiro的支持
这样可以在控制器Controller上,使用像@RequireRole 这样的注解,来表示某个方法必须有相关的角色才能访问
3. 指定了异常处理类DefaultExceptionHandler,这样当访问没有权限的资源的时候,就会跳到统一的页面去显示错误信息

代码如下:

 <?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"> <context:annotation-config/> <context:component-scan base-package="com.how2java.controller">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean> <!--启用shiro注解 -->
<bean
class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<property name="proxyTargetClass" value="true" />
</bean>
<bean
class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager" />
</bean> <!-- 控制器异常处理 -->
<bean id="exceptionHandlerExceptionResolver" class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
</bean>
<bean class="com.how2java.exception.DefaultExceptionHandler"/> </beans>

log4j.properties

代码如下:

 # Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.how2java=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
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配置权限。

代码如下:

 package com.how2java.controller;

 import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; //专门用于显示页面的控制器
@Controller
@RequestMapping("")
public class PageController { @RequestMapping("index")
public String index(){
return "index";
} @RequiresPermissions("deleteOrder")
@RequestMapping("deleteOrder")
public String deleteOrder(){
return "deleteOrder";
}
@RequiresRoles("productManager")
@RequestMapping("deleteProduct")
public String deleteProduct(){
return "deleteProduct";
}
@RequestMapping("listProduct")
public String listProduct(){
return "listProduct";
} @RequestMapping(value="/login",method=RequestMethod.GET)
public String login(){
return "login";
}
@RequestMapping("unauthorized")
public String noPerms(){
return "unauthorized";
}

View层的各个页面

直接贴出结构图和代码

index页面

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <link rel="stylesheet" type="text/css" href="static/css/style.css" /> </head>
<body> <div class="workingroom">
<div class="loginDiv"> <c:if test="${empty subject.principal}">
<a href="login">登录</a><br>
</c:if>
<c:if test="${!empty subject.principal}">
<span class="desc">你好,${subject.principal},</span>
<a href="doLogout">退出</a><br>
</c:if> <a href="listProduct">查看产品</a><span class="desc">(登录后才可以查看) </span><br>
<a href="deleteProduct">删除产品</a><span class="desc">(要有产品管理员角色, zhang3没有,li4 有) </span><br>
<a href="deleteOrder">删除订单</a><span class="desc">(要有删除订单权限, zhang3有,li4没有) </span><br>
</div> </body>
</html>

login.jsp登陆页面

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%> <!DOCTYPE html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="static/css/style.css" /> <div class="workingroom"> <div class="errorInfo">${error}</div>
<form action="login" method="post">
账号: <input type="text" name="name"> <br>
密码: <input type="password" name="password"> <br>
<br>
<input type="submit" value="登录">
<br>
<br>
<div>
<span class="desc">账号:zhang3 密码:12345 角色:admin</span><br>
<span class="desc">账号:li4 密码:abcde 角色:productManager</span><br>
</div> </form>
</div>

listProduct.jsp  需要登录才能访问的页面

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%> <!DOCTYPE html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="static/css/style.css" /> <div class="workingroom"> listProduct.jsp ,能进来,就表示已经登录成功了
<br>
<a href="#" onClick="javascript:history.back()">返回</a>
</div>

deleteProduct.jsp 需要角色才能访问的页面

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%> <!DOCTYPE html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="static/css/style.css" /> <div class="workingroom"> deleteProduct.jsp,能进来<br>就表示拥有 productManager 角色
<br>
<a href="#" onClick="javascript:history.back()">返回</a>
</div>

deleteOrder.jsp 需要权限deleteOrder 才能访问的页面

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%> <!DOCTYPE html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="static/css/style.css" /> <div class="workingroom"> deleteOrder.jsp ,能进来,就表示有deleteOrder权限
<br>
<a href="#" onClick="javascript:history.back()">返回</a>
</div>

unauthorized.jsp没有角色,没有权限都会跳转到这个页面来

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" import="java.util.*"%> <!DOCTYPE html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="static/css/style.css" /> <div class="workingroom"> 权限不足,具体原因:${ex.message}
<br>
<a href="#" onClick="javascript:history.back()">返回</a>
</div>

menu.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<div class="menu">
<a href="listUser">用户管理</a>
<a href="listRole">角色管理</a>
<a href="listPermission">权限管理</a>
</div>

style.css

 span.desc{
margin-left:20px;
color:gray;
}
div.workingroom{
margin:200px auto;
width:600px;
position:relative;
}
div.workingroom a{
/* display:inline-block; */
/* margin-top:20px; */
}
div.loginDiv{
text-align: left;
}
div.errorInfo{
color:red;
font-size:0.65em;
}
div.workingroom td{
border:1px solid black;
}
div.workingroom table{
border-collapse:collapse;
width:100%;
} div.workingroom td{
border:1px solid black;
} div.workingroom div.menu{
position:absolute;
left:-160px;
top:-20px;
}
div.workingroom div.menu a{
display:block;
margin-top:20px;
} div.workingroom div.addOrEdit{
margin:20px;
text-align:center;
}

listUser.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <link rel="stylesheet" type="text/css" href="../static/css/style.css" />
</head>
<body> <div class="workingroom">
<%@include file="include/menu.jsp" %>
<table>
<tr>
<td>id</td>
<td>用户名称</td>
<td>用户密码</td>
<td>加密盐</td>
<td>角色</td>
<td>编辑</td>
<td>删除</td>
</tr>
<c:forEach items="${us}" var="u">
<tr>
<td>${u.id}</td>
<td>${u.name}</td>
<td>${fn:substring(u.password, 0, 5)}...</td>
<td>${fn:substring(u.salt, 0, 5)}...</td>
<td>
<c:forEach items="${user_roles[u]}" var="r">
${r.name} <br>
</c:forEach>
</td>
<td><a href="editUser?id=${u.id}">编辑</a></td>
<td><a href="deleteUser?id=${u.id}">删除</a></td>
</tr>
</c:forEach>
</table> <div class="addOrEdit" >
<form action="addUser" method="post">
用户名: <input type="text" name="name"> <br>
密码: <input type="password" name="password"> <br><br>
<input type="submit" value="增加">
</form>
</div>
</div>
</body>
</html>

editUser.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> </head>
<body> <div class="workingroom"> <%@include file="include/menu.jsp" %> <div class="addOrEdit" >
<form action="updateUser" method="post">
用户名: <input type="text" name="name" value="${user.name}"> <br><br>
密码: <input type="password" name="password" value="" placeholder="留空就表示不修改密码"> <br><br>
配置角色:<br>
<div style="text-align:left;width:300px;margin:0px auto;padding-left:50px">
<c:forEach items="${rs}" var="r">
<c:set var="hasRole" value="false" />
<c:forEach items="${currentRoles}" var="currentRole">
<c:if test="${r.id==currentRole.id}">
<c:set var="hasRole" value="true" />
</c:if>
</c:forEach>
<input type="checkbox" ${hasRole?"checked='checked'":"" } name="roleIds" value="${r.id}"> ${r.name}<br>
</c:forEach>
</div> <br>
<input type="hidden" name="id" value="${user.id}">
<input type="submit" value="修改">
</form>
</div>
</div>
<script>
</script>
</body>
</html>

listRole.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> </head>
<body> <div class="workingroom"> <%@include file="include/menu.jsp" %> <table>
<tr>
<td>id</td>
<td>角色名称</td>
<td>角色描述</td>
<td>权限</td>
<td>编辑</td>
<td>删除</td>
</tr>
<c:forEach items="${rs}" var="r">
<tr>
<td>${r.id}</td>
<td>${r.name}</td>
<td>${r.desc_}</td>
<td>
<c:forEach items="${role_permissions[r]}" var="p">
${p.name} <br>
</c:forEach>
</td> <td><a href="editRole?id=${r.id}">编辑</a></td>
<td><a href="deleteRole?id=${r.id}">删除</a></td>
</tr>
</c:forEach>
</table> <div class="addOrEdit" >
<form action="addRole" method="post">
角色名称: <input type="text" name="name"> <br>
角色描述: <input type="text" name="desc_"> <br><br>
<input type="submit" value="增加">
</form>
</div>
</div>
</body>
</html>

editRole.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> </head>
<body> <div class="workingroom"> <%@include file="include/menu.jsp" %> <div class="addOrEdit" >
<form action="updateRole" method="post">
角色名: <input type="text" name="name" value="${role.name}"> <br>
角色描述: <input type="text" name="desc_" value="${role.desc_}" > <br><br>
配置权限:<br>
<div style="text-align:left;width:300px;margin:0px auto;padding-left:50px">
<c:forEach items="${ps}" var="p">
<c:set var="hasPermission" value="false" />
<c:forEach items="${currentPermissions}" var="currentPermission">
<c:if test="${p.id==currentPermission.id}">
<c:set var="hasPermission" value="true" />
</c:if>
</c:forEach>
<input type="checkbox" ${hasPermission?"checked='checked'":"" } name="permissionIds" value="${p.id}"> ${p.name}<br>
</c:forEach>
</div> <input type="hidden" name="id" value="${role.id}">
<input type="submit" value="修改">
</form>
</div>
</div>
</body>
</html>

listPermission.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> </head>
<body> <div class="workingroom"> <%@include file="include/menu.jsp" %> <table>
<tr>
<td>id</td>
<td>权限名称</td>
<td>权限描述</td>
<td>权限对应的路径</td>
<td>编辑</td>
<td>删除</td>
</tr>
<c:forEach items="${ps}" var="p">
<tr>
<td>${p.id}</td>
<td>${p.name}</td>
<td>${p.desc_}</td>
<td>${p.url}</td>
<td><a href="editPermission?id=${p.id}">编辑</a></td>
<td><a href="deletePermission?id=${p.id}">删除</a></td>
</tr>
</c:forEach>
</table> <div class="addOrEdit" >
<form action="addPermission" method="post">
权限名称: <input type="text" name="name"> <br>
权限描述: <input type="text" name="desc_"> <br>
权限对应的url: <input type="text" name="url"> <br><br>
<input type="submit" value="增加">
</form>
</div>
</div>
</body>
</html>

editPermission.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <link rel="stylesheet" type="text/css" href="../static/css/style.css" /> </head>
<body> <div class="workingroom"> <%@include file="include/menu.jsp" %> <div class="addOrEdit" >
<form action="updatePermission" method="post">
权限名称: <input type="text" name="name" value="${permission.name}"> <br>
权限描述: <input type="text" name="desc_" value="${permission.desc_}"> <br>
权限对应的url: <input type="text" name="url" value="${permission.url}"> <br><br>
<input type="hidden" name="id" value="${permission.id}">
<input type="submit" value="修改">
</form>
</div>
</div>
</body>
</html>

OverIsMergeablePlugin.java

这个类的解释见,解决MybatisGenerator多次运行mapper生成重复内容

代码如下:

 package com.how2java.util;

 import org.mybatis.generator.api.GeneratedXmlFile;

 import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter; import java.lang.reflect.Field;
import java.util.List; public class OverIsMergeablePlugin extends PluginAdapter {
@Override
public boolean validate(List<String> warnings) {
return true;
} @Override
public boolean sqlMapGenerated(GeneratedXmlFile sqlMap, IntrospectedTable introspectedTable) {
try {
Field field = sqlMap.getClass().getDeclaredField("isMergeable");
field.setAccessible(true);
field.setBoolean(sqlMap, false);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
}

generatorConfig.xml

目录如下:

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration> <context id="DB2Tables" targetRuntime="MyBatis3">
<!--避免生成重复代码的插件-->
<plugin type="com.how2java.util.OverIsMergeablePlugin" /> <!--是否在代码中显示注释-->
<commentGenerator>
<property name="suppressDate" value="true" />
<property name="suppressAllComments" value="true" />
</commentGenerator> <!--数据库链接地址账号密码-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/shiro" userId="root" password="admin">
</jdbcConnection>
<!--不知道做什么用的。。。反正贴上来了~-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!--生成pojo类存放位置-->
<javaModelGenerator targetPackage="com.how2java.pojo" targetProject="src">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--生成xml映射文件存放位置-->
<sqlMapGenerator targetPackage="com.how2java.mapper" targetProject="src">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--生成mapper类存放位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.how2java.mapper" targetProject="src">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator> <!--生成对应表及类名-->
<table tableName="user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
<property name="my.isgen.usekeys" value="true"/>
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
<table tableName="role" domainObjectName="Role" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
<property name="my.isgen.usekeys" value="true"/>
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
<table tableName="permission" domainObjectName="Permission" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
<property name="my.isgen.usekeys" value="true"/>
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
<table tableName="user_role" domainObjectName="UserRole" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
<property name="my.isgen.usekeys" value="true"/>
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="JDBC"/>
</table>
<table tableName="role_permission" domainObjectName="RolePermission" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="true" selectByExampleQueryId="false">
<property name="my.isgen.usekeys" value="true"/>
<property name="useActualColumnNames" value="true"/>
<generatedKey column="id" sqlStatement="JDBC"/>
</table> </context>
</generatorConfiguration>

MybatisGenerator.java

代码如下:

 package com.how2java.util;

 import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback; import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; public class MybatisGenerator { public static void main(String[] args) throws Exception {
String today = "2018-5-21"; SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd");
Date now =sdf.parse(today);
Date d = new Date(); if(d.getTime()>now.getTime()+1000*60*60*24){
System.err.println("——————未成成功运行——————");
System.err.println("——————未成成功运行——————");
System.err.println("本程序具有破坏作用,应该只运行一次,如果必须要再运行,需要修改today变量为今天,如:" + sdf.format(new Date()));
return;
} if(false)
return;
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
InputStream is= MybatisGenerator.class.getClassLoader().getResource("generatorConfig.xml").openStream();
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(is);
is.close();
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null); System.out.println("生成代码成功,只能执行一次,以后执行会覆盖掉mapper,pojo,xml 等文件上做的修改"); }
}

运行 MybatisGenerator 以获取自动生成 Pojo、Example 和 Mapper

记得刷新一下项目。

Service层

PermissionService

 package com.how2java.service;

 import java.util.List;
import java.util.Set; import com.how2java.pojo.Permission;
import com.how2java.pojo.Role; public interface PermissionService {
public Set<String> listPermissions(String userName); public List<Permission> list();
public void add(Permission permission);
public void delete(Long id);
public Permission get(Long id);
public void update(Permission permission); public List<Permission> list(Role role); }

RolePermissionService

 package com.how2java.service;

 import com.how2java.pojo.Role;

 public interface RolePermissionService {
public void setPermissions(Role role, long[] permissionIds);
public void deleteByRole(long roleId);
public void deleteByPermission(long permissionId);
}

RoleService

 package com.how2java.service;

 import java.util.List;
import java.util.Set; import com.how2java.pojo.Role;
import com.how2java.pojo.User; public interface RoleService {
public Set<String> listRoleNames(String userName);
public List<Role> listRoles(String userName);
public List<Role> listRoles(User user); public List<Role> list();
public void add(Role role);
public void delete(Long id);
public Role get(Long id);
public void update(Role role); }

UserRoleService

 package com.how2java.service;

 import com.how2java.pojo.User;

 public interface UserRoleService {

     public void setRoles(User user, long[] roleIds);
public void deleteByUser(long userId);
public void deleteByRole(long roleId); }

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

 package com.how2java.service.impl;

 import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.how2java.mapper.PermissionMapper;
import com.how2java.mapper.RolePermissionMapper;
import com.how2java.pojo.Permission;
import com.how2java.pojo.PermissionExample;
import com.how2java.pojo.Role;
import com.how2java.pojo.RolePermission;
import com.how2java.pojo.RolePermissionExample;
import com.how2java.service.PermissionService;
import com.how2java.service.RoleService;
import com.how2java.service.UserService; @Service
public class PermissionServiceImpl implements PermissionService{ @Autowired PermissionMapper permissionMapper;
@Autowired UserService userService;
@Autowired RoleService roleService;
@Autowired RolePermissionMapper rolePermissionMapper; @Override
public Set<String> listPermissions(String userName) {
Set<String> result = new HashSet<>();
List<Role> roles = roleService.listRoles(userName); List<RolePermission> rolePermissions = new ArrayList<>(); for (Role role : roles) {
RolePermissionExample example = new RolePermissionExample();
example.createCriteria().andRidEqualTo(role.getId());
List<RolePermission> rps= rolePermissionMapper.selectByExample(example);
rolePermissions.addAll(rps);
} for (RolePermission rolePermission : rolePermissions) {
Permission p = permissionMapper.selectByPrimaryKey(rolePermission.getPid());
result.add(p.getName());
} return result;
}
@Override
public void add(Permission u) {
permissionMapper.insert(u);
} @Override
public void delete(Long id) {
permissionMapper.deleteByPrimaryKey(id);
} @Override
public void update(Permission u) {
permissionMapper.updateByPrimaryKeySelective(u);
} @Override
public Permission get(Long id) {
return permissionMapper.selectByPrimaryKey(id);
} @Override
public List<Permission> list(){
PermissionExample example =new PermissionExample();
example.setOrderByClause("id desc");
return permissionMapper.selectByExample(example); }
@Override
public List<Permission> list(Role role) {
List<Permission> result = new ArrayList<>();
RolePermissionExample example = new RolePermissionExample();
example.createCriteria().andRidEqualTo(role.getId());
List<RolePermission> rps = rolePermissionMapper.selectByExample(example);
for (RolePermission rolePermission : rps) {
result.add(permissionMapper.selectByPrimaryKey(rolePermission.getPid()));
} return result;
} }

RolePermissionServiceImpl

 package com.how2java.service.impl;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.how2java.mapper.RolePermissionMapper;
import com.how2java.pojo.Permission;
import com.how2java.pojo.Role;
import com.how2java.pojo.RolePermission;
import com.how2java.pojo.RolePermissionExample;
import com.how2java.service.RolePermissionService; @Service
public class RolePermissionServiceImpl implements RolePermissionService{ @Autowired RolePermissionMapper rolePermissionMapper; @Override
public void setPermissions(Role role, long[] permissionIds) {
//删除当前角色所有的权限
RolePermissionExample example= new RolePermissionExample();
example.createCriteria().andRidEqualTo(role.getId());
List<RolePermission> rps= rolePermissionMapper.selectByExample(example);
for (RolePermission rolePermission : rps)
rolePermissionMapper.deleteByPrimaryKey(rolePermission.getId()); //设置新的权限关系
if(null!=permissionIds)
for (long pid : permissionIds) {
RolePermission rolePermission = new RolePermission();
rolePermission.setPid(pid);
rolePermission.setRid(role.getId());
rolePermissionMapper.insert(rolePermission);
}
} @Override
public void deleteByRole(long roleId) {
RolePermissionExample example= new RolePermissionExample();
example.createCriteria().andRidEqualTo(roleId);
List<RolePermission> rps= rolePermissionMapper.selectByExample(example);
for (RolePermission rolePermission : rps)
rolePermissionMapper.deleteByPrimaryKey(rolePermission.getId());
} @Override
public void deleteByPermission(long permissionId) {
RolePermissionExample example= new RolePermissionExample();
example.createCriteria().andPidEqualTo(permissionId);
List<RolePermission> rps= rolePermissionMapper.selectByExample(example);
for (RolePermission rolePermission : rps)
rolePermissionMapper.deleteByPrimaryKey(rolePermission.getId());
} }

RoleServiceImpl

 package com.how2java.service.impl;

 import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.how2java.mapper.RoleMapper;
import com.how2java.mapper.UserRoleMapper;
import com.how2java.pojo.Role;
import com.how2java.pojo.RoleExample;
import com.how2java.pojo.User;
import com.how2java.pojo.UserRole;
import com.how2java.pojo.UserRoleExample;
import com.how2java.service.RoleService;
import com.how2java.service.UserService; @Service
public class RoleServiceImpl implements RoleService{
@Autowired RoleMapper roleMapper;
@Autowired UserRoleMapper userRoleMapper;
@Autowired UserService userService; @Override
public Set<String> listRoleNames(String userName) {
Set<String> result = new HashSet<>();
List<Role> roles = listRoles(userName);
for (Role role : roles) {
result.add(role.getName());
}
return result;
} @Override
public List<Role> listRoles(String userName) {
List<Role> roles = new ArrayList<>();
User user = userService.getByName(userName);
if(null==user)
return roles; roles = listRoles(user);
return roles;
} @Override
public void add(Role u) {
roleMapper.insert(u);
} @Override
public void delete(Long id) {
roleMapper.deleteByPrimaryKey(id);
} @Override
public void update(Role u) {
roleMapper.updateByPrimaryKeySelective(u);
} @Override
public Role get(Long id) {
return roleMapper.selectByPrimaryKey(id);
} @Override
public List<Role> list(){
RoleExample example =new RoleExample();
example.setOrderByClause("id desc");
return roleMapper.selectByExample(example); } @Override
public List<Role> listRoles(User user) {
List<Role> roles = new ArrayList<>(); UserRoleExample example = new UserRoleExample(); example.createCriteria().andUidEqualTo(user.getId());
List<UserRole> userRoles= userRoleMapper.selectByExample(example); for (UserRole userRole : userRoles) {
Role role=roleMapper.selectByPrimaryKey(userRole.getRid());
roles.add(role);
}
return roles;
} }

UserRoleServiceImpl

 package com.how2java.service.impl;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.how2java.mapper.UserRoleMapper;
import com.how2java.pojo.Role;
import com.how2java.pojo.User;
import com.how2java.pojo.UserRole;
import com.how2java.pojo.UserRoleExample;
import com.how2java.service.UserRoleService; @Service
public class UserRoleServiceImpl implements UserRoleService{ @Autowired UserRoleMapper userRoleMapper;
@Override
public void setRoles(User user, long[] roleIds) {
//删除当前用户所有的角色
UserRoleExample example= new UserRoleExample();
example.createCriteria().andUidEqualTo(user.getId());
List<UserRole> urs= userRoleMapper.selectByExample(example);
for (UserRole userRole : urs)
userRoleMapper.deleteByPrimaryKey(userRole.getId()); //设置新的角色关系
if(null!=roleIds)
for (long rid : roleIds) {
UserRole userRole = new UserRole();
userRole.setRid(rid);
userRole.setUid(user.getId());
userRoleMapper.insert(userRole);
}
}
@Override
public void deleteByUser(long userId) {
UserRoleExample example= new UserRoleExample();
example.createCriteria().andUidEqualTo(userId);
List<UserRole> urs= userRoleMapper.selectByExample(example);
for (UserRole userRole : urs) {
userRoleMapper.deleteByPrimaryKey(userRole.getId());
}
}
@Override
public void deleteByRole(long roleId) {
UserRoleExample example= new UserRoleExample();
example.createCriteria().andRidEqualTo(roleId);
List<UserRole> urs= userRoleMapper.selectByExample(example);
for (UserRole userRole : urs) {
userRoleMapper.deleteByPrimaryKey(userRole.getId());
}
} }

UserServiceImpl

 package com.how2java.service.impl;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.how2java.mapper.UserMapper;
import com.how2java.pojo.User;
import com.how2java.pojo.UserExample;
import com.how2java.service.UserRoleService;
import com.how2java.service.UserService; @Service
public class UserServiceImpl implements UserService{ @Autowired UserMapper userMapper;
@Autowired UserRoleService userRoleService; @Override
public String getPassword(String name) {
User user = getByName(name);
if(null==user)
return null;
return user.getPassword();
} @Override
public User getByName(String name) {
UserExample example = new UserExample();
example.createCriteria().andNameEqualTo(name);
List<User> users = userMapper.selectByExample(example);
if(users.isEmpty())
return null;
return users.get(0);
} @Override
public void add(User u) {
userMapper.insert(u);
} @Override
public void delete(Long id) {
userMapper.deleteByPrimaryKey(id);
userRoleService.deleteByUser(id);
} @Override
public void update(User u) {
userMapper.updateByPrimaryKeySelective(u);
} @Override
public User get(Long id) {
return userMapper.selectByPrimaryKey(id);
} @Override
public List<User> list(){
UserExample example =new UserExample();
example.setOrderByClause("id desc");
return userMapper.selectByExample(example); } }

Controller 层

LoginController

 package com.how2java.controller;

 import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; @Controller
@RequestMapping("")
public class LoginController {
@RequestMapping(value="/login",method=RequestMethod.POST)
public String login(Model model,String name, String password) {
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(name, password);
try {
subject.login(token);
Session session=subject.getSession();
session.setAttribute("subject", subject);
return "redirect:index"; } catch (AuthenticationException e) {
model.addAttribute("error", "验证失败");
return "login";
}
} }

PageController

上面已贴

PermissionController

 package com.how2java.controller;

 import java.util.List;

 import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import com.how2java.pojo.Permission;
import com.how2java.service.PermissionService; @Controller
@RequestMapping("config")
public class PermissionController {
@Autowired PermissionService permissionService; @RequestMapping("listPermission")
public String list(Model model){
List<Permission> ps= permissionService.list();
model.addAttribute("ps", ps);
return "listPermission";
}
@RequestMapping("editPermission")
public String list(Model model,long id){
Permission permission =permissionService.get(id);
model.addAttribute("permission", permission);
return "editPermission";
}
@RequestMapping("updatePermission")
public String update(Permission permission){ permissionService.update(permission);
return "redirect:listPermission";
} @RequestMapping("addPermission")
public String list(Model model,Permission permission){
System.out.println(permission.getName());
System.out.println(permission.getDesc_());
permissionService.add(permission);
return "redirect:listPermission";
}
@RequestMapping("deletePermission")
public String delete(Model model,long id){
permissionService.delete(id);
return "redirect:listPermission";
} }

RoleController

 package com.how2java.controller;

 import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import com.how2java.pojo.Permission;
import com.how2java.pojo.Role;
import com.how2java.service.PermissionService;
import com.how2java.service.RolePermissionService;
import com.how2java.service.RoleService; @Controller
@RequestMapping("config")
public class RoleController {
@Autowired RoleService roleService;
@Autowired RolePermissionService rolePermissionService;
@Autowired PermissionService permissionService; @RequestMapping("listRole")
public String list(Model model){
List<Role> rs= roleService.list();
model.addAttribute("rs", rs); Map<Role,List<Permission>> role_permissions = new HashMap<>(); for (Role role : rs) {
List<Permission> ps = permissionService.list(role);
role_permissions.put(role, ps);
}
model.addAttribute("role_permissions", role_permissions); return "listRole";
}
@RequestMapping("editRole")
public String list(Model model,long id){
Role role =roleService.get(id);
model.addAttribute("role", role); List<Permission> ps = permissionService.list();
model.addAttribute("ps", ps); List<Permission> currentPermissions = permissionService.list(role);
model.addAttribute("currentPermissions", currentPermissions); return "editRole";
}
@RequestMapping("updateRole")
public String update(Role role,long[] permissionIds){
rolePermissionService.setPermissions(role, permissionIds);
roleService.update(role);
return "redirect:listRole";
} @RequestMapping("addRole")
public String list(Model model,Role role){
System.out.println(role.getName());
System.out.println(role.getDesc_());
roleService.add(role);
return "redirect:listRole";
}
@RequestMapping("deleteRole")
public String delete(Model model,long id){
roleService.delete(id);
return "redirect:listRole";
} }

UserController

 package com.how2java.controller;

 import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping; import com.how2java.pojo.Role;
import com.how2java.pojo.User;
import com.how2java.service.RoleService;
import com.how2java.service.UserRoleService;
import com.how2java.service.UserService; @Controller
@RequestMapping("config")
public class UserController {
@Autowired UserRoleService userRoleService;
@Autowired UserService userService;
@Autowired RoleService roleService; @RequestMapping("listUser")
public String list(Model model){
List<User> us= userService.list();
model.addAttribute("us", us);
Map<User,List<Role>> user_roles = new HashMap<>();
for (User user : us) {
List<Role> roles=roleService.listRoles(user);
user_roles.put(user, roles);
}
model.addAttribute("user_roles", user_roles); return "listUser";
}
@RequestMapping("editUser")
public String edit(Model model,long id){
List<Role> rs = roleService.list();
model.addAttribute("rs", rs);
User user =userService.get(id);
model.addAttribute("user", user); List<Role> roles =roleService.listRoles(user);
model.addAttribute("currentRoles", roles); return "editUser";
}
@RequestMapping("deleteUser")
public String delete(Model model,long id){
userService.delete(id);
return "redirect:listUser";
}
@RequestMapping("updateUser")
public String update(User user,long[] roleIds){
userRoleService.setRoles(user,roleIds); String password=user.getPassword();
//如果在修改的时候没有设置密码,就表示不改动密码
if(user.getPassword().length()!=0) {
String salt = new SecureRandomNumberGenerator().nextBytes().toString();
int times = 2;
String algorithmName = "md5";
String encodedPassword = new SimpleHash(algorithmName,password,salt,times).toString();
user.setSalt(salt);
user.setPassword(encodedPassword);
}
else
user.setPassword(null); userService.update(user); return "redirect:listUser"; } @RequestMapping("addUser")
public String add(Model model,String name, String password){ String salt = new SecureRandomNumberGenerator().nextBytes().toString();
int times = 2;
String algorithmName = "md5"; String encodedPassword = new SimpleHash(algorithmName,password,salt,times).toString(); User u = new User();
u.setName(name);
u.setPassword(encodedPassword);
u.setSalt(salt);
userService.add(u); return "redirect:listUser";
} }

DatabaseRealm

代码如下:

 package com.how2java.realm;

 import java.util.Set;

 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.codec.CodecException;
import org.apache.shiro.crypto.UnknownAlgorithmException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired; import com.how2java.pojo.User;
import com.how2java.service.PermissionService;
import com.how2java.service.RoleService;
import com.how2java.service.UserService; public class DatabaseRealm extends AuthorizingRealm { @Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private PermissionService permissionService; @Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//能进入到这里,表示账号已经通过验证了
String userName =(String) principalCollection.getPrimaryPrincipal();
//通过service获取角色和权限
Set<String> permissions = permissionService.listPermissions(userName);
Set<String> roles = roleService.listRoleNames(userName); //授权对象
SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
//把通过service获取到的角色和权限放进去
s.setStringPermissions(permissions);
s.setRoles(roles);
return s;
} @Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//获取账号密码
UsernamePasswordToken t = (UsernamePasswordToken) token;
String userName= token.getPrincipal().toString();
//获取数据库中的密码
User user =userService.getByName(userName);
String passwordInDB = user.getPassword();
String salt = user.getSalt();
//认证信息里存放账号密码, getName() 是当前Realm的继承方法,通常返回当前类名 :databaseRealm
//盐也放进去
//这样通过applicationContext-shiro.xml里配置的 HashedCredentialsMatcher 进行自动校验
SimpleAuthenticationInfo a = new SimpleAuthenticationInfo(userName,passwordInDB,ByteSource.Util.bytes(salt),getName());
return a;
} }
DefaultExceptionHandler
代码如下:
package com.how2java.exception; import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView; @ControllerAdvice
public class DefaultExceptionHandler {
@ExceptionHandler({UnauthorizedException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
ModelAndView mv = new ModelAndView();
mv.addObject("ex", e);
mv.setViewName("unauthorized");
return mv;
}
}

DefaultExceptionHandler

 package com.how2java.exception;

 import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView; @ControllerAdvice
public class DefaultExceptionHandler {
@ExceptionHandler({UnauthorizedException.class})
@ResponseStatus(HttpStatus.UNAUTHORIZED)
public ModelAndView processUnauthenticatedException(NativeWebRequest request, UnauthorizedException e) {
ModelAndView mv = new ModelAndView();
mv.addObject("ex", e);
mv.setViewName("unauthorized");
return mv;
}
}

http://127.0.0.1:8080/shirossm/config/listUser

http://127.0.0.1:8080/shirossm/index

项目名不一致的话自行修改。

不过此时的权限还是通过注解@RequiresRoles、@RequiresPermissions实现,而非动态url.。之后会在此基础上实现动态url了。

基本代码都贴出来了。如有需要demo源码,请留言,互相交流学习乐意分享。

最新文章

  1. C# .Net :Excel NPOI导入导出操作教程之将Excel文件读取并写到数据库表,示例分享
  2. RF 基本方法
  3. inotify监控文件变化
  4. 用CMake设置Visual Studio工程中预处理器定义值
  5. 九、UINavigationController切换视图 实例
  6. 【GOF23设计模式】享元模式
  7. 第四次个人作业--必应词典(PC端)分析
  8. [IT学习]PowerBi 入门
  9. iOS9对SDK的影响(iOS9适配必看)
  10. WinForm媒体播放器
  11. visual studio 中将选中代码相同的代码的颜色设置,修改高亮颜色
  12. webstrom管理git
  13. bzoj1396
  14. PHP获取Post的原始数据方法小结(POST无变量名)
  15. 树莓派mariadb折腾
  16. 【转】学习Robot Framework必须掌握的库—-BuiltIn库
  17. python print()内置函数
  18. PID控制器(比例-积分-微分控制器)- III
  19. getWidth() 和 getMeasuredWidth()的区别
  20. 在Linux 系统 Latex安装 使用入门教程

热门文章

  1. 牛客练习赛38 E 出题人的数组 2018ccpc桂林A题 贪心
  2. Codeforces Round #504 E - Down or Right 交互题
  3. 牛客2018多校第六场 J Heritage of skywalkert - nth_element
  4. 杭电多校第十场 hdu6432 Cyclic 打表找规律
  5. 2017 计蒜之道 初赛 第五场 UCloud 的安全秘钥(中等)
  6. 天梯杯 PAT L2-013 红色警报
  7. 百度之星 资格赛 1003 度度熊与邪恶大魔王 dp(背包)
  8. Python 之父的解析器系列之五:左递归 PEG 语法
  9. yzoj P1126 塔 题解
  10. SpringBoot+SpringMVC+MyBatis快速整合搭建