SpringBoot整合JDBC

配置

  • application.yaml中配置
spring:datasource:username: 用户名password: 密码url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Driver
  • 在代码中通过DataSource自动注入
@Autowired

数据库Druid

  • 配置applicaiton.yaml文件
spring:datasource:username: rootpassword: rooturl: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourceinitialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入#如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity#则导入log4j 依赖就行filters: stat,wall,log4jmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  • 配置/config/DruidConfig.java
  • 在localhost:3306中可以访问到项目的sql访问情况,后台页面
package com.example.springbootdata.config;import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import javax.sql.DataSource;
import java.util.HashMap;@Configuration
public class DruidConfig {//注册数据源@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource druidDataSource(){return new DruidDataSource();}//后台监控@Beanpublic ServletRegistrationBean statViewServlet(){//定义访问后台的页面ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");HashMap<String,String> initParameters = new HashMap<>();//初始化用户和密码initParameters.put("loginUsername","admin");//后台登录的key是固定的,代码是死的initParameters.put("loginPassword","123456");initParameters.put("allow","");//允许所有人访问bean.setInitParameters(initParameters);return bean;}
}

整合Mybatis框架

  • 配置pom.xml,手动添加mybatis依赖(包含了mysql和jdbc的驱动)
<dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId><version>2.0.2</version>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId>
</dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope>
</dependency>
  • 添加application.yaml的配置
