栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

项目中的工具使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

项目中的工具使用

knife4J
  • 导包
        
        
            com.github.xiaoymin
            knife4j-spring-boot-starter
        
        
            com.github.xiaoymin
            knife4j-springdoc-ui
        
  • 配置类
package com.imooc;

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

@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {
    @Bean
    public Docket defaultApi2() {
        Docket docket=new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        //.title("swagger-bootstrap-ui-demo RESTful APIs")
                        .description("慕红薯短视频实战接口文档")
                        .termsOfServiceUrl("http://www.xx.com/")
                        .contact(new Contact("lee", "http://www.imooc.com/", "abc@imooc.com"))
                        .version("1.0")
                        .build())
                //分组名称
                .groupName("2.X版本")
                .select()
                //这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.imooc.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
}

腾讯云短信工具(一种读取properties配置文件的示例)
  • 导入依赖



 -->

        
            com.tencentcloudapi
            tencentcloud-sdk-java
            3.1.270
        
  • 创建properties配置文件,用于配置密码
# 从腾讯云中生成并且获得
tencent.cloud.secretId=A*************
tencent.cloud.secretKey=l****************
  • 创建工具类读取配置
package com.imooc.utils;




import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@Data

@PropertySource("classpath:tencentcloud.properties") //表示资源文件映射的是哪一个
@ConfigurationProperties(prefix = "tencent.cloud") //通过点操作的,把前缀加进来
public class TencentCloudProperties {
    private String secretId;
    private String secretKey;
}

  • 使用工具类,将配置信息注入工具类中
