我是靠谱客的博主 天真枫叶,最近开发中收集的这篇文章主要介绍使用IDEA搭建springboot+token+swagger-ui环境配置创建基本框架配置全局配置Token验证Swagger-ui常用工具类,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

使用IDEA搭建springboot+token+swagger-ui

  • 环境配置
  • 创建基本框架
  • 配置
    • POM.XML文件
    • 完善application.properties文件
    • 启动类加入如下注解
  • 全局配置
    • config包下创建CorsConfig类,解决vue跨域问题
    • config包下创建FastJsonHttpMessageConverterEx类
    • 全局异常处理,interceptor包下创建GloablExceptionHandler
  • Token验证
    • 创建自定义注解
      • 进行拦截
      • 放开拦截
    • config包下创建拦截器InterceptorConfig
    • interceptor包下创建AuthenticationInterceptor用于验证
    • interceptor包下创建自定义Token异常类
    • Token工具类,utils包下
    • 登录时Token处理
  • Swagger-ui
    • 导入包
    • config包下创建SwaggerConfiguration
    • 使用
  • 常用工具类
    • 导出Excel
    • 文件上传
    • 返回json封装

环境配置

JDK:1.8 MAVEN:3.6.1 IDE:19.3 MYSQL:5.7

创建基本框架

在这里插入图片描述

选择jdk版本,点击下一步

在这里插入图片描述

Group处设置自己的包路径,Artifact设置自己的目录名

在这里插入图片描述

设置项目名称和项目存储地址。

在这里插入图片描述

搭建完成的项目初始结构

在这里插入图片描述

在这里插入代码片
完善项目结构

配置

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>
    <!--BOOT版本-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.5.RELEASE</version>
        <relativePath/> 
        <!-- lookup parent from repository -->
    </parent>
    <!--包路径-->
    <groupId>com.item</groupId>
    <!--目录-->
    <artifactId>demo</artifactId>
    <!--版本号-->
    <version>0.0.1-SNAPSHOT</version>
    <!--打包后的jar名称-->
    <name>item</name>
    <description>Demo project for Spring Boot</description>
    <packaging>jar</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!--设置mybatis版本-->
        <mybatis.version>1.1.1</mybatis.version>
        <mybatis.tk.version>1.0.0</mybatis.tk.version>
        <!--设置分页插件版本版本-->
        <pagehelper.version>1.2.7</pagehelper.version>
    </properties>

    <dependencies>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        
        <!--mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>${mybatis.tk.version}</version>
        </dependency>
        
        <!--pagehelper 分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>

        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- 添加servlet依赖模块 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
        
        <!-- fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.41</version>
        </dependency>
        
        <!-- swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        
        <!-- jwt token处理 -->
        <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.4.0</version>
        </dependency>
        
        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.18</version>
        </dependency>
        
        <!-- excel -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>

    </dependencies>

    <build>
    	<!--打jar包去掉版本号-->
        <finalName>${project.artifactId}</finalName>
        <plugins>
            <!-- maven 打包方式 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            
            <!-- 打包时忽略测试类插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.18.1</version>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

完善application.properties文件


# 驱动配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url = jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8

spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver

# 连接池的配置信息
# 初始化大小,最小,最大
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# 配置获取连接等待超时的时间
spring.datasource.maxWait=60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

#端口
server.port=8088
#映射实体
mybatis.type-aliases-package=com.item.demo.entity
#映射xml
mybatis.mapper-locations=classpath:mapper/*.xml

#sql日志打印
logging.level.com.item.demo.dao=debug

#指明分页插件是给mysql用的
pagehelper.helper-dialect=mysql
pagehelper.reasonable=true
pagehelper.support-methods-arguments=true
pagehelper.params=count=countSql

启动类加入如下注解

@SpringBootApplication
//指定dao的位置
@MapperScan("com.item.demo.dao")
@EnableScheduling
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication .class, args);
    }
}

全局配置

config包下创建CorsConfig类,解决vue跨域问题

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
 * 解决vue跨域问题
 */
@Configuration
public class CorsConfig {

