1.首先需要一个完整的springboot的项目,搭建过程可以参考我的另一篇博客:
地址:https://blog.csdn.net/qq_38669394/article/details/84232976
2先看一下我的项目目录,主要涉及到两个类:ShiroConfig 是shiro的配置类,CustomRealm 进行权限控制
3.项目亲测没有任何问题,觉得有用的小伙伴可以给个关注哦!
首先我们需要 用户表,角色表,权限表 ,用户角色表,角色权限表这五张表来实现我们项目的基本权限,看下图
1. user表是用户表,2,3,4数据是经过加密加盐的,密码就是用户名,盐值也是用户名,我在测试时会使用zhang用户
2.role表是角色表
3.permission表是权限表 权限我用的是getUser,getUp是我瞎造的
4.user_role是用户角色表,user_id 为2(zhang)是role_id为1(admin)
5.role_permission表是角色权限表 admin用户权限为1,2 (getUp,getUser)
下面我把数据库sql语句给出来
/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50717
Source Host : localhost:3306
Source Database : springboot
Target Server Type : MYSQL
Target Server Version : 50717
File Encoding : 65001
Date: 2018-11-21 17:47:58
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for permission
-- ----------------------------
DROP TABLE IF EXISTS `permission`;
CREATE TABLE `permission` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL COMMENT '菜单名称',
`url` varchar(256) DEFAULT NULL COMMENT '菜单URL',
`permission` varchar(500) DEFAULT NULL COMMENT '授权(多个用逗号分隔,如:user:list,user:create)',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=61 DEFAULT CHARSET=utf8mb4 COMMENT='菜单管理';
-- ----------------------------
-- Records of permission
-- ----------------------------
INSERT INTO `permission` VALUES ('1', '主页', '', 'getUp');
INSERT INTO `permission` VALUES ('2', '获取用户', '', 'getUser');
-- ----------------------------
-- Table structure for role
-- ----------------------------
DROP TABLE IF EXISTS `role`;
CREATE TABLE `role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL COMMENT '角色名称',
`remark` varchar(256) DEFAULT NULL COMMENT '备注',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='角色';
-- ----------------------------
-- Records of role
-- ----------------------------
INSERT INTO `role` VALUES ('1', 'admin', '管理员', null);
INSERT INTO `role` VALUES ('2', 'user', '普通用户', null);
INSERT INTO `role` VALUES ('3', 'vip', '会员', null);
-- ----------------------------
-- Table structure for role_permission
-- ----------------------------
DROP TABLE IF EXISTS `role_permission`;
CREATE TABLE `role_permission` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`role_id` bigint(20) NOT NULL COMMENT '角色ID',
`permission_id` bigint(20) NOT NULL COMMENT '菜单ID',
PRIMARY KEY (`id`),
KEY `role_id` (`role_id`),
KEY `menu_id` (`permission_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COMMENT='角色与菜单对应关系';
-- ----------------------------
-- Records of role_permission
-- ----------------------------
INSERT INTO `role_permission` VALUES ('1', '1', '1');
INSERT INTO `role_permission` VALUES ('2', '1', '2');
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`type` char(1) DEFAULT NULL,
`create_time` datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'admin', 'admin', '1', '2018-10-13 18:36:02');
INSERT INTO `user` VALUES ('2', 'zhang', '051757d33622c6638e25ba6273b6b1e5', '1', '2018-11-20 15:28:16');
INSERT INTO `user` VALUES ('3', 'zhao', 'cf40ec51b3027e24c6c309c0939119be', '1', '2018-11-20 15:28:18');
INSERT INTO `user` VALUES ('4', 'zhou', '36598b4bc66bfd95e27effd8ee1a8048', '1', '2018-11-20 15:28:20');
-- ----------------------------
-- Table structure for user_role
-- ----------------------------
DROP TABLE IF EXISTS `user_role`;
CREATE TABLE `user_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NOT NULL COMMENT '用户ID',
`role_id` bigint(20) NOT NULL COMMENT '角色ID',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`),
KEY `role_id` (`role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COMMENT='用户与角色对应关系';
-- ----------------------------
-- Records of user_role
-- ----------------------------
INSERT INTO `user_role` VALUES ('1', '2', '1');
INSERT INTO `user_role` VALUES ('4', '3', '2');
INSERT INTO `user_role` VALUES ('5', '3', '3');
INSERT INTO `user_role` VALUES ('6', '4', '2');
下面开始正式整合springboot 和shiro
6.引入jia包 ,只要在项目中引入
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
我的pom.xml文件,在我上一篇springboot项目搭建中已经有了,为了给大家省事,我就再粘贴一次
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zhangdi</groupId>
<artifactId>springboot</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency> -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mybaits -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!--shiro集成 -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
7.jar包引入之后编写最重要的两个类,首先是shiro配置类ShiroConfig.java,采用md5加密1024次,roles[admin] 角色控制,perms[getUser]权限控制,"roles[admin],perms[getUser]"角色权限都生效。可以根据需求,还可以在方法上使用注解的方式(未侧式)
package com.zhangdi.springboot.shiro;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.SecurityManager;
@Configuration
public class ShiroConfig {
@Bean
public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
// 必须设置 SecurityManager
shiroFilterFactoryBean.setSecurityManager( securityManager);
// setLoginUrl 如果不设置值,默认会自动寻找Web工程根目录下的"/login.jsp"页面 或 "/login" 映射
shiroFilterFactoryBean.setLoginUrl("/login");
// 设置无权限时跳转的 url;
//shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");
// 设置拦截器
Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
//静态资源释放
filterChainDefinitionMap.put("/images/**", "anon");
filterChainDefinitionMap.put("/lib/**", "anon");
filterChainDefinitionMap.put("/stylesheets/**", "anon");
//游客,开发权限
filterChainDefinitionMap.put("/guest/**", "anon");
//用户,需要角色权限 “user”
filterChainDefinitionMap.put("/user/**", "roles[user]"); //也可以 注解角色权限注入方法上 @RequiresRoles("admin")和@RequiresPermissions("create")
//管理员,需要角色权限 “admin”
// filterChainDefinitionMap.put("/getUser", "roles[admin]");
filterChainDefinitionMap.put("/getUser", "perms[getUser]");
//filterChainDefinitionMap.put("/getUser","roles[admin],perms[getUser]");
//开放登陆接口
filterChainDefinitionMap.put("/login", "anon");
filterChainDefinitionMap.put("/checkLogin", "anon");
//其余接口一律拦截
//主要这行代码必须放在所有权限设置的最后,不然会导致所有 url 都被拦截
filterChainDefinitionMap.put("/**", "authc");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
System.out.println("Shiro拦截器工厂类注入成功");
return shiroFilterFactoryBean;
}
/**
* 注入 securityManager
*/
@Bean
@DependsOn("credentialsMatcher")
public SecurityManager securityManager(CredentialsMatcher credentialsMatcher){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
securityManager.setRealm(customRealm(credentialsMatcher));
return securityManager;
}
/**
* 自定义身份认证 realm;
* <p>
* 必须写这个类,并加上 @Bean 注解,目的是注入 CustomRealm,
* 否则会影响 CustomRealm类 中其他类的依赖注入
*/
@Bean
public CustomRealm customRealm(CredentialsMatcher credentialsMatcher) {
CustomRealm customRealm = new CustomRealm();
//将自定义的令牌set到了Realm
customRealm.setCredentialsMatcher(credentialsMatcher);
return customRealm;
}
/**
* 密码匹配凭证管理器
*
* @return
*/
@Bean(name = "credentialsMatcher")
public HashedCredentialsMatcher hashedCredentialsMatcher() {
HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
// 采用MD5方式加密
hashedCredentialsMatcher.setHashAlgorithmName("MD5");
// 设置加密次数
hashedCredentialsMatcher.setHashIterations(1024);
return hashedCredentialsMatcher;
}
}
8.shiro权限实现类CustomRealm.java继承AuthorizingRealm主要实现两个方法,进行密码校验时,返回
return new SimpleAuthenticationInfo(user,credentials,salt,realmName);(第一个参数用户对象)与
return new SimpleAuthenticationInfo(principal,credentials,salt,realmName);(第一个参数用户名)都行,
为了验证角色,权限时方便获取用户id 我返回的user
package com.zhangdi.springboot.shiro;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.shiro.SecurityUtils;
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.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import com.zhangdi.springboot.domain.Permission;
import com.zhangdi.springboot.domain.Role;
import com.zhangdi.springboot.domain.User;
import com.zhangdi.springboot.service.UserService;
public class CustomRealm extends AuthorizingRealm {
private UserService userService;
@Autowired
private void UserService(UserService userService) {
this.userService = userService;
}
/**
* 获取授权信息
* ao si ra yi zai shen 授权认证
* @param principalCollection
* @return
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
// TODO Auto-generated method stub
System.out.println("————权限认证————");
User user = (User) SecurityUtils.getSubject().getPrincipal();
// User user = userService.getUser(username);
List<Role> roleList = userService.getUserRole(user.getId());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
for(Role role : roleList) {
info.addRole(role.getName());
List<Permission> permissionList = userService.getUserPermission(role.getId());
for(Permission permission : permissionList) {
info.addStringPermission(permission.getPermission());
}
}
return info;
}
/**
* 获取身份验证信息
* Shiro中,最终是通过 Realm 来获取应用程序中的用户、角色及权限信息的。
* ao san ti kai shen 登陆认证
* @param authenticationToken 用户身份信息 token
* @return 返回封装了用户信息的 AuthenticationInfo 实例
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
// 将token装换成UsernamePasswordToken
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
// 获取用户名即可
String username = token.getUsername();
// 从数据库获取对应用户名的用户
User user = userService.getUser(username);
if (null == user) {
throw new UnknownAccountException("用户不存在!");
}else {
Object principal = username;
// (2)credentials:密码
Object credentials = user.getPassword();
// 获取盐值,即用户名
ByteSource salt = ByteSource.Util.bytes(username);
String realmName = this.getName();
// 若存在,将此用户存放到登录认证info中,无需自己做密码对比,Shiro会为我们进行密码对比校验
return new SimpleAuthenticationInfo(user,credentials,salt,realmName);
}
}
}
9.为了完成以上操作,我们需要实现四个方法,第一个 插入用户到数据库,MD5加密1024次用户名作为盐值,第二个,根据用户名查询用户信息,第三个根据用户id查询用户角色,第四个根据用户角色id查询用户权限。UserMapper.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zhangdi.springboot.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.zhangdi.springboot.domain.User">
<result column="id" property="id" jdbcType="INTEGER"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="password" property="password" jdbcType="VARCHAR"/>
<result column="create_time" property="createTime" jdbcType="VARCHAR"/>
</resultMap>
<resultMap id="RoleResultMap" type="com.zhangdi.springboot.domain.Role">
<result column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="remark" property="remark" jdbcType="VARCHAR"/>
<result column="create_time" property="createTime" jdbcType="VARCHAR"/>
</resultMap>
<resultMap id="PermissionResultMap" type="com.zhangdi.springboot.domain.Permission">
<result column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="permission" property="permission" jdbcType="VARCHAR"/>
<result column="url" property="url" jdbcType="VARCHAR"/>
</resultMap>
<select id="selectUser" resultMap="BaseResultMap" parameterType="string">
SELECT * FROM user
WHERE username = #{username}
</select>
<insert id="insertUser" parameterType="com.zhangdi.springboot.domain.User">
INSERT INTO user ( username,password,type,create_time)
VALUES (#{username, jdbcType=VARCHAR},#{password, jdbcType=VARCHAR},
#{type, jdbcType=VARCHAR},#{createTime, jdbcType=VARCHAR});
</insert>
<select id="selectRoleByUserId" resultMap="RoleResultMap" parameterType="integer">
select role_id id,r.name,r.remark,r.create_time
FROM user_role u LEFT JOIN role r
ON u.role_id = r.id
WHERE u.user_id = #{userId}
</select>
<select id="selectPermissionByRoleId" resultMap="PermissionResultMap" parameterType="integer">
SELECT p.id,p.`name`,p.permission,p.url
FROM role_permission r LEFT JOIN permission p
ON r.permission_id = p.id
WHERE r.role_id = #{roleId}
</select>
</mapper>
11. dao层代码我就不粘贴整个Java文件了只粘贴方法
User selectUser(@Param("username") String username);
int insertUser(User user);
List<Role> selectRoleByUserId(@Param("userId") int userId);
List<Permission> selectPermissionByRoleId(@Param("roleId") int roleId);
12. service层
public User getUser(String username);
public boolean registerUser(User user);
List<Role> getUserRole( int userId);
List<Permission> getUserPermission( int roleId);
13.service实现层我只粘贴插入加盐加密的代码:
@Override
public boolean registerUser(User user) {
// 将用户名作为盐值
String username = user.getUsername();
ByteSource salt = ByteSource.Util.bytes(username);
/*
* MD5加密:
* 使用SimpleHash类对原始密码进行加密。
* 第一个参数代表使用MD5方式加密
* 第二个参数为原始密码
* 第三个参数为盐值,即用户名
* 第四个参数为加密次数
* 最后用toHex()方法将加密后的密码转成String
* */
String newPassword = new SimpleHash("MD5", user.getPassword(), salt, 1024).toHex();
User userInfo = userMapper.selectUser(username);
if(userInfo==null) {
user.setPassword(newPassword);
int i = userMapper.insertUser(user);
if(i>0) {
return true;
}
}
return false;
}
14.三个实体对象,User.java之前代码链接已经存在
Role.java : private int id; private String name; private String remark; private String createTime;四个字段
Permission.java : private int id; private String name; private String permission; private String url;四个字段
15.UserController前面链接代码中有,LoginController代码:
package com.zhangdi.springboot.controller;
import java.util.HashMap;
import java.util.Map;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zhangdi.springboot.domain.User;
@Controller
public class LoginController {
/**
* 登陆
*
* @param username 用户名
* @param password 密码
*/
@RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> loginIndex(@RequestBody User user) {
String username = user.getUsername();
String password = user.getPassword();
// 在认证提交前准备 token(令牌)
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 从SecurityUtils里边创建一个 subject
Subject subject = SecurityUtils.getSubject();
if (!subject.isAuthenticated()){
//使用shiro来验证
// token.setRememberMe(true);
try {
subject.login(token);//验证角色和权限
} catch ( UnknownAccountException e ) {
System.out.println("用户未注册!");
}catch ( IncorrectCredentialsException e ) {
System.out.println("密码错误!!");
}catch ( LockedAccountException e ) {
System.out.println("该账户不可用~");
} catch ( ExcessiveAttemptsException e ) {
System.out.println("尝试次数超限!!");
}
}
Map<String,Object> resultMap = new HashMap<String,Object>();
resultMap.put("success", true);
return resultMap;
}
}
login.html页面:css,和jquery.js 没有引入。自行修改
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap Admin</title>
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="stylesheet" type="text/css" href="lib/bootstrap/css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="stylesheets/theme.css">
<link rel="stylesheet" href="lib/font-awesome/css/font-awesome.css">
<script src="lib/jquery-1.7.2.min.js" type="text/javascript"></script>
<!-- Demo page code -->
<style type="text/css">
#line-chart {
height:300px;
width:800px;
margin: 0px auto;
margin-top: 1em;
}
.brand { font-family: georgia, serif; }
.brand .first {
color: #ccc;
font-style: italic;
}
.brand .second {
color: #fff;
font-weight: bold;
}
</style>
<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="../assets/ico/favicon.ico">
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="../assets/ico/apple-touch-icon-57-precomposed.png">
</head>
<!--[if lt IE 7 ]> <body class="ie ie6"> <![endif]-->
<!--[if IE 7 ]> <body class="ie ie7 "> <![endif]-->
<!--[if IE 8 ]> <body class="ie ie8 "> <![endif]-->
<!--[if IE 9 ]> <body class="ie ie9 "> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!-->
<body class="">
<!--<![endif]-->
<div class="navbar">
<div class="navbar-inner">
<ul class="nav pull-right">
</ul>
<a class="brand" href="index.html"><span class="first">Your</span> <span class="second">Company</span></a>
</div>
</div>
<div class="row-fluid">
<div class="dialog">
<div class="block">
<p class="block-heading">登陆</p>
<div class="block-body">
<form>
<label>用户名</label>
<input type="text" class="span12" id="username">
<label>密码</label>
<input type="password" class="span12" id="password">
<a id="login" class="btn btn-primary pull-right">登陆</a>
<label class="remember-me"><input type="checkbox"> Remember me</label>
<div class="clearfix"></div>
</form>
</div>
</div>
<!-- <p class="pull-right" style=""><a href="#" target="blank">Theme by Portnine</a></p>
<p><a href="reset-password.html">Forgot your password?</a></p> -->
</div>
</div>
<script src="lib/bootstrap/js/bootstrap.js"></script>
<script type="text/javascript">
$("[rel=tooltip]").tooltip();
$(function() {
/* $('.demo-cancel-click').click(function(){return false;}); */
$("body").keydown(function(event) {
if (event.keyCode == "13") {//keyCode=13是回车键
$("#login").click();
}
});
$("#login").on('click',function() {
var jsr ='{"id":"","username":"","password":"","type":"","crateTime":""}';
jsr = JSON.parse(jsr);
jsr.username=$("#username").val();
jsr.password=$("#password").val();
jsr = JSON.stringify(jsr);
console.log(jsr)
$.ajax({
type :"POST",
url : "http://localhost:8080/checkLogin",
dataType : "json",
contentType : "application/json",
data :jsr,
success : function(data) {
if(data.success){
window.location.href='http://localhost:8080/index'
}else{
alert("用户名或密码错误")
}
},
error: function(error) {
}
});
})
});
</script>
</body>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bootstrap Admin</title>
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
</head>
<body class="">
Index.html
</body>
</html>
16.代码已经贴完了,下面开始启动测试
启动后页面输入http://localhost:8080/getUser?username=zhang
会跳转到登陆页面
点击登陆:
跳转的主页
登陆后,当我们数据库中没有给zhang用户getUser权限时 访问http://localhost:8080/getUser?username=zhang
当我们数据库给getUser权限时,获得到数据
根据上面三种配置测试都成功了
至此,springboot整合shiro已经完成了,有需要源码的可以留言发送给你们,感觉赞的点下关注不迷路。