package com.imooc.utils;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sms.v20210111.SmsClient;
import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SMSUtils {
    @Autowired
    private TencentCloudProperties tencentCloudProperties;

    public void sendSMS(String phone, String code) throws Exception {
        try {
            
            Credential cred = new Credential(tencentCloudProperties.getSecretId(),
                    tencentCloudProperties.getSecretKey());

            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();

//            httpProfile.setReqMethod("POST"); // 默认使用POST

            
            httpProfile.setEndpoint("sms.tencentcloudapi.com");

            // 实例化一个client选项
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            SmsClient client = new SmsClient(cred, "ap-nanjing", clientProfile);

            // 实例化一个请求对象,每个接口都会对应一个request对象
            SendSmsRequest req = new SendSmsRequest();
            String[] phoneNumberSet1 = {"+86" + phone};//电话号码
            req.setPhoneNumberSet(phoneNumberSet1);
            req.setSmsSdkAppId("1*******8");   // 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId
            req.setSignName("喜欢历史的工科生公众号");         // 签名
            req.setTemplateId("******");       // 模板id:必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看

            
            String[] templateParamSet1 = {code};
            req.setTemplateParamSet(templateParamSet1);

            // 返回的resp是一个SendSmsResponse的实例,与请求对象对应
            SendSmsResponse resp = client.SendSms(req);
            // 输出json格式的字符串回包
//            System.out.println(SendSmsResponse.toJsonString(resp));
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
    }

//    public static void main(String[] args) {
//        try {
//            new SMSUtils().sendSMS("17864264616", "7896");
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
Redis使用
  • 导包
        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        
  • 导入Redis工具类(封装了StringRedisTemplate)
  • 配置yml文件
spring:
  redis:
    host: ***********
    port: 6379
    database: 0
    password: ******
项目中异常错误返回

如果项目中有要返回给前端的错误异常,可以通过自定义异常的方式,然后拦截异常并返回给前端

  • 定义枚举类,用于存储常量,该常量定义了返回给前端的内容(ResponseStatusEnum),最后将这些枚举传入到一个优雅的返回类(GraceJSONResult)中。这也是前后端交互的一种处理。
  • 定义异常,继承RunntimeException
package com.imooc.exceptions;
import com.imooc.grace.result.ResponseStatusEnum;




public class MyCustomException extends RuntimeException {

    private ResponseStatusEnum responseStatusEnum;

    public MyCustomException(ResponseStatusEnum responseStatusEnum) {
        super("异常状态码为:" + responseStatusEnum.status()
                + ";具体异常信息为:" + responseStatusEnum.msg());
        this.responseStatusEnum = responseStatusEnum;
    }

    public ResponseStatusEnum getResponseStatusEnum() {
        return responseStatusEnum;
    }

    public void setResponseStatusEnum(ResponseStatusEnum responseStatusEnum) {
        this.responseStatusEnum = responseStatusEnum;
    }
}
  • 定义异常拦截类
    异常拦截类上添加@ControllerAdvice,并在类中的方法上添加@ExceptionHandler(异常.class)注解,用于捕获特定的异常
package com.imooc.exceptions;

import com.imooc.grace.result.GraceJSONResult;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;



@ControllerAdvice
public class GraceExceptionHandler {

    @ExceptionHandler(MyCustomException.class)
    @ResponseBody
    public GraceJSONResult returnMyException(MyCustomException e) {
        e.printStackTrace();
        return GraceJSONResult.exception(e.getResponseStatusEnum());
    }
}

对某个路由进行拦截

编写类实现andlerInterceptor,重写其中的三个拦截方法,再编写配置类实现WebMvcConfigurer,从写addInterceptors方法,并在该类中将andlerInterceptor的实现利用@Bean方式添加到容器中

  • 编写类实现andlerInterceptor
@Slf4j
//可以使用日志        log.info(stu.toString());log.debug(stu.toString());log.warn(stu.toString());log.error(stu.toString());
//日志级别可以去yml文件中配置
public class PassportInterceptor extends BaseInfoProperties implements HandlerInterceptor{

    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        
        String userIp = IPUtil.getRequestIp(request);
        // 得到是否存在的判断
        boolean keyIsExist =  redis.keyIsExist(MOBILE_SMSCODE + ":" + userIp);
        if (keyIsExist) {
            GraceException.display(ResponseStatusEnum.SMS_NEED_WAIT_ERROR);  //这里会抛出异常
            log.info("短信发送频率太大!");
            return false;
        }
        
        return true;
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

  • 编写配置类注册拦截器
package com.imooc;


import com.imooc.interceptor.PassportInterceptor;
import com.imooc.interceptor.UserTokenInterceptor;
import org.springframework.context.annotation.Bean;
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{


    
    @Bean
    public PassportInterceptor passportInterceptor() {
        return new PassportInterceptor();
    }
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(passportInterceptor())
                .addPathPatterns("/passport/getSMSCode");
    }
}

前端输入参数的验证

导入spring-boot-starter-validation验证框架;建立业务对象BO,用于接收前端传来的数据对象,标记处理验证位置;编写接收接口,并处理验证异常

  • 导入spring-boot-starter-validation验证框架
        
        
            org.springframework.boot
            spring-boot-starter-validation
        
  • 建立业务对象BO,标记处理验证位置
package com.imooc.bo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;


@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class RegistLoginBO {

    @NotBlank(message = "手机号不能为空")
    @Length(min = 11, max=11, message = "手机号长度不正确") //框架中的注解
    private String mobile;
    @NotBlank(message = "验证码不能为空")
    private String smsCode;

}

  • 编写接收接口,并处理验证异常,因为直接处理得到的错误结果,那么会对代码造成侵入,所以用异常拦截的方式处理
    @GetMapping("login")
    public Object login(@Valid @RequestBody RegistLoginBO registLoginBO,
                        HttpServletRequest request) throws Exception {
        

    }
@ControllerAdvice
public class GraceExceptionHandler {




    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public GraceJSONResult returnMethodArgumentNotValid(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        Map map = getErrors(result);
        return GraceJSONResult.errorMap(map);
    }


    public Map getErrors(BindingResult result) {
        Map map = new HashMap<>();
        List errorList = result.getFieldErrors();
        for (FieldError ff : errorList) {
            // 错误所对应的属性字段名
            String field = ff.getField();
            // 错误的信息
            String msg = ff.getDefaultMessage();
            map.put(field, msg);
        }
        return map;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/953027.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号