springboot整合mybatis配置以及杂七杂八设置(给自己参考)

application.properties

#阿里巴巴数据连接池
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#初始容量
spring.datasource.druid.initial-size=20
#最小连接数
spring.datasource.druid.min-idle=10
#最大连接数
spring.datasource.druid.max-active=100


#开启mybatisSQL显示
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#数据库url
spring.datasource.url=jdbc:mysql://localhost:3306/xiangmu?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8
#数据库用户密码
spring.datasource.username=root
spring.datasource.password=root

#开启mybatis二级缓存
mybatis.configuration.cache-enabled=true
#指定mybatis的Mapper文件存放位置
mybatis.mapper-locations=classpath:mapper/*.xml
#数据库驱动
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#单个文件大小
spring.servlet.multipart.max-file-size=100MB
spring.servlet.multipart.max-request-size=100MB
#驼峰
mybatis.configuration.map-underscore-to-camel-case: true
#
#file.staticAccessPath=/keshe/**
##file.uploadFolder=/root/uploadFiles/
#file.uploadFolder=F://keshe/
#file.url=/keshe/

log4j

### 设置logger###
log4j.rootLogger = debug,stdout,D,E

### 输出信息到控制台 ###
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

### 按天输出DEBUG 级别以上的日志到=D://logs/debug.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File =F://logs/debug.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %l%m%n

### 按天输出ERROR 级别以上的日志到=D://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =F\://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}  [ %t\:%r ] - [ %p ]  %l%m%n

解决跨域

package com.thethird.config;


import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/*
 * 跨域请求
 */
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
  static final String ORIGINS[] = new String[]{"GET", "POST", "PUT", "DELETE"};
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS)
            .maxAge(3600);
  }
}

拦截器

package com.thethird.config;

import com.thethird.interceptors.JWTInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new JWTInterceptor())
            .addPathPatterns("/test/**")//拦截所有用/**
            .excludePathPatterns("/user/**","/keshe/**");//拦截了用户相关比如登录,不能生成token

  }
}

图片配置

package com.thethird.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    //和页面有关的静态目录都放在项目的static目录下
    registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    //上传的图片在D盘下的OTA目录下,访问路径如:http://localhost:8081/OTA/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg
    //其中OTA表示访问的前缀。"file:D:/OTA/"是文件真实的存储路径
    registry.addResourceHandler("/keshe/**").addResourceLocations("file:F:/keshe/");
  }
}

pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.thethird</groupId>
    <artifactId>coal_project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>coal_project</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

<!--  springboot整合web项目  -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--  springboot整合mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
<!--   springboot热部署  -->
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-devtools</artifactId>-->
<!--            <scope>runtime</scope>-->
<!--            <optional>true</optional>-->
<!--        </dependency>-->
<!--   java连接数据库     -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
<!--    springboot读取配置文件    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
<!--    lombook快速生成getset    -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
<!--    springboot测试启动类    -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
<!--    spring发送邮件    -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-email</artifactId>
            <version>1.5</version>
        </dependency>
<!--    阿里巴巴的fastjson    -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.74</version>
        </dependency>
<!--    阿里巴巴连接池    -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
<!--    分页插件    -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
<!--    slf4j日志         -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
<!--    支持下载    -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.11.0</version>
        </dependency>
    </dependencies>


<!--    打包    -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

用户注册

