博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Springmvc+Mybatis+shiro整合
阅读量:5168 次
发布时间:2019-06-13

本文共 19345 字,大约阅读时间需要 64 分钟。

Apache Shiro是一个强大且易用的Java安全框架,执行身份验证、授权、密码学和会话管理。使用Shiro的易于理解的API,您可以快速、轻松地获得任何应用程序,从最小的移动应用程序到最大的网络和企业应用程序。

Shiro 主要分为来个部分就是认证和授权,在个人感觉来看就是查询数据库做相应的判断而已,Shiro只是一个框架而已,其中的内容需要自己的去构建,前后是自己的,中间是Shiro帮我们去搭建和配置好的

 

项目:创建maven项目web项目

 

pomx.xml配置好需要的jar包

4.0.0
com
oabyddh
war
0.0.1-SNAPSHOT
oabyddh Maven Webapp
http://maven.apache.org
junit
junit
3.8.1
test
javax.servlet
servlet-api
2.5
provided
org.mybatis
mybatis
3.4.1
mysql
mysql-connector-java
5.1.39
org.mybatis
mybatis-spring
1.3.0
org.springframework
spring-core
4.3.2.RELEASE
org.springframework
spring-jdbc
4.3.2.RELEASE
org.springframework
spring-aspects
4.3.2.RELEASE
org.springframework
spring-beans
4.3.2.RELEASE
org.springframework
spring-context
4.3.2.RELEASE
org.springframework
spring-context-support
4.3.2.RELEASE
org.springframework
spring-aop
4.3.2.RELEASE
org.springframework
spring-webmvc
4.3.2.RELEASE
org.springframework
spring-tx
4.3.2.RELEASE
org.springframework
spring-web
4.3.2.RELEASE
org.slf4j
slf4j-log4j12
1.7.21
javax.servlet
jstl
1.2
c3p0
c3p0
0.9.1.2
com.alibaba
fastjson
1.2.35
com.github.pagehelper
pagehelper
5.0.0
org.apache.shiro
shiro-core
1.2.2
org.apache.shiro
shiro-web
1.2.6
org.apache.shiro
shiro-spring
1.2.6
commons-fileupload
commons-fileupload
1.3.2
org.apache.poi
poi
3.15
org.apache.poi
poi-ooxml
3.15
org.csource
fastdfs_client
1.20
oabyddh
org.apache.maven.plugins
maven-compiler-plugin
2.3.2
1.6
1.6
UTF-8
UTF-8
UTF-8
UTF-8

web.xml配置文件:

oa system
contextConfigLocation
classpath:resources/spring.xml
characterEncodingFilter
org.springframework.web.filter.CharacterEncodingFilter
encoding
UTF-8
forceEncoding
true
shiroFilter
org.springframework.web.filter.DelegatingFilterProxy
targetFilterLifecycle
true
characterEncodingFilter
/*
shiroFilter
/*
org.springframework.web.util.IntrospectorCleanupListener
org.springframework.web.context.ContextLoaderListener
springMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:resources/springmvc.xml
springMVC
/
index.jsp

springmvc.xml

/exceptions
text/html;charset=utf-8
application/json
WriteMapNullValue
QuoteFieldNames

spring.xml

helperDialect=mysql

spring-shiro.xml

/css/**=anon /js/**=anon /fonts/**=anon /auth/**=anon /**=authc

oabyddh.properties

#\u6570\u636E\u5E93\u914D\u7F6Ejdbc.driverClass=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://172.16.27.11:3306/oabyddh?useUnicode=true&characterEncoding=utf8jdbc.user=oabyddhjdbc.password=oabyddh#\u56FE\u7247\u5B58\u50A8\u914D\u7F6EimgServerAddress=172.16.27.11imgServerPort=80

mybatis.xml

AuthController.java

package com.oabyddh.controller;import java.util.HashMap;import java.util.Map;import org.apache.shiro.SecurityUtils;import org.apache.shiro.authc.UsernamePasswordToken;import org.apache.shiro.subject.Subject;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import com.oabyddh.model.User;/** * 平台 登陆,退出控制器 * @author djoker * */@Controller@RequestMapping("/auth")public class AuthController {    /**     * 登陆控制器     * @param user     * @return     */    @ResponseBody    @RequestMapping("/ajaxLogin")        public Object login(User user) {        Map
res = new HashMap
(); UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(), user.getPassword()); Subject subject = SecurityUtils.getSubject(); try { subject.login(token); if(subject.isAuthenticated()) { res.put("code", "0"); res.put("msg", "登陆成功!"); } }catch(Exception e) { res.put("code", "-1"); res.put("msg", e.getMessage()); } return res; } /** * 退出控制器 * @return */ @ResponseBody @RequestMapping("/ajaxLogout") public Object logout() { SecurityUtils.getSubject().logout(); Map
res = new HashMap
(); res.put("code", "0"); res.put("msg", "退出成功!"); return res; }}

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><%@ page isELIgnored="false"%>    <%    String path = request.getContextPath();    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";    %>    

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>   <%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %> <%@ page isELIgnored="false"%><%    String path = request.getContextPath();    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";    %>    
你好管理员,属于manager组成员
新的一天,工作努力,工作加油!