    @Configuration
    public class CustomCORSConfiguration {
        private CorsConfiguration buildConfig() {
            CorsConfiguration corsConfiguration = new CorsConfiguration();
            corsConfiguration.addAllowedOrigin("*");
            corsConfiguration.addAllowedHeader("*");
            corsConfiguration.addAllowedMethod("*");
            corsConfiguration.setAllowCredentials(true);
            return corsConfiguration;
        }

        @Bean
        public CorsFilter corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            source.registerCorsConfiguration("/**", buildConfig());
            return new CorsFilter(source);
        }
    }
    
}

config包下创建FastJsonHttpMessageConverterEx类

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import java.nio.charset.Charset;

@Configuration
public class FastJsonHttpMessageConverterEx extends FastJsonHttpMessageConverter {

    public FastJsonHttpMessageConverterEx(){
        //在这里配置fastjson特性(全局设置)
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");    //自定义时间格式
        fastJsonConfig.setCharset(Charset.forName("UTF-8"));
        this.setFastJsonConfig(fastJsonConfig);
    }
    @Override
    protected boolean supports(Class<?> clazz) {
        return super.supports(clazz);
    }

}

全局异常处理,interceptor包下创建GloablExceptionHandler

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

/**
 * 全局异常处理类
 */
@ControllerAdvice
public class GloablExceptionHandler {

    /**
     * 文件上传限制异常413
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MultipartException.class)
    public Object handleMultipartException(MultipartException e) {
        String msg = e.getMessage();
        if (msg == null || msg.equals("")) {
            msg = "服务器出错";
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", 413);
        jsonObject.put("msg", "文件太大,不允许上传!" + msg);
        return jsonObject;
    }

    /**
     * token 不合法异常,返回403
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Object handleRuntimeException(RuntimeException e) {
        String msg = e.getMessage();
        if (msg == null || msg.equals("")) {
            msg = "服务器出错";
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", 401);
        jsonObject.put("msg", msg);
        return jsonObject;
    }

    /**
     * token 不合法异常,返回403
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(TokenException.class)
    public Object handleTokenException(TokenException e) {
        String msg = e.getMessage();
        if (msg == null || msg.equals("")) {
            msg = "服务器出错";
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("status", 403);
        jsonObject.put("msg", msg);
        return jsonObject;
    }
}

Token验证

创建自定义注解

进行拦截

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 需要登录才能进行操作的注解AdminLoginToken
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AdminLoginToken {
    boolean required() default true;
}

放开拦截

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 用来跳过验证的PassToken
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
    boolean required() default true;
}

config包下创建拦截器InterceptorConfig

import com.school.item.interceptor.AuthenticationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry interceptorRegistry) {
        interceptorRegistry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/**");// 拦截所有请求,通过判断注解,决定是否需要登录
    }
    @Bean
    public HandlerInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }
}

interceptor包下创建AuthenticationInterceptor用于验证

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.school.item.annotation.AdminLoginToken;
import com.school.item.annotation.PassToken;
import com.school.item.entity.Users;
import com.school.item.service.UsersService;
import com.school.item.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private UsersService usersService;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) {
        String token = httpServletRequest.getHeader("Authorization");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查是否有passtoken注释,有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(AdminLoginToken.class)) {
            AdminLoginToken adminLoginToken = method.getAnnotation(AdminLoginToken.class);
            if (adminLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new TokenException(403,"无token,请重新登录");
                }
                // 获取 token 中的 userId
                int adminUserId = TokenUtil.getAdminUserId(token);
                Users adminUser = usersService.selectByPrimaryKey(adminUserId);
                if (adminUser == null) {
                    throw new TokenException(403,"用户不存在,请重新登录");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TokenUtil.SECRET)).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new TokenException(403,"token不合法");
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

interceptor包下创建自定义Token异常类

**
 * 自定义token异常类
 */
public class TokenException extends RuntimeException {
    private Integer code;

    public TokenException(Integer code, String message){
        super(message);
        this.code = code;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code){
        this.code = code;
    }

}

Token工具类,utils包下

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.school.item.entity.Users;
import com.school.item.interceptor.TokenException;
import java.util.Date;

public class TokenUtil {