public Result register(User user) {
    if (user.getBusinessName()==null||user.getFiles()==null||user.getEmail()==null){
      return new Result(500,"前台没传来要注册的用户信息","无法注册");
    }
    //注册校验,不存在可以注册
    User datauser = userDao.selectByBusinessName(user);
    if (datauser != null) {
      return new Result(500, "失败", "已存在该用户");
    }
    System.out.println(".....");
    System.out.println(user.getUserAccount() + user.getPassword() + user.getFiles());
    //获取他的路径/keshe/xxxx.jpg
    ArrayList file = user.getFiles();
    //新的路径
    ArrayList newFilePathArray = new ArrayList();
    //新的路径名
    String newPathName = new String();
    //遍历数据路径
    for (Object path : file) {
      //测试输出路径
      System.out.println(path.toString());
      //获得路径
      StringBuffer oldPath = new StringBuffer(path.toString());
      //获得文件名linux得改----------------------------------------------------------
      String fileName = oldPath.substring(7);
      //到linux记得改路径-------------------------------------------------------------------------------
      newPathName = "F:/keshe/" + user.getBusinessName() + "/" + "认证材料";
      //老的文件路径 到linux记得改路径
      File oldFile = new File("F:/keshe/" + fileName);
      //创建新的文件夹
      File newFileDir = new File(newPathName);
      if (!newFileDir.exists()) {
        newFileDir.mkdirs();
      }
      File newFile = new File(newPathName + "/" + fileName);
      Rename_String.copyFile1(oldFile, newFileDir);
      //删除老文件
      oldFile.delete();
      newFilePathArray.add(newFile.toString());
      log.info("新的文件路径");
      log.info(newFilePathArray);

    }

用户认证(加盐)

@Override
  @Transactional
  public Result sendAccount(User user) throws EmailException {

    User user1 = userDao.selectByBusinessName(user);
    if (user1 == null) {
      return new Result(500, "不存在该用户", "");
    }
    if (user1.getEmail() == null) {
      return new Result(500, "没有邮箱", "");
    }
    String email = user1.getEmail();
    //加密方式
    //获取帐号
    String userAccount;
    User dataUser = userDao.selectTheLastOne();
    //生成账号
    if (dataUser.getUserAccount() != null) {
      String account = dataUser.getUserAccount();
      Integer accountNum = Integer.parseInt(account);
      Integer random2 = random.nextInt(10);
      Integer acc = accountNum + random2;
      userAccount = acc.toString();
    } else {
      userAccount = "50000";
    }
    //随机密码(要发给邮箱的)
    String password = RandomAccountAndPassword.getCharAndNumr();
    user.setUserAccount(userAccount);
    user.setPassword(password);
    emailService.sendAccount(email, userAccount, password);
    //加盐(要插入到数据库的)
    String salt = UUID.randomUUID().toString();
    user.setSalt(salt);
//  System.out.println("盐值"+salt);
    String pass = password + salt;
//  System.out.println("密码+盐"+pass);
    //要放在数据库密码这块的
    String datapassword = DigestUtils.md5DigestAsHex(pass.getBytes());
    user.setAuthentical(1);
    user.setPassword(datapassword);
    log.info(user.toString());
    Financial financial=new Financial();
    financial.setUserAccount(user.getUserAccount());
    financial.setBalance(new BigDecimal(0));
    financial.setFreeze(new BigDecimal(0));
    //生成财物表的帐号
    financialDao.insert(financial);
    int i = userDao.updateUserAccountByBusinessName(user);
//  System.out.println(s);
    return new Result(200, "发送成功", i);
  }

复制拷贝文件和随机文件名

package com.thethird.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;
import java.util.logging.Logger;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

public class Rename_String {


    public static String rename(String origin) {
      StringBuffer sb = new StringBuffer(origin);
      //反转
      String reverseStr = sb.reverse().toString();
      System.out.println(reverseStr);
      int indexOf = reverseStr.indexOf(".");
      String subString = reverseStr.substring(0, indexOf + 1);
      //str2是文件的格式如.png
      String str2 = new StringBuffer(subString).reverse().toString();
      UUID uuid = UUID.randomUUID();
      String str = uuid.toString();
      System.out.println(str + "    =========");
      String newStr = str.replace("-", "");
      return newStr.concat(str2);
    }
  public static void removeFile(File oldPath, File newPath) {//复制
    if (oldPath.exists()) {
      File[] files = oldPath.listFiles();
      for (File file : files) {
        if (file.isFile()) {
          copyFile1(file, newPath);
        } else {
          File file1 = new File(newPath, file.getName());
          file1.mkdirs();
          removeFile(file, file1);
        }
      }
    }
  }
  public static void copyFile1(File file, File newPath) {//复制
    FileInputStream fileInputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
      fileInputStream = new FileInputStream(file);
      fileOutputStream = new FileOutputStream(new File(newPath, file.getName()));
      int len = 0;
      byte[] bytes = new byte[1024 * 8];
      while ((len = fileInputStream.read(bytes)) != -1) {
        fileOutputStream.write(bytes, 0, len);
        fileOutputStream.flush();
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (fileInputStream != null) {
          fileInputStream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
      try {
        if (fileOutputStream != null)
          fileOutputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

  }
  public static void deleteFile(File oldPath) {//删除源文件
    if (oldPath.exists()){
      File[] files = oldPath.listFiles();
      for (File file : files) {
        if(file.isFile()){
          file.delete();
        }else {
          deleteFile(file);
        }
      }
      boolean delete = oldPath.delete();
      System.out.println(delete);
    }
  }
  public static void main(String[] args) {
    StringBuffer sb=new StringBuffer("F:/keshe/\\50318f456c1447f6a2989903f2fd446b.png");
    String substring = sb.substring(10);
    System.out.println(substring);
  }
  }



随机生成密码

public class RandomAccountAndPassword {


  public static String getCharAndNumr() {
    String val = "";
    Random random = new Random();
    for (int i = 0; i < 8; i++) {
      // 输出字母还是数字
      String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
      // 字符串
      if ("char".equalsIgnoreCase(charOrNum)) {
        // 取得大写字母还是小写字母
        int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
        val += (char) (choice + random.nextInt(26));
      } else if ("num".equalsIgnoreCase(charOrNum)) { // 数字
        val += String.valueOf(random.nextInt(10));
      }
    }
    return val;
  }
}

分页

控制层

  @RequestMapping("getUserListNoAuthenticalForAndroid")
  public PagesList getUserListNoAuthentical1( Map<String, Integer> map) {

    Integer pageNum = map.get("pageNum");
    Integer  pageSize=map.get("pageSize");
    Integer maxPage=map.get("pages");

    List<User> users= userService.getUserListNoAuthentical(pageNum, pageSize, maxPage);

    PageInfo<User> pageInfo =new PageInfo<User>(users);
    System.out.println(users);
    System.out.println(pageInfo);
    return new PagesList(200,"成功", pageInfo) ;
  }
服务层
 public List<User> getUserListNoAuthentical(Integer pageNum,Integer  pageSize,Integer pages) {
    //赛选,第几面
   if (pageSize<=0||pageSize==null){
     return null;
   }
    if (pageNum<1){
      pageNum=1;
    }else if(pageNum>=pages){
      pageNum = pages;
    }
    PageHelper.startPage(pageNum, pageSize);
    List<User> data = userDao.getUserListNoAuthentical();
    if (data != null) {
      return data;
    } else {
      return null;
    }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值