3-8 基于SpringBoot连接数据库与配置MyBatis实操 创建表sql

11                    13-8 基于SpringBoot连接数据库与配置MyBatis实操

springSecurity提供了     现成的基于内存管理的类     

shiro则必须自己设计这样的类      需要自己设计用户权限这样的体系

这里基于RBAC简单的设计一套

 

 

 

 

-- 权限表 --
CREATE TABLE permission (pid int(11) NOT NULL AUTO_INCREMENT,name VARCHAR(255) NOT NULL DEFAULT '',url VARCHAR(255) DEFAULT '',PRIMARY KEY (pid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;INSERT INTO permission VALUES ('1', 'add', '');
INSERT INTO permission VALUES ('2', 'delete', '');
INSERT INTO permission VALUES ('3', 'edit', '');
INSERT INTO permission VALUES ('4', 'query', '');-- 用户表 --
CREATE TABLE user(uid int(11) NOT NULL AUTO_INCREMENT,username VARCHAR(255) NOT NULL DEFAULT '',password VARCHAR(255) NOT NULL DEFAULT '',PRIMARY KEY (uid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;INSERT INTO user VALUES ('1', 'admin', '123');
INSERT INTO user VALUES ('2', 'demo', '123');-- 角色表 --
CREATE TABLE role(rid int(11) NOT NULL AUTO_INCREMENT,rname VARCHAR(255) NOT NULL DEFAULT '',PRIMARY KEY (rid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;INSERT INTO role VALUES ('1', 'admin');
INSERT INTO role VALUES ('2', 'customer');-- 权限角色关系表 --
CREATE TABLE permission_role (rid int(11) NOT NULL ,pid int(11) NOT NULL ,KEY idx_rid (rid),KEY idx_pid (pid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;INSERT INTO permission_role VALUES ('1', '1');
INSERT INTO permission_role VALUES ('1', '2');
INSERT INTO permission_role VALUES ('1', '3');
INSERT INTO permission_role VALUES ('1', '4');
INSERT INTO permission_role VALUES ('2', '1');
INSERT INTO permission_role VALUES ('2', '4');-- 用户角色关系表 --
CREATE TABLE user_role (uid int(11) NOT NULL ,rid int(11) NOT NULL ,KEY idx_uid (uid),KEY idx_rid (rid)
) ENGINE = InnoDB DEFAULT CHARSET = utf8;INSERT INTO user_role VALUES (1, 1);
INSERT INTO user_role VALUES (2, 2);

 

//mapper的配置

1.扫描mapper的路径

2.使用spring要告诉它扫描相关的注解

现在写几个case     需要些几个realm     shiro的授权和登录     需要实现相关的认证和授权    核心是自定义的realm

 

 

 

********************************************************************************************************************************************

 

package com.mmall.demo2;import com.mmall.demo2.model.Permission;
import com.mmall.demo2.model.Role;
import com.mmall.demo2.model.User;
import com.mmall.demo2.service.UserService;
import org.apache.commons.collections.CollectionUtils;
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.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;import java.util.ArrayList;
import java.util.List;
import java.util.Set;//需要实现  AuthorizingRealm
public class AuthRealm extends AuthorizingRealm {//需要注入user的serviece@Autowiredprivate UserService userService;// 2、授权@Overrideprotected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {//授权是在验证登录成功之后进行的   在认证登录之后我们会将user这个对象放到session 中//s所以我们先从session 中取出这个对象//通过这个方法可以取出session 中的对象     相当于从session中获取用户User user = (User) principals.fromRealm(this.getClass().getName()).iterator().next();List<String> permissionList = new ArrayList<>();//一个角色有多个权限List<String> roleNameList = new ArrayList<>();//一个用户有多个角色Set<Role> roleSet = user.getRoles();//用户所有的角色if (CollectionUtils.isNotEmpty(roleSet)) {//用户的角色不为空  遍历用户所有的角色//这里只有一个循环  不是2个循环 看清楚了for(Role role : roleSet) {// 角色roleNameList.add(role.getRname());//存储用户名下的角色名称Set<Permission> permissionSet = role.getPermissions();//角色有可能重复权限这里使用set 可以去重复if (CollectionUtils.isNotEmpty(permissionSet)) {//如果该角色下面有权限for (Permission permission : permissionSet) {permissionList.add(permission.getName());//每个角色的权限 都加进去  set可以去重复}}}}SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();info.addStringPermissions(permissionList);info.addRoles(roleNameList);return info;}// 1、首先先写   认证登录@Overrideprotected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException    {//首先先写   传入的token  转换为 UsernamePasswordToken    强行转换就可以了UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;String username = usernamePasswordToken.getUsername();User user = userService.findByUsername(username);//获取用户// 完成了认证登录的部分    参数       用户对象      认证器就是密码             当前类名return new SimpleAuthenticationInfo(user, user.getPassword(), this.getClass().getName());// 上面是转换为AuthenticationInfo这个对象         1、这就完成认证登录功能     2、接下来写授权}//上面  1,2 完成  就需要 校验user.getPassword(),是否是我们要求的规则  实现一个接口传入即可//CredentialMatcher  //public class CredentialMatcher extends SimpleCredentialsMatcher {}******************************************************************************************************
package com.mmall.demo2;import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.SimpleCredentialsMatcher;public class CredentialMatcher extends SimpleCredentialsMatcher {// 完成了简单的密码校验的重写@Overridepublic boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {//首先token强转UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;//强转后获取password   得到是数组强转String   这个是user对象中的password字段String password = new String(usernamePasswordToken.getPassword());//获取数据库密码   其实就是我们刚刚传入的值String dbPassword = (String) info.getCredentials();//强转//验证规则  自己定义就好了   这里就写是否相等就好了return this.equals(password, dbPassword);}//完成 shiro的认证和授权    和密码校验规则之后//我们需要将他们注入到我们这个shiro的配置中//public class ShiroConfiguration {
}

******************************************************************************************************

 

package com.mmall.demo2;import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.LinkedHashMap;//这个类是shrio的核心配置
//在springboot中用@Configuration  作为标识   在项目启动时自动配置这个类
@Configuration
public class ShiroConfiguration {//1、首先写密码和自定义规则   定义自己的类@Bean("credentialMatcher")public CredentialMatcher credentialMatcher() {return new CredentialMatcher();//直接声明这个实例即可   拿到这个bean就可以拿到校验规则}//2.自定义authRealm 完成@Bean("authRealm")                 // 用上下文的bean   这里从spring中取出来 就上bean的名字public AuthRealm authRealm(@Qualifier("credentialMatcher") CredentialMatcher matcher) {AuthRealm authRealm = new AuthRealm();//定义real的实例authRealm.setCacheManager(new MemoryConstrainedCacheManager());authRealm.setCredentialsMatcher(matcher);//实例中给出自己的密码比较器return authRealm;}//3、realm的上一层是securityManager     注入的是上一步中的realm@Bean("securityManager")public SecurityManager securityManager(@Qualifier("authRealm") AuthRealm authRealm) {//这里使用DefaultWebSecurityManagerDefaultWebSecurityManager manager = new DefaultWebSecurityManager();//把第二步定义的authRealm放进去manager.setRealm(authRealm);return manager;}//4.shiroFilter   注入上一步的securityManager   这里返回值是ShiroFilter的工厂Bean@Bean("shiroFilter")public ShiroFilterFactoryBean shiroFilter(@Qualifier("securityManager") SecurityManager manager) {//首先声明实例   把securityManager 先注入进去ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();bean.setSecurityManager(manager);//定义登录的urlbean.setLoginUrl("/login");//定义登录成功后跳转的urlbean.setSuccessUrl("/index");//定义没有权限访问的urlbean.setUnauthorizedUrl("/unauthorized");//定义最核心的 某系请求怎么拦截      定义权限配置LinkedHashMap<String, String> filterChainDefinitionMap = new LinkedHashMap<>();//第一个参数是我们访问的请求   第二个参数是我们使用的是什么样的拦截器filterChainDefinitionMap.put("/index", "authc");//主页必须登录  authcfilterChainDefinitionMap.put("/login", "anon");//登录不用校验filterChainDefinitionMap.put("/loginUser", "anon");filterChainDefinitionMap.put("/admin", "roles[admin]");filterChainDefinitionMap.put("/edit", "perms[edit]");filterChainDefinitionMap.put("/druid/**", "anon");filterChainDefinitionMap.put("/**", "user");bean.setFilterChainDefinitionMap(filterChainDefinitionMap);//设置进filter//authc是什么含义??  含义是前面的url使用authc的拦截器进行验证//在enum DefaultFilter中//常用的就这几个return bean;}//  这样当项目启动的时候  shirofiler首先初始化  会依次初始化下去//  一层一层的就会初始化下去////下面的2个类  使得shiro和spring关联是我们自己定制的//配置一下shiro和spring之间的几个类    参数传入securityManager@Beanpublic AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") SecurityManager securityManager) {//给一个实例AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();//设置securityManageradvisor.setSecurityManager(securityManager);return advisor;//这样spring对securityManager使用就是我们自定义的securityManager}//z这个不用配置  只要出入shrio的管理就好了@Beanpublic DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();creator.setProxyTargetClass(true);//默认是falsereturn creator;}//shrio的整个流程全部讲解完毕了
}

 

 

 

 

 

******************************************************************************************************

## database ##
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=root## mybatis ##
#  mybatis.xml文件的位置
mybatis.mapper-locations=mappers/*.xml
#  mybatis使用到的实体类pojo对象   都放到这个包下面
mybatis.type-aliases-package=com.mmall.demo2.model## jsp ##    定义页面的位置   jsp放置在pages目录下面
spring.mvc.view.prefix=/pages/
spring.mvc.view.suffix=.jsp

******************************************************************************************************

在main文件夹中新加webapp文件夹,springboot默认将页面放在webapp下面   我们配置了jsp前缀为pages文件夹下面

 

******************************************************************************************************

 

package com.mmall.demo2;import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;import javax.sql.DataSource;//@Configuration  加上这个注解在项目启动时就配置
@Configuration
public class DruidConfiguration {@Beanpublic ServletRegistrationBean statViewServlet() {ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");//白名单:     设置允许访问的beanservletRegistrationBean.addInitParameter("allow", "127.0.0.1");//设置不允许访问的ip//IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的即提示:Sorry, you are not permitted to view this page.servletRegistrationBean.addInitParameter("deny", "192.168.1.100");//登录查看信息的账号密码.          查看druid登录信息的用户名和密码servletRegistrationBean.addInitParameter("loginUsername", "druid");servletRegistrationBean.addInitParameter("loginPassword", "12345678");//是否能够重置数据.servletRegistrationBean.addInitParameter("resetEnable", "false");return servletRegistrationBean;}@Beanpublic FilterRegistrationBean statFilter() {FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());//添加过滤规则.      拦截那些请求filterRegistrationBean.addUrlPatterns("/*");//添加不需要忽略的格式信息.     过滤那些请求filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");return filterRegistrationBean;}@BeanPersistenceExceptionTranslationPostProcessor persistenceExceptionTranslationPostProcessor() {return new PersistenceExceptionTranslationPostProcessor();}//配置数据库的基本链接信息   信息也是是从application.properties文件中读取@Bean(name = "dataSource")@Primary@ConfigurationProperties(prefix = "spring.datasource")    //可以在application.properties中直接导入public DataSource dataSource() {return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();}@Beanpublic SqlSessionFactoryBean sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception {SqlSessionFactoryBean bean = new SqlSessionFactoryBean();bean.setDataSource(dataSource);PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();//最后指定mapper文件  有了这些就可以轻松的监控数据库的请求bean.setMapperLocations(resolver.getResources("classpath:/mappers/*.xml"));return bean;}
}
//访问http://localhost:8080/druid/index.html   用户名是上定义的druid 12345678
//可以对数据库进行监控

 

 

 

 

阿里的druid数据源监控

******************************************************************************************************

代码已经上传gitee

git@gitee.com:yjb1091947832/demo2druid.git

这节课内容不少  建议大家多看几遍 ---   视频老师

 

 

******************************************************************************************************

 

 

 

 

******************************************************************************************************

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

 

******************************************************************************************************

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/328103.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

struts基本概念(1)

model1:1,纯jsp2.jspjavabeanmodel2&#xff1a;MVC: jspservletjavabean m:model (模型)封装数据&#xff0c;业务处理类 &#xff0c;返回处理结果v:view(视图)展示数据c&#xff1a;cotroller&#xff08;控制器&#xff09;处理请求&#xff0c;模型和视图之间进行转换DTD…

使用 RxJS 实现 JavaScript 的 Reactive 编程

简介 作为有经验的JavaScript开发者&#xff0c;我们会在代码中采用一定程度的异步代码。我们不断地处理用户的输入请求&#xff0c;也从远程获取数据&#xff0c;或者同时运行耗时的计算任务&#xff0c;所有这些都不能让浏览器崩溃。可以说&#xff0c;这些都不是琐碎的任务&…

vue组件自定义v-model

转载自 vue组件&#xff0c;自定义v-model方法1<my-component v-model"obj"></my-component>在使用my-component组件时&#xff0c;为了实现双向绑定。1234567891011121314Vue.component(my-component, {props: {obj: Object,},model: {prop: obj,event…

权限管理系统

11 已经有现成的spring Security 和 Apache shiro 为什么还要开发自己的一套权限管理系统 1.必须按照框架的要求进行配置&#xff0c;会被框架限制&#xff0c;差一点点就转不起来&#xff0c;犯一点点错误都不行&#xff0c; 2.没有界面操作&#xff0c;和查看&#xf…

vue watch监听对象

一、watch的API vm.$watch( expOrFn, callback, [options] ) 参数&#xff1a; {string | Function} expOrFn{Function | Object} callback{Object} [options] {boolean} deep{boolean} immediate 返回值&#xff1a;{Function} unwatch 用法&#xff1a; 观察 Vue 实例变化的…

从.NET和Java之争谈IT这个行业

一、有些事情难以回头 开篇我得表名自己的立场:.NET JAVA同时使用者,但更加偏爱.NET.原因很简单 1.NET语言更具开放性,从开源协议和规范可以看出; 2.语言更具优势严谨; 3.开发工具VS更具生产力; 然而 1.Java,C#的职位比率在4:1,虽然这不是什么问题,因为求职竞争的比例更大(JAVA…

权限管理系统2_权限表,权限模块表

CREATE TABLE sys_acl_module ( id int(11) NOT NULL AUTO_INCREMENT COMMENT 权限模块id, name varchar(20) NOT NULL DEFAULT COMMENT 权限模块名称, parent_id int(11) NOT NULL DEFAULT 0 COMMENT 上级权限模块id, level varchar(200) NOT NULL DEFAULT COMMENT …

struts基本概念(2)

一、struts使用步骤&#xff1a;1.导包&#xff08;基本&#xff09;2.web.xml配置struts控制器 C3.页面开发 V4.处理类开发 M()5.配置struts.xml 6.部署运行二、struts访问session(servlet )1.解耦方式:ActionContext Map 2.耦合方式:ServletActionContextHttpSession 三…

vue2.0 $router和$route的区别

转载自 vue2.0 $router和$route的区别在vue2.0里页面参数是 this.$route.query或者 this.$route.params 接收router-link传的参数。 在路由跳转的时候除了用router-link标签以外需要在script标签在事件里面跳转&#xff0c;所以有个方法就是在script标签里面写this.$router.pu…

基于Bootstrap 3.x的免费高级管理控制面板主题:AdminLTE

AdminLTE 是一个基于Bootstrap 3.x的免费高级管理控制面板主题。AdminLTE - 是一个完全响应式管理模板。基于Bootstrap3框架。高度可定制的&#xff0c;易于使用。适合从小型移动设备到大型台式机很多的屏幕分辨率。 在线预览: http://almsaeedstudio.com/preview/ AdminLTE 在…

Spring MVC开发环境搭建

现在springMVC是非常常用的框架&#xff0c;很多公司的内部都是使用这个框架 打开maven查询jar包的网址 mvnrepository.com 测试是否成功 war:只是运行 war expord: 运行且调试

Redola.Rpc 的一个小目标:20000 tps

Redola.Rpc 的一个小目标 Redola.Rpc 的一个小目标&#xff1a;20000 tps。 Concurrency level: 8 threadsComplete requests: 20000 Time taken for tests: 0.886 secondsTime per request: 0.044 ms (avg)Requests per second: 22573 [#/sec] (avg) Concurrency level: 8 thr…

vue 动态修改路由参数

转载自 vue 动态修改路由参数 import merge from webpack-merge&#xff1b;修改原有参数 this.$router.push({query:merge(this.$route.query,{maxPrice:630}) })新增一个参数&#xff1a; this.$router.push({query:merge(this.$route.query,{addParams:我是新增的一…

2016年寒假心得

对于上学的孩子来说每年都有寒假&#xff0c;可是一样的寒假总是不一样的玩法。自从高中毕业之后&#xff0c;很少动笔写文了&#xff0c;这次就好好的写一下吧&#xff01;咱的文笔也不是很好&#xff0c;就写个最简单的流水状大家凑合的看看吧&#xff01;&#xff01;&#…

Vue.js 定义组件模板的七种方式

转载自 Vue.js 定义组件模板的七种方式在 Vue 中定义一个组件模板&#xff0c;至少有七种不同的方式&#xff08;或许还有其它我不知道的方式&#xff09;&#xff1a; 字符串模板字面量x-template内联模板render 函数JSF单文件组件 在这篇文章中&#xff0c;我将通过示例介绍…

.Net Core上用于代替System.Drawing的类库

目前.Net Core上没有System.Drawing这个类库&#xff0c;想要在.Net Core上处理图片得另辟蹊径。 微软给出了将来取代System.Drawing的方案&#xff0c;偏向于使用一个单独的服务端进行各种图片处理https://github.com/dotnet/corefx/issues/2020https://github.com/imazen/Gra…

16-1 Redis分布式缓存引入与保存缓存功能实现

16-1 Redis分布式缓存引入与保存缓存功能实现 现在功能已经完成了&#xff0c;但是我们还是要考虑一下性能问题&#xff0c;现在任何请求都是要到数据库中查询很多的数据&#xff0c;才能知道当前的用户是否有权限可以访问当前的url&#xff0c;当我们的请求量很大时&#xff…

oracle基本笔记整理

oracle&#xff0c;简单来说就是数据库&#xff0c;数据库 &#xff0c;顾名思义&#xff0c;就是存放数据的容器&#xff01;&#xff01; 不知道oracle的我先科普一下吧~~~科普&#xff0c;科学普及简称科普&#xff0c;又称大众科学或者普及科学&#xff0c;是指利用各种传…

不同范数下的余弦定理_第06题 | 从源头追溯「余弦定理」amp; 文理科知识点的异同...

文、理科数学大部分知识点、甚至相关知识点的考查形式都是共同的&#xff0c;甚至往年理科题目过几年就会出现在文科试卷上&#xff0c;反之亦然&#xff1b;「射影定理」是「余弦定理」的直接来源&#xff0c;所以不算超纲知识点。先发福利&#xff1a;这里有6场「高考数学」系…