    // 过期时间,单位毫秒,正常30分钟
    private static final long EXPIRE_TIME = 1000 * 60 * 30;
    //密钥
    public  static String SECRET = "HH_CC_FFF";

    public static String getAdminToken(Users users) {
        // 生成过期时间
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String token = "";
        token = JWT.create().withAudience(String.valueOf(users.getId()))// 将 user id 保存到 token 里面
                .withExpiresAt(date)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SECRET));// 以 SECRET 作为 token 的密钥;
        return token;
    }

    public static Integer getAdminUserId(String token) {
        int adminUserId = 0;
        try {
            adminUserId = Integer.parseInt(JWT.decode(token).getAudience().get(0));
            return adminUserId;
        } catch (JWTDecodeException j) {
            throw new TokenException(403,"token不合法");
        }
    }
}

登录时Token处理

//获取Token
String adminToken = TokenUtil.getAdminToken("用户对象");
JSONObject obj = new JSONObject();
obj.put("info", "登录后用户信息");
obj.put("token", adminToken);
//返回信息
return ResultVo.build(200, "登录成功", obj);

Swagger-ui

导入包

		<!-- swagger接口 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

config包下创建SwaggerConfiguration

import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.List;
import static springfox.documentation.builders.PathSelectors.regex;

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {

    @Bean
    public Docket platformApi() {

        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).forCodeGeneration(true)
                .select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(regex("^.*(?<!error)$"))
                .build()
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());
    }

    private List<ApiKey> securitySchemes() {
        return Lists.newArrayList(
                new ApiKey("Authorization", "Authorization", "header"));
    }

    private List<SecurityContext> securityContexts() {
        return Lists.newArrayList(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .build()
        );
    }

    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "认证权限");
        return Lists.newArrayList(
                new SecurityReference("Authorization", new AuthorizationScope[]{authorizationScope}));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title("XXX平台API")
                .contact(new Contact(" XXX平台", "", "xiaojiajia981225@outlook.com"))
                .license("Copyright 2019  XXX. All rights reserved.")
                .licenseUrl("").version("2.0").build();
    }

}

使用

//模块
@Api(tags = "XX管理")
//接口
@ApiOperation(value = "查询XX")

常用工具类

导出Excel

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import org.apache.poi.hssf.usermodel.*;

public class ExcelUtil {

    /**
     * Excel表格导出
     *
     * @param response    HttpServletResponse对象
     * @param excelData   Excel表格的数据,封装为List<List<String>>
     * @param sheetName   sheet的名字
     * @param fileName    导出Excel的文件名
     * @param columnWidth Excel表格的宽度,建议为15
     * @throws java.io.IOException 抛IO异常
     */
    public static void exportExcel(HttpServletResponse response,
                                   List<List<String>> excelData,
                                   String sheetName,
                                   String fileName,
                                   int columnWidth) throws IOException {
        //声明一个工作簿
        HSSFWorkbook workbook = new HSSFWorkbook();
        //生成一个表格,设置表格名称
        HSSFSheet sheet = workbook.createSheet(sheetName);
        //设置表格列宽度
        sheet.setDefaultColumnWidth(columnWidth);
        //写入List<List<String>>中的数据
        int rowIndex = 0;
        for (List<String> data : excelData) {
            //创建一个row行,然后自增1
            HSSFRow row = sheet.createRow(rowIndex++);
            //遍历添加本行数据
            for (int i = 0; i < data.size(); i++) {
                //创建一个单元格
                HSSFCell cell = row.createCell(i);
                //创建一个内容对象
                HSSFRichTextString text = new HSSFRichTextString(data.get(i));
                //将内容对象的文字内容写入到单元格中
                cell.setCellValue(text);
            }
        }

        //准备将Excel的输出流通过response输出到页面下载
        //八进制输出流
        response.setContentType("application/octet-stream");
        //设置导出Excel的名称
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        //刷新缓冲
        response.flushBuffer();
        //workbook将Excel写入到response的输出流中,供页面下载该Excel文件
        workbook.write(response.getOutputStream());
        //关闭workbook
        workbook.close();
    }
}