mybatis:mapper-locations: classpath:mapper/*.xmltype-aliases-package: --包名--
  • 创建/mapper/UserMapper接口以及pojo类User
@Mapper
@Repository
public interface UserMapper {List<User> queryUserList();User queryUser(int id);int addUser(User user);int updateUser(User user);int deleteUser(int id);
}
  • 编写/resources/mybatis/mapper/UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><!-- type是映射到pojo -->
<mapper namespace="com.example.springbootdata.Mapper.
AccountMapper"><select id="queryAccountList" resultType="Account">select * from user</select><insert id="addAccount" parameterType="Account">insert into user values(#{id},#{name},#{password},#{age})</insert><update id="updateAccount" parameterType="Account">update user set name = #{name},password = #{password} where id = #{id}</update><delete id="deleteAccount" parameterType="int">delete from user where id = #{id}</delete>
</mapper>
  • 编写UserController
@RestController
public class AccountController {@Autowiredprivate AccountMapper accountMapper;@GetMapping("/queryUserList")public List<Account> queryUserList(){List<Account> accounts = accountMapper.queryUserList();for(Account account:accounts){System.out.println(account);}return accounts;}@GetMapping("/addUser")public String addUser(){accountMapper.addUser(new Account(2,"李应红","123456",20));return "ok";}
}

Spring Security(认证和授权)

  • pox.xml中导入相关依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
  • 新建config/SecurityConfig.class
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {super.configure(http);}
}
  • 修改授权中的内容
@Override
protected void configure(HttpSecurity http) throws Exception {//请求授权的规则http.authorizeRequests()//允许用户访问的页面.antMatchers("/").permitAll().antMatchers("/level1/**").hasAnyRole("vip1").antMatchers("/level2/**").hasAnyRole("vip2").antMatchers("/level3/**").hasAnyRole("vip3");//没有权限默认登录页面,需要开始登录的页面//自定义前端用户名和密码name,同时设置路由映射// /login是框架默认的http.formLogin().loginPage("/toLogin").usernameParameter("自定义用户名name").passwordParameter("自定义密码name").loginProcessingUrl("/login");//注销功能,注销成功后跳转http.csrf().disable();http.logout().logoutSuccessUrl("/");}
  • 在前端页面使用对应方法
<a class="item" th:href="@{/toLogin}"><i class="address card icon"></i> 登录
</a>
<!--                注销-->
<a class="item" th:href="@{/logout}"><i class="address card icon"></i> 注销
</a>
  • 认证部分,注意修改密码的编码方式
//认证
//密码编码
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()).withUser("langzhizhen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3").and().withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3").and().withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
  • 根据用户是否登录显示不同的页面
//需要现在.html文件里声明扩展包来实现提示语法
//使用sec:autorize属性来判断
<html lang="en" xmlns:th="http://www.thymeleaf.org"xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<div sec:authorize="!isAuthenticated()"><!--未登录--><a class="item" th:href="@{/toLogin}"><i class="address card icon"></i> 登录</a>
</div><div sec:authorize="isAuthenticated()"><a class="item">用户名: <span sec:authentication="name"></span>角色:   <span sec:authentication="principal.authorities"></span></a>
</div>
<div sec:authorize="isAuthenticated()"><a class="item" th:href="@{/logout}"><i class="address card icon"></i> 注销</a>
</div>
  • 根据用户的权限来显示不同的页面
//只需要在该块元素中添加hasRole()判断是否有该特权
<div class="column" sec:authorize="hasRole('vip1')"></div>
  • 开启记住我功能和自定义首页和快捷显示不同页面的请求
//开启记住我功能
http.rememberMe().rememberMeParameter("remember");//直接传入id参数然后拼接字符串
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id")int id)
{return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id")int id)
{return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id")int id)
{return "views/level3/"+id;
}

SpringBoot学习笔记(三)用户登录、授权、认真、数据库整合框架相关推荐

  1. imos学习笔记二 用户登录c#

    用户登录 1 初始化sdk 2 加密密码 3 登录 4 定阅推送功能 5 注册推送信息处理的回调函数 6 用户注销   /// <summary>         /// 多用户登录方法 ...

  2. springboot学习笔记(三)使用JDBC以及整合spring data jpa

    spring boot JDBC的使用: 1.引入依赖 <dependency><groupId>mysql</groupId><artifactId> ...

  3. JavaWeb-综合案例(用户信息)-学习笔记02【登录功能】

    Java后端 学习路线 笔记汇总表[黑马程序员] JavaWeb-综合案例(用户信息)-学习笔记01[列表查询] JavaWeb-综合案例(用户信息)-学习笔记02[登录功能] JavaWeb-综合案 ...

  4. SpringBoot(学习笔记)

    SpringBoot学习笔记 从今天开始就进入微服务阶段 一些小问题 1.HelloWorld 1.1回顾什么是Spring 1.2什么是SpringBoot 1.3微服务架构 2.第一个Spring ...

  5. SpringBoot 学习笔记

    SpringBoot 学习笔记 文章目录 SpringBoot 学习笔记 1. SpringBoot简介 1.1 什么是Spring 1.2 Spring 是如何简化Java开发的 1.3 什么是 S ...

  6. Springboot学习笔记(二)Web开发

    前言: 学习B站UP主狂神说视频笔记整理视频链接 狂神笔记链接 上篇笔记链接-Springboot学习笔记(一)快速上手 Web开发 静态资源 在以往的SpringMVC中所有静态资源或者页面应该放在 ...

  7. J2EE学习笔记三:EJB基础概念和知识 收藏

    J2EE学习笔记三:EJB基础概念和知识 收藏 EJB正是J2EE的旗舰技术,因此俺直接跳到这一章来了,前面的几章都是讲Servlet和JSP以及JDBC的,俺都懂一些.那么EJB和通常我们所说的Ja ...

  8. SpringBoot学习笔记(3):静态资源处理

    SpringBoot学习笔记(3):静态资源处理 在web开发中,静态资源的访问是必不可少的,如:Html.图片.js.css 等资源的访问. Spring Boot 对静态资源访问提供了很好的支持, ...

  9. SpringBoot学习笔记(9)----SpringBoot中使用关系型数据库以及事务处理

    在实际的运用开发中,跟数据库之间的交互是必不可少的,SpringBoot也提供了两种跟数据库交互的方式. 1. 使用JdbcTemplate 在SpringBoot中提供了JdbcTemplate模板 ...

最新文章

  1. Vmware Tools安装之Ubuntu7.10问题解决--持续更新中
  2. python输出数据到excel-python实现数据导出到excel的示例
  3. 【干货】产品经理如何使用大数据构建用户画像
  4. python实例属性与类属性_Python中的类属性和实例属性引发的一个坑-续
  5. RTP之H264封包和解包
  6. SpringCloud服务安全连接
  7. linux命令怎么调wsdl,如何从命令行执行SOAP wsdl Web服务调用
  8. 编写一个程序解决选择问题。令k=N/2。
  9. 如何高效检查一个数组中是否包含某个值?
  10. winfrom 窗口起始位置为屏幕中央
  11. android通过代码设置铃声_让你的手机铃声与众不同 (附ios音乐dj)
  12. 收藏夹吃灰系列(五):解决Win10插入U盘不显示磁盘可用容量且打不开卡死问题 | 超级详细,建议收藏
  13. ubuntu(乌班图) 修改ip
  14. Java开发之消息队列
  15. 小度计算机笔记,开售告罄、口碑炸裂、高语音交互率的小度耳机,全新升级语音笔记...
  16. python游戏寻路_python模拟实现A*寻路算法
  17. PCB工程文件默认打开方式变成了SoildWorks,怎么改成AD默认打开
  18. 软件过程的价值观、原则以及实践——从敏捷说起
  19. python pdf删除图片_python-删除PDF空白页
  20. 贰零贰壹·陆·伍·|比赛|·|创客|:第二十届自治区青少年机器人竞赛心得总结

热门文章

  1. socket的send、recv阻塞设置阻塞超时时间
  2. ice-full与ice-lite
  3. 阻抗匹配选取50Ω的原因
  4. 【LEDE】树莓派上玩LEDE终极指南-90-挂卡
  5. linux视频编辑软件字幕,Linux下的视频字幕编辑
  6. 英语口语8000句-见面、分手时
  7. android 打开部分文件方法汇总整理
  8. BOM案例之图片移动
  9. 3D游戏与编程hw7——模型与动画
  10. Win10语音转为文字的快捷键