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

SpringBoot整合JDBC

配置

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

数据库Druid

  • 配置applicaiton.yaml文件
spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource


    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
    #则导入log4j 依赖就行
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: 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")
    @Bean
    public DataSource druidDataSource()
    {
        return new DruidDataSource();
    }
    //后台监控
    @Bean
    public 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/*.xml
    type-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 mapper
        PUBLIC "-//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 {

    @Autowired
    private 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 {
    @Override
    protected 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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值