SpringBoot2.0整合SpringSecurity,Mybatis,Layui框架从零开始实现登入登陆的增删查改

╄→尐↘猪︶ㄣ 提交于 2020-08-13 13:24:48

一、工具说明

    开发工具:idea2019

    jdk版本:1.8

    数据库: Mysql5.0+

二、项目说明

    基于springboot2.0,整合druid, jpa , thymeleaf,layui,mybatis,maven,springsecurity框架实现登入登出的管理系统。

三、项目搭建

1、快速搭建maven项目

(1)点击左侧Maven,选择Jdk1.8,选中 Create from archetype,点击next。

(2)填写项目信息,点击next

(3)选择项目位置,点击finish。

(4)项目结构图如下:

2、引入相关依赖

    <!-- springboot 2.0.9 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.9.RELEASE</version>
    </parent>
    <dependencies>
        <!--springboot -web 组件,整合 springmvc,spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <!--引入springthymeleaf -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- springboot 整合mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.25</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.16</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.22</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
            <scope>compile</scope>
        </dependency>
        <!--alibaba-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.24</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.30</version>
        </dependency>
        <dependency>
            <groupId>com.xiaoleilu</groupId>
            <artifactId>hutool-all</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.6</version>
        </dependency>
        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.4</version>
        </dependency>
    </dependencies>

3.配置相关参数

server:
  port: 8090
  tomcat:
    uri-encoding: UTF-8

spring:
  http:
    encoding:
      force: true
      ### 模板引擎编码为UTF-8
      charset: UTF-8
    thymeleaf:
      prefix: classpath:/templates
      suffix: .html
      mode: HTML5
      encoding: UTF-8
      content-type: text/html
    # 关闭缓存, 即时刷新, 上线生产环境需要改为true
      cache: false
  datasource:
    # 连接池配置
    url: jdbc:mysql://127.0.0.1::3306/test?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai
    username: root
    password: mysql
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    # 初始化大小,最小,最大
    initial-size: 5
    min-idle: 5
    max-active: 20
    # 配置获取连接等待超时的时间
    max-wait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位毫秒
    time-between-eviction-runs-millis: 60000
    # 配置一个连接在池中最小生存时间
    min-evictable-idle-time-millis: 300000
    validation-query: SELECT 1 FROM sys_user
    test-while-idle: true
    test-on-borrow: false
    test-on-return: false
    # 打开 PSCache,并且指定每个连接上 PSCache 的大小
    pool-prepared-statements: true
    max-pool-prepared-statement-per-connection-size: 20
    #开启页面访问
    stat-view-servlet:
      enable: true
    # 配置监控统计拦截的 Filter,去掉后监控界面 SQL 无法统计,wall 用于防火墙
    filters: stat,wall,log4j
    # 通过 connection-properties 属性打开 mergeSql 功能;慢 SQL 记录
    connection-properties: druid.stat.mergeSql\=true;druid.stat.slowSqlMillis\=5000
    # 配置 DruidStatFilter
    web-stat-filter:
      enabled: true
      url-pattern: /*
      exclusions: .js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*

# mybatis配置
mybatis:
  mapper-locations: classpath:/mapper/**/*.xml
  configuration:
    jdbc-type-for-null: null
  type-aliases-package: cn.com.liu.model
# 日志打印级别,设为 debug可打印出 SQL
logging:
  level:
    cn:
      com:
        liu:
            mapper: debug

app:
  #AOP记录用户操作日志,true开启,false关闭
  open-aop-log: false

4、添加配置类

(1)WebMvcConfig 把静态资源文件加载进去。

package cn.com.liu.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");

    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        // 1.需要先定义一个convert 转换消息的对象
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2.添加fastJson的配置信息,比如,是否需要格式化返回的json数据
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        // 空值特别处理
        // WriteNullListAsEmpty 将Collection类型字段的字段空值输出为[]
        // WriteNullStringAsEmpty 将字符串类型字段的空值输出为空字符串 ""
        // WriteNullNumberAsZero 将数值类型字段的空值输出为0
        // WriteNullBooleanAsFalse 将Boolean类型字段的空值输出为false
        fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNonStringKeyAsString);
        // 处理中文乱码问题
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        // 3.在convert中添加配置信息
        fastConverter.setFastJsonConfig(fastJsonConfig);
        // 4.将convert添加到converters当中
        converters.add(fastConverter);
    }
}

(2)WebSecurityConfig  配置springsecurity

package cn.com.liu.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.util.matcher.RegexRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Pattern;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        http.authorizeRequests().antMatchers("/").permitAll()
                .antMatchers("/hello").hasRole("USER").and()
                //.csrf().disable() //关闭CSRF
                .csrf().requireCsrfProtectionMatcher(new RequestMatcher() {
                //放行这几种请求
                private Pattern allowedMethods = Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$");
                //放行rest请求
                private RegexRequestMatcher unprotectedMatcher = new RegexRequestMatcher("^/manage/.*", null);
                    @Override
                    public boolean matches(HttpServletRequest request) {
                        if(allowedMethods.matcher(request.getMethod()).matches()){
                            return false;
                        }
                        String servletPath = request.getServletPath();
                        if (servletPath.contains("/druid")) {
                            return false;
                        }
                        return !unprotectedMatcher.matches(request);
                    }
                }).and()
                    .formLogin().loginPage("/login").defaultSuccessUrl("/manage").and()
                    .logout().logoutUrl("/logout").logoutSuccessUrl("/login");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }


}

(3)配置druid监控

package cn.com.liu.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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 javax.sql.DataSource;
@Configuration
public class DruidConfiguration {
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP白名单
        //servletRegistrationBean.addInitParameter("allow", "192.168.*");
        // IP黑名单(共同存在时,deny优先于allow)
        //dservletRegistrationBean.addInitParameter("deny", "192.168.1.100");
        //控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "user");
        servletRegistrationBean.addInitParameter("loginPassword", "user");
        //是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }


}

5、启动项目

访问 http://localhost:8090/druid/index.html  即可看到监控日志信息, springsecurity登录账号密码为user/ 密码即为上述配置文件中的 user/user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!