封装java返回对象|swagger配置|jwtUtil|

1. 封装java返回对象

public class R {
    
    
    private String code;
    private String msg;
    private Map<String, Object> data;

    public R(String code, String msg, Map<String, Object> data) {
    
    
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    // getter and setter methods
    public String getCode() {
    
    
        return code;
    }

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

    public String getMsg() {
    
    
        return msg;
    }

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

    public Map<String, Object> getData() {
    
    
        return data;
    }

    public void setData(Map<String, Object> data) {
    
    
        this.data = data;
    }

    // static factory methods
    public static R ok(Map<String, Object> data) {
    
    
        return new R("200", "OK", data);
    }

    public static R error(String code, String msg) {
    
    
        return new R(code, msg, null);
    }
}

1.2. 使用R对象返回

// 返回成功结果
Map<String, Object> data = new HashMap<>();
data.put("name", "张三");
data.put("age", 20);
R result = R.ok(data);

// 返回错误结果
R errorResult = R.error("501","参数错误");

2. swagger配置

package com.atguigu.service_utils.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2Config {
    
    
    @Bean
    public Docket webApiConfig(){
    
    
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("ggkt")
                .apiInfo(webApiInfo())
                .select()
                //只显示api路径下的页面
                //.paths(Predicates.and(PathSelectors.regex("/api/.*")))
                .build();
    }

    private ApiInfo webApiInfo(){
    
    
        return new ApiInfoBuilder()
                .title("网站-API文档")
                .description("本文档描述了网站微服务接口定义")
                .version("1.0")
                .contact(new Contact("atguigu", "http://atguigu.com", "atguigu.com"))
                .build();
    }
}

3. JWTUtil

package cn.speedit.extend.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @ClassName TokenUtil
 * @author 潮流coder
 * @version 1.0
 * @create 2022/12/9 17:07
 * @description token生成与校验
 */
public class TokenUtil {
    
    
    /**
     * token过期时间
     */
    private static final long EXPIRE_TIME = 5 * 60 * 1000;
    /**
     * token秘钥
     */
    private static final String TOKEN_SECRET = "1669884955725685";


    /**
     * 生成签名,5分钟过期
     * @param username 用户名
     * @param userId 用户id
     * @param loginTime 登录时间
     * @return 生成的token
     */
    public static String sign(String username,String userId, String loginTime) {
    
    
        try {
    
    
            // 设置过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            // 私钥和加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            // 设置头部信息
            Map<String, Object> header = new HashMap<>(2);
            header.put("Type", "Jwt");
            header.put("alg", "HS256");
            // 返回token字符串
            return JWT.create()
                    .withHeader(header)
                    .withClaim("loginName", username)
                    .withClaim("userId", userId)
                    .withClaim("loginTime", loginTime)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 检验token是否正确
     * @param token 需要校验的token
     * @return 校验是否成功
     */
    public static boolean verify(String token){
    
    
        try {
    
    
            //设置签名的加密算法:HMAC256
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        }
        catch (Exception e){
    
    
            //throw new RuntimeException(e.getMessage());
            return false;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45699990/article/details/130658172