文件上传

import org.springframework.web.multipart.MultipartFile;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

public class FileUpload {

    public static String uploadAccessory(MultipartFile uploadImage) {
        String requestURL = null;
        // 计算文件大小
        BigDecimal size = new BigDecimal(uploadImage.getSize());
        BigDecimal mod = new BigDecimal(1024);
        //除一个1024,不保留小数,进行四舍五入
        String fileSize = size.divide(mod).setScale(0, BigDecimal.ROUND_HALF_UP).toString();
        // 生成的文件名
        String fileName = UploadFileUtils.CreateFileUrl(uploadImage.getOriginalFilename());
        // 生成目的文件夹名称(日期命名)
        String folder = UploadFileUtils.CreateNowDate();
        // 原文件名
        String oldName = uploadImage.getOriginalFilename();
        // 取出文件的后缀(类型)
        String fileType = oldName.substring(oldName.lastIndexOf(".") + 1);
        try {
            InputStream inputStream = uploadImage.getInputStream();
            BufferedImage bi = ImageIO.read(inputStream);
            String uploadPath = "";
            if (bi == null) {
                return "此文件不是图片文件";
            } else {
                // 图片请求路径
                requestURL = "http://127.0.0.1:8190/image/" + folder + "/" + fileName;
                uploadPath = "C:/image/" + folder;
            }
            File file = new File(uploadPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            uploadImage.transferTo(new File(uploadPath + File.separator + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return requestURL;
    }
}
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Calendar;
import java.util.UUID;

public class UploadFileUtils {

    /**
     * 生成文件名+后缀
     *
     * @return
     */
    public static String CreateFileUrl(String path) {
        //获取.的位置
        int index = path.lastIndexOf(".");
        //获取后缀
        String extions = path.substring(index);
        //返回随机生成+后缀
        return UUID.randomUUID() + extions;
    }

    /**
     * 生成当前日期字符串
     *
     * @return
     */
    public static String CreateNowDate() {
        Calendar now = Calendar.getInstance();
        String nowDate = "";
        nowDate += now.get(Calendar.YEAR);
        nowDate += (now.get(Calendar.MONTH) + 1);
        nowDate += now.get(Calendar.DAY_OF_MONTH);
        return nowDate;
    }

    /**
     * 判断是否是图片
     *
     * @param file
     * @return
     */
    public static boolean isImage(File file) {
        if (!file.exists()) {
            return false;
        }
        BufferedImage image = null;
        try {
            image = ImageIO.read(file);
            if (image == null || image.getWidth() <= 0 || image.getHeight() <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

返回json封装

import java.io.Serializable;

public class ResultVo implements Serializable {

    private static final long serialVersionUID = 1L;

    // 响应业务状态
    /*
     * 200	成功
     * 201	错误
     * 400	参数错误
     */
    private Integer status;

    // 响应消息
    private String msg;

    // 响应中的数据
    private Object data;

    public static ResultVo build(Integer status, String msg, Object data) {
        return new ResultVo(status, msg, data);
    }

    public static ResultVo failed(Integer status, String msg) {
        return new ResultVo(status, msg);
    }

    public static ResultVo oK(Object data) {
        return new ResultVo(data);
    }

    public static ResultVo oK() {
        return new ResultVo(null);
    }

    public ResultVo() {

    }

    public ResultVo(Integer status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    public ResultVo(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public ResultVo(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

    public Boolean isOk() {
        return this.status == 200;
    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

至此搭建完成,如有疑问请留言
在这里插入图片描述

最后

以上就是天真枫叶为你收集整理的使用IDEA搭建springboot+token+swagger-ui环境配置创建基本框架配置全局配置Token验证Swagger-ui常用工具类的全部内容,希望文章能够帮你解决使用IDEA搭建springboot+token+swagger-ui环境配置创建基本框架配置全局配置Token验证Swagger-ui常用工具类所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(140)

评论列表共有 0 条评论

立即
投稿
返回
顶部