数据库:

-- MySQL dump 10.13  Distrib 5.1.73, for redhat-linux-gnu (x86_64)---- Host: localhost    Database: oabyddh-- -------------------------------------------------------- Server version       5.1.73/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;/*!40101 SET NAMES utf8 */;/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;/*!40103 SET TIME_ZONE='+00:00' */;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;---- Table structure for table `tbl_groupMapPermission`--DROP TABLE IF EXISTS `tbl_groupMapPermission`;/*!40101 SET @saved_cs_client     = @@character_set_client */;/*!40101 SET character_set_client = utf8 */;CREATE TABLE `tbl_groupMapPermission` (  `id` int(255) NOT NULL AUTO_INCREMENT,  `groupId` int(255) DEFAULT NULL,  `permissionId` int(255) DEFAULT NULL,  `state` int(255) DEFAULT '0',  PRIMARY KEY (`id`),  KEY `groupId` (`groupId`),  KEY `permissionId` (`permissionId`),  CONSTRAINT `tbl_groupMapPermission_ibfk_1` FOREIGN KEY (`groupId`) REFERENCES `tbl_userGroups` (`id`),  CONSTRAINT `tbl_groupMapPermission_ibfk_2` FOREIGN KEY (`permissionId`) REFERENCES `tbl_permissions` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;/*!40101 SET character_set_client = @saved_cs_client */;---- Dumping data for table `tbl_groupMapPermission`--LOCK TABLES `tbl_groupMapPermission` WRITE;/*!40000 ALTER TABLE `tbl_groupMapPermission` DISABLE KEYS */;INSERT INTO `tbl_groupMapPermission` VALUES (1,1,1,0),(2,1,2,0),(3,1,3,0),(4,1,4,0);/*!40000 ALTER TABLE `tbl_groupMapPermission` ENABLE KEYS */;UNLOCK TABLES;---- Table structure for table `tbl_permissions`--DROP TABLE IF EXISTS `tbl_permissions`;/*!40101 SET @saved_cs_client     = @@character_set_client */;/*!40101 SET character_set_client = utf8 */;CREATE TABLE `tbl_permissions` (  `id` int(255) NOT NULL AUTO_INCREMENT,  `perName` varchar(255) NOT NULL,  `description` varchar(255) DEFAULT NULL,  PRIMARY KEY (`id`),  UNIQUE KEY `perName` (`perName`)) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;/*!40101 SET character_set_client = @saved_cs_client */;---- Dumping data for table `tbl_permissions`--LOCK TABLES `tbl_permissions` WRITE;/*!40000 ALTER TABLE `tbl_permissions` DISABLE KEYS */;INSERT INTO `tbl_permissions` VALUES (1,'manager:view','查看管理员权限'),(2,'manager:add','添加管理员权限'),(3,'manager:del','删除管理员权限'),(4,'manager:modify','修改管理员权限');/*!40000 ALTER TABLE `tbl_permissions` ENABLE KEYS */;UNLOCK TABLES;---- Table structure for table `tbl_userGroups`--DROP TABLE IF EXISTS `tbl_userGroups`;/*!40101 SET @saved_cs_client     = @@character_set_client */;/*!40101 SET character_set_client = utf8 */;CREATE TABLE `tbl_userGroups` (  `id` int(255) NOT NULL AUTO_INCREMENT,  `groupName` varchar(255) NOT NULL,  `description` varchar(255) DEFAULT NULL,  PRIMARY KEY (`id`),  UNIQUE KEY `groupName` (`groupName`)) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;/*!40101 SET character_set_client = @saved_cs_client */;---- Dumping data for table `tbl_userGroups`--LOCK TABLES `tbl_userGroups` WRITE;/*!40000 ALTER TABLE `tbl_userGroups` DISABLE KEYS */;INSERT INTO `tbl_userGroups` VALUES (1,'管理员组','管理员所属组'),(2,'经理组','经理职务所属组'),(3,'主管组','主管职务所属组'),(4,'财务组','财务职务所属组'),(5,'人事组','人事职务所属组'),(6,'员工组','普通员工所属组');/*!40000 ALTER TABLE `tbl_userGroups` ENABLE KEYS */;UNLOCK TABLES;---- Table structure for table `tbl_users`--DROP TABLE IF EXISTS `tbl_users`;/*!40101 SET @saved_cs_client     = @@character_set_client */;/*!40101 SET character_set_client = utf8 */;CREATE TABLE `tbl_users` (  `id` int(255) NOT NULL AUTO_INCREMENT,  `userName` varchar(255) NOT NULL,  `password` varchar(255) NOT NULL,  `realName` varchar(255) NOT NULL,  `groupId` int(255) DEFAULT NULL,  PRIMARY KEY (`id`),  UNIQUE KEY `userName` (`userName`),  KEY `groupId` (`groupId`),  CONSTRAINT `tbl_users_ibfk_1` FOREIGN KEY (`groupId`) REFERENCES `tbl_userGroups` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;/*!40101 SET character_set_client = @saved_cs_client */;---- Dumping data for table `tbl_users`--LOCK TABLES `tbl_users` WRITE;/*!40000 ALTER TABLE `tbl_users` DISABLE KEYS */;INSERT INTO `tbl_users` VALUES (1,'admin','9003d1df22eb4d3820015070385194c8','超级管理员',1),(2,'user01','9003d1df22eb4d3820015070385194c8','张楚岚',6);/*!40000 ALTER TABLE `tbl_users` ENABLE KEYS */;UNLOCK TABLES;/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;-- Dump completed on 2018-04-28 23:18:42

使用到的js文件:oabyddh.js

/*************登陆与退出***************///登陆平台function login(){    var userName = $("#userName").val();    var password = $("#password").val();    $.ajax({        url:"auth/ajaxLogin",        type:"post",        dataType:'json',        //不使用contentType,data可以是对象,如果使用contentType,则data只能是字符串        //contentType:"application/json; charset=utf-8",        data:{userName: userName, password: password},        success:function(data){            var code = data.code;            if(code == 0){                location.href="index.jsp";            }else{                alert(data.msg);            }                    },        error:function(){                    }    });}//退出平台function logout(){    $.ajax({        url:"auth/ajaxLogout",        type:"post",        dataType:"json",        success:function(data){            var code = data.code;            location.href="login.jsp";        },        error:function(){                    }    });}

 

测试效果:

使用admin pwd登陆时可以看到管理员信息,而使用user01 pwd登陆,看不到管理员才能看到的信息

转载于:https://www.cnblogs.com/djoker/p/9055500.html

你可能感兴趣的文章
【Mood-20】滴滤咖啡做法 IT工程师加班必备 更健康的coffee 项目经理加班密鉴
查看>>
读《构建之法-软件工程》第四章有感
查看>>
使用 Printf via SWO/SWV 输出调试信息
查看>>
.net 分布式架构之分布式锁实现(转)
查看>>
Problem E: Automatic Editing
查看>>
SpringBoot 使用 MyBatis 分页插件 PageHelper 进行分页查询
查看>>
《DSP using MATLAB》Problem 6.17
查看>>
微信公众平台开发实战Java版之如何网页授权获取用户基本信息
查看>>
一周TDD小结
查看>>
sizeof与strlen的用法
查看>>
Linux 下常见目录及其功能
查看>>
开源框架中常用的php函数
查看>>
nginx 的提升多个小文件访问的性能模块
查看>>
set&map
查看>>
集合类总结
查看>>
4.AE中的缩放,书签
查看>>
给一次重新选择的机会_您还会选择程序员吗?
查看>>
Mysql MHA高可用集群架构
查看>>
心急的C小加
查看>>
编译原理 First,Follow,select集求法
查看>>