Java项目常用的工具类
主要是收集常用的Java项目工具类,减少写不必要的代码,专注写业务逻辑方面的代码
随机数验证码
十分简单的生成随机数验证码(4-6位),只包括数字和字母(大小写),原理很简单,定义两个String类型的字符串,一个是包括字母数字,另一个是空字符串,然后利用Random工具类再结合循环遍历添加指定多少个字符来生成随机验证码
| public class VerifyCodeTool { |
| |
| |
| |
| |
| |
| public static String createVerifyCode(int n) { |
| String code = ""; |
| String data = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; |
| |
| Random r = new Random(); |
| |
| for (int i = 0; i < n; i++) { |
| int index = r.nextInt(data.length()); |
| code += data.charAt(index); |
| } |
| return code; |
| } |
| } |
邮箱验证码
之前学习瑞吉外卖项目时,登录移动端用户时实现用邮箱登录代替了手机号验证码登录(主要是邮箱不用钱😂),但最重要还是图方便,因为手机验证码登录要去阿里云注册账号申请等一系列操作,很费时间,但并不代表手机验证码登录不重要,仍然还是要学习这个的,毕竟真实的项目中肯定用手机验证码登录的多,目前我还没有看见用邮箱登录的😂
{% span red,注意: %}该工具类用于发送邮箱验证码来实现登录,首先你的邮箱要开启SMTP服务才行(在邮箱首页设置账号那里开启,会获得一个16位SMTP口令,把这个口令填写在工具类相应的位置里),然后在maven项目中导入邮箱依赖,最后填写好相应的参数就可以直接使用了
| public class MailUtils { |
| |
| public static void sendTestMail(String email, String code) throws MessagingException { |
| |
| Properties pros = new Properties(); |
| |
| pros.put("mail.smtp.auth", "true"); |
| |
| pros.put("mail.smtp.host", "smtp.qq.com"); |
| |
| pros.put("mail.smtp.port", "587"); |
| |
| pros.put("mail.user", "这里写发送者QQ号"); |
| |
| pros.put("mail.password", "这里写入自己的SMTP口令,在QQ邮箱里开启获取"); |
| |
| |
| Authenticator authenticator = new Authenticator() { |
| @Override |
| protected javax.mail.PasswordAuthentication getPasswordAuthentication() { |
| |
| String userName = pros.getProperty("mail.user"); |
| |
| String password = pros.getProperty("mail.password"); |
| return new javax.mail.PasswordAuthentication(userName, password); |
| } |
| }; |
| |
| |
| Session mailSession = Session.getInstance(pros, authenticator); |
| |
| MimeMessage message = new MimeMessage(mailSession); |
| |
| InternetAddress from = new InternetAddress(pros.getProperty("mail.user")); |
| message.setFrom(from); |
| |
| InternetAddress to = new InternetAddress(email); |
| message.setRecipient(Message.RecipientType.TO, to); |
| |
| message.setSubject("邮箱登录验证码"); |
| |
| message.setContent("尊敬的用户:您好!您的登录验证码为:" + code + "(有效期为五分钟,请勿告知他人)", "text/html;charset=UTF-8"); |
| |
| Transport.send(message); |
| } |
| |
| |
| public static String getCode() { |
| |
| String[] beforeShuffle = {"2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", |
| "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", |
| "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", |
| "w", "x", "y", "z"}; |
| |
| List<String> list = Arrays.asList(beforeShuffle); |
| |
| Collections.shuffle(list); |
| |
| StringBuilder sb = new StringBuilder(); |
| |
| for (String s : list) { |
| sb.append(s); |
| } |
| |
| return sb.substring(10, 16); |
| } |
| } |
静态资源映射
配置springboot项目Tomcat服务器访问静态资源(html/css/js/...)
| @Slf4j |
| @Configuration |
| public class WebMvcConfig extends WebMvcConfigurationSupport { |
| |
| |
| |
| |
| |
| @Override |
| protected void addResourceHandlers(ResourceHandlerRegistry registry) { |
| log.info("开始进行静态资源映射..."); |
| |
| |
| |
| |
| |
| registry.addResourceHandler("").addResourceLocations(""); |
| registry.addResourceHandler("").addResourceLocations(""); |
| } |
| |
| |
| |
| |
| |
| |
| @Override |
| protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) { |
| |
| MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter(); |
| |
| messageConverter.setObjectMapper(new JacksonObjectMapper()); |
| |
| converters.add(0, messageConverter); |
| } |
| } |
Date序列化和反序列化
常用于存储和取出数据库Date字段的时候,进行序列化和反序列化,实现两个不同的对象进行互转
| |
| |
| |
| |
| |
| public class JacksonObjectMapper extends ObjectMapper { |
| |
| public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd"; |
| public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; |
| public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss"; |
| |
| public JacksonObjectMapper() { |
| super(); |
| |
| this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false); |
| |
| |
| this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); |
| |
| |
| SimpleModule simpleModule = new SimpleModule() |
| .addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT))) |
| .addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT))) |
| .addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT))) |
| |
| .addSerializer(BigInteger.class, ToStringSerializer.instance) |
| .addSerializer(Long.class, ToStringSerializer.instance) |
| .addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT))) |
| .addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT))) |
| .addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT))); |
| |
| this.registerModule(simpleModule); |
| } |
| } |
正则表达式
包括手机号、邮箱、密码、验证码的正则表达式验证
| public abstract class RegexPatterns { |
| |
| |
| |
| public static final String PHONE_REGEX = "^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$"; |
| |
| |
| |
| public static final String EMAIL_REGEX = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$"; |
| |
| |
| |
| public static final String PASSWORD_REGEX = "^\\w{4,32}$"; |
| |
| |
| |
| public static final String VERIFY_CODE_REGEX = "^[a-zA-Z\\d]{6}$"; |
| |
| } |
校验正则表达式
对手机号、邮箱、验证码进行校验
| public class RegexUtils { |
| |
| |
| |
| |
| |
| public static boolean isPhoneInvalid(String phone){ |
| return mismatch(phone, RegexPatterns.PHONE_REGEX); |
| } |
| |
| |
| |
| |
| |
| public static boolean isEmailInvalid(String email){ |
| return mismatch(email, RegexPatterns.EMAIL_REGEX); |
| } |
| |
| |
| |
| |
| |
| |
| public static boolean isCodeInvalid(String code){ |
| return mismatch(code, RegexPatterns.VERIFY_CODE_REGEX); |
| } |
| |
| |
| private static boolean mismatch(String str, String regex){ |
| if (StrUtil.isBlank(str)) { |
| return true; |
| } |
| return !str.matches(regex); |
| } |
| } |
状态码类
| public class ResultCode { |
| |
| |
| |
| public static final Integer SUCCESS = 200; |
| |
| |
| |
| public static final Integer ERROR = 500; |
| } |
| @Data |
| public class R<T> { |
| @ApiModelProperty(value = "是否成功") |
| private Boolean success; |
| @ApiModelProperty(value = "返回码") |
| private Integer code; |
| @ApiModelProperty(value = "返回消息") |
| private String msg; |
| @ApiModelProperty(value = "填写数据") |
| private Map<String, Object> map = new HashMap<>(); |
| @ApiModelProperty(value = "返回数据") |
| private T data; |
| |
| public static <T> R<T> success(T object) { |
| R<T> r = new R<>(); |
| r.data = object; |
| r.success = true; |
| r.code = SUCCESS; |
| return r; |
| } |
| |
| public static <T> R<T> error(String msg) { |
| R<T> r = new R<>(); |
| r.msg = msg; |
| r.success = false; |
| r.code = ERROR; |
| return r; |
| } |
| |
| public static <T> R<T> error(Integer code, String msg) { |
| R<T> r = new R<>(); |
| r.msg = msg; |
| r.success = false; |
| r.code = code; |
| return r; |
| } |
| |
| public R<T> add(String key, Object value) { |
| this.map.put(key, value); |
| return this; |
| } |
| } |
异常处理
| @Slf4j |
| @ControllerAdvice |
| public class GlobalExceptionHander { |
| |
| |
| |
| |
| |
| |
| @ResponseBody |
| @ExceptionHandler(value = Exception.class) |
| public R error(Exception e){ |
| e.printStackTrace(); |
| log.error(e.getMessage()); |
| return R.error("执行了全局异常处理"); |
| } |
| |
| |
| |
| |
| @ExceptionHandler(value = GuliException.class) |
| @ResponseBody |
| public R error(MyException e){ |
| e.printStackTrace(); |
| return R.error(e.getCode(),e.getMsg()); |
| } |
| } |
| @Data |
| @AllArgsConstructor |
| @NoArgsConstructor |
| public class MyException extends RuntimeException { |
| |
| |
| |
| private Integer code; |
| |
| |
| |
| private String msg; |
| } |
字段自动填充
| @Component |
| public class MyMetaObjectHandler implements MetaObjectHandler { |
| |
| @Override |
| public void insertFill(MetaObject metaObject) { |
| |
| this.setFieldValByName("createTime", new Date(), metaObject); |
| this.setFieldValByName("updateTime", new Date(), metaObject); |
| } |
| |
| @Override |
| public void updateFill(MetaObject metaObject) { |
| this.setFieldValByName("updateTime", new Date(), metaObject); |
| } |
| } |
Swagger配置类
| @Configuration |
| @EnableSwagger2 |
| public class SwaggerConfig { |
| @Bean |
| public Docket webApiConfig(){ |
| return new Docket(DocumentationType.SWAGGER_2) |
| .groupName("webApi") |
| .apiInfo(webApiInfo()) |
| .select() |
| .paths(Predicates.not(PathSelectors.regex("/admin/.*"))) |
| .paths(Predicates.not(PathSelectors.regex("/error.*"))) |
| .build(); |
| } |
| private ApiInfo webApiInfo(){ |
| return new ApiInfoBuilder() |
| .title("网站-课程中心API文档") |
| .description("本文档描述了课程中心微服务接口定义") |
| .version("1.0") |
| .contact(new Contact("guangzai", "http://blog.ydg.icu", "YDG_0814@qq.com")) |
| .build(); |
| } |
| } |
自动生成代码
| public class CodeGenerator { |
| |
| @Test |
| public void run() { |
| |
| |
| AutoGenerator mpg = new AutoGenerator(); |
| |
| |
| GlobalConfig gc = new GlobalConfig(); |
| String projectPath = System.getProperty("user.dir"); |
| gc.setOutputDir(projectPath + "/src/main/java"); |
| gc.setAuthor("guangzai"); |
| gc.setOpen(false); |
| gc.setFileOverride(false); |
| gc.setServiceName("%sService"); |
| gc.setIdType(IdType.ID_WORKER_STR); |
| gc.setDateType(DateType.ONLY_DATE); |
| gc.setSwagger2(true); |
| |
| mpg.setGlobalConfig(gc); |
| |
| |
| DataSourceConfig dsc = new DataSourceConfig(); |
| dsc.setUrl("jdbc:mysql://localhost:3306/数据库名称?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8"); |
| dsc.setDriverName("com.mysql.cj.jdbc.Driver"); |
| dsc.setUsername("root"); |
| dsc.setPassword("root"); |
| dsc.setDbType(DbType.MYSQL); |
| mpg.setDataSource(dsc); |
| |
| |
| PackageConfig pc = new PackageConfig(); |
| pc.setModuleName("demo"); |
| pc.setParent("com.guangzai"); |
| pc.setController("controller"); |
| pc.setEntity("entity"); |
| pc.setService("service"); |
| pc.setMapper("mapper"); |
| mpg.setPackageInfo(pc); |
| |
| |
| StrategyConfig strategy = new StrategyConfig(); |
| strategy.setInclude("demo"); |
| strategy.setNaming(NamingStrategy.underline_to_camel); |
| strategy.setTablePrefix(pc.getModuleName() + "_"); |
| |
| strategy.setColumnNaming(NamingStrategy.underline_to_camel); |
| strategy.setEntityLombokModel(true); |
| |
| strategy.setRestControllerStyle(true); |
| strategy.setControllerMappingHyphenStyle(true); |
| |
| mpg.setStrategy(strategy); |
| |
| |
| |
| mpg.execute(); |
| } |
| } |
逻辑删除插件
| |
| |
| |
| @Bean |
| public ISqlInjector sqlInjector() { |
| return new LogicSqlInjector(); |
| } |
分页插件
| |
| |
| |
| @Bean |
| public PaginationInterceptor paginationInterceptor() { |
| return new PaginationInterceptor(); |
| } |
日志配置xml文件
将日志输出到文件中保存,其他配置文件xml的名字必须为logback-spring.xml,将该xml文件放在resource资源目录下即可
| <?xml version="1.0" encoding="UTF-8"?> |
| <configuration scan="true" scanPeriod="10 seconds"> |
| |
| |
| |
| |
| |
| |
| |
| |
| <contextName>logback</contextName> |
| |
| |
| |
| <property name="log.path" value="guli_log/edu" /> |
| |
| |
| |
| |
| |
| |
| |
| <property name="CONSOLE_LOG_PATTERN" |
| value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) |%highlight(%-5level) |
| |%blue(%thread) |%blue(%file:%line) |%green(%logger) |%cyan(%msg%n)"/> |
| |
| <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> |
| |
| |
| |
| |
| <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> |
| <level>INFO</level> |
| </filter> |
| <encoder> |
| <Pattern>${CONSOLE_LOG_PATTERN}</Pattern> |
| |
| <charset>UTF-8</charset> |
| </encoder> |
| </appender> |
| |
| |
| <appender name="INFO_FILE" |
| class="ch.qos.logback.core.rolling.RollingFileAppender"> |
| |
| <file>${log.path}/log_info.log</file> |
| |
| <encoder> |
| <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level |
| %logger{50} - %msg%n</pattern> |
| <charset>UTF-8</charset> |
| </encoder> |
| |
| <rollingPolicy |
| class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> |
| |
| <fileNamePattern>${log.path}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern> |
| <timeBasedFileNamingAndTriggeringPolicy |
| class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> |
| <maxFileSize>100MB</maxFileSize> |
| </timeBasedFileNamingAndTriggeringPolicy> |
| |
| <maxHistory>15</maxHistory> |
| </rollingPolicy> |
| |
| <filter class="ch.qos.logback.classic.filter.LevelFilter"> |
| <level>INFO</level> |
| <onMatch>ACCEPT</onMatch> |
| <onMismatch>DENY</onMismatch> |
| </filter> |
| </appender> |
| |
| <appender name="WARN_FILE" |
| class="ch.qos.logback.core.rolling.RollingFileAppender"> |
| |
| <file>${log.path}/log_warn.log</file> |
| |
| <encoder> |
| <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level |
| %logger{50} - %msg%n</pattern> |
| <charset>UTF-8</charset> |
| </encoder> |
| |
| <rollingPolicy |
| class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> |
| <fileNamePattern>${log.path}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern> |
| <timeBasedFileNamingAndTriggeringPolicy |
| class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> |
| <maxFileSize>100MB</maxFileSize> |
| </timeBasedFileNamingAndTriggeringPolicy> |
| |
| <maxHistory>15</maxHistory> |
| </rollingPolicy> |
| |
| <filter class="ch.qos.logback.classic.filter.LevelFilter"> |
| <level>warn</level> |
| <onMatch>ACCEPT</onMatch> |
| <onMismatch>DENY</onMismatch> |
| </filter> |
| </appender> |
| |
| <appender name="ERROR_FILE" |
| class="ch.qos.logback.core.rolling.RollingFileAppender"> |
| |
| <file>${log.path}/log_error.log</file> |
| |
| <encoder> |
| <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level |
| %logger{50} - %msg%n</pattern> |
| <charset>UTF-8</charset> |
| </encoder> |
| |
| <rollingPolicy |
| class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> |
| <fileNamePattern>${log.path}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern> |
| <timeBasedFileNamingAndTriggeringPolicy |
| class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> |
| <maxFileSize>100MB</maxFileSize> |
| </timeBasedFileNamingAndTriggeringPolicy> |
| |
| <maxHistory>15</maxHistory> |
| </rollingPolicy> |
| |
| <filter class="ch.qos.logback.classic.filter.LevelFilter"> |
| <level>ERROR</level> |
| <onMatch>ACCEPT</onMatch> |
| <onMismatch>DENY</onMismatch> |
| </filter> |
| </appender> |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| <springProfile name="dev"> |
| |
| <logger name="com.guli" level="INFO" /> |
| |
| |
| |
| |
| |
| |
| <root level="INFO"> |
| <appender-ref ref="CONSOLE" /> |
| <appender-ref ref="INFO_FILE" /> |
| <appender-ref ref="WARN_FILE" /> |
| <appender-ref ref="ERROR_FILE" /> |
| </root> |
| </springProfile> |
| |
| <springProfile name="pro"> |
| <root level="INFO"> |
| <appender-ref ref="CONSOLE" /> |
| <appender-ref ref="DEBUG_FILE" /> |
| <appender-ref ref="INFO_FILE" /> |
| <appender-ref ref="ERROR_FILE" /> |
| <appender-ref ref="WARN_FILE" /> |
| </root> |
| </springProfile> |
| </configuration> |
上传图片到码云
springboot项目存储图片到Gitee(码云里)
工具类
| import java.text.SimpleDateFormat; |
| import java.util.Date; |
| |
| public class DateUtils { |
| |
| |
| |
| |
| public static String getYearMonth(){ |
| |
| SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); |
| return sdf.format(new Date()); |
| } |
| } |
| public class FileUtils { |
| |
| |
| |
| |
| |
| public static String getFileSuffix(String fileName) { |
| return fileName.contains(".") ? fileName.substring(fileName.indexOf('.')) : null; |
| } |
| } |
| import cn.hutool.core.codec.Base64; |
| import java.util.HashMap; |
| import java.util.Map; |
| import java.util.UUID; |
| |
| |
| |
| |
| |
| |
| |
| public class UploadGiteeImgBed { |
| |
| |
| |
| |
| public static final String ACCESS_TOKEN = "bc8e13839b1cd8cf6a7af161f2ee84ab"; |
| |
| |
| |
| |
| public static final String OWNER = "YDG0814"; |
| |
| |
| |
| |
| public static final String REPO = "head-portrait"; |
| |
| |
| |
| |
| |
| public static final String PATH = "/uploadimg/" + DateUtils.getYearMonth() + "/"; |
| |
| |
| |
| |
| |
| public static final String ADD_MESSAGE = "add img"; |
| public static final String DEL_MESSAGE = "DEL img"; |
| |
| |
| |
| |
| |
| |
| |
| |
| public static final String API_CREATE_POST = "https://gitee.com/api/v5/repos/%s/%s/contents/%s"; |
| |
| |
| |
| |
| |
| |
| |
| |
| public static String createUploadFileUrl(String originalFilename) { |
| |
| String suffix = FileUtils.getFileSuffix(originalFilename); |
| |
| String fileName = System.currentTimeMillis() + "_" + UUID.randomUUID() + suffix; |
| |
| String url = String.format(UploadGiteeImgBed.API_CREATE_POST, |
| UploadGiteeImgBed.OWNER, |
| UploadGiteeImgBed.REPO, |
| UploadGiteeImgBed.PATH + fileName); |
| return url; |
| } |
| |
| |
| |
| |
| |
| |
| |
| public static Map<String, Object> getUploadBodyMap(byte[] multipartFile) { |
| HashMap<String, Object> bodyMap = new HashMap<>(3); |
| bodyMap.put("access_token", UploadGiteeImgBed.ACCESS_TOKEN); |
| bodyMap.put("message", UploadGiteeImgBed.ADD_MESSAGE); |
| bodyMap.put("content", Base64.encode(multipartFile)); |
| return bodyMap; |
| } |
| } |
控制层
| import cn.hutool.http.HttpUtil; |
| import cn.hutool.json.JSONObject; |
| import cn.hutool.json.JSONUtil; |
| import com.guangzai.commonutils.R; |
| import com.guangzai.oss.utils.UploadGiteeImgBed; |
| import com.guangzai.servicebase.exceptionhandler.GuliException; |
| import lombok.extern.slf4j.Slf4j; |
| import org.springframework.web.bind.annotation.PostMapping; |
| import org.springframework.web.bind.annotation.RequestMapping; |
| import org.springframework.web.bind.annotation.RequestParam; |
| import org.springframework.web.bind.annotation.RestController; |
| import org.springframework.web.multipart.MultipartFile; |
| import java.io.IOException; |
| import java.util.Map; |
| |
| @RestController |
| @Slf4j |
| @RequestMapping("/gitee") |
| public class UploadController { |
| |
| |
| |
| |
| |
| |
| |
| @PostMapping("/uploadImg") |
| public R uploadImg(@RequestParam("file") MultipartFile multipartFile) throws IOException { |
| log.info("uploadImg()请求已来临..."); |
| |
| String originalFilename = multipartFile.getOriginalFilename(); |
| if (originalFilename == null) { |
| throw new GuliException(); |
| } |
| String targetURL = UploadGiteeImgBed.createUploadFileUrl(originalFilename); |
| log.info("目标url:" + targetURL); |
| |
| Map<String, Object> uploadBodyMap = UploadGiteeImgBed.getUploadBodyMap(multipartFile.getBytes()); |
| |
| String JSONResult = HttpUtil.post(targetURL, uploadBodyMap); |
| |
| JSONObject jsonObj = JSONUtil.parseObj(JSONResult); |
| |
| if (jsonObj.getObj("commit") == null) { |
| return R.error("请求失败"); |
| } |
| |
| JSONObject content = JSONUtil.parseObj(jsonObj.getObj("content")); |
| log.info("响应data为:" + content.getObj("download_url")); |
| return R.success(content.getObj("download_url")); |
| } |
| } |
redis配置类
| @EnableCaching |
| @Configuration |
| public class RedisConfig extends CachingConfigurerSupport { |
| |
| @Bean |
| public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { |
| RedisTemplate<String, Object> template = new RedisTemplate<>(); |
| RedisSerializer<String> redisSerializer = new StringRedisSerializer(); |
| Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); |
| ObjectMapper om = new ObjectMapper(); |
| om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); |
| om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); |
| jackson2JsonRedisSerializer.setObjectMapper(om); |
| template.setConnectionFactory(factory); |
| |
| template.setKeySerializer(redisSerializer); |
| |
| template.setValueSerializer(jackson2JsonRedisSerializer); |
| |
| template.setHashValueSerializer(jackson2JsonRedisSerializer); |
| return template; |
| } |
| |
| @Bean |
| public CacheManager cacheManager(RedisConnectionFactory factory) { |
| RedisSerializer<String> redisSerializer = new StringRedisSerializer(); |
| Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); |
| |
| ObjectMapper om = new ObjectMapper(); |
| om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); |
| om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); |
| jackson2JsonRedisSerializer.setObjectMapper(om); |
| |
| RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig() |
| .entryTtl(Duration.ofSeconds(600)) |
| .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)) |
| .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) |
| .disableCachingNullValues(); |
| RedisCacheManager cacheManager = RedisCacheManager.builder(factory) |
| .cacheDefaults(config) |
| .build(); |
| return cacheManager; |
| } |
| } |
JWT工具类
| |
| |
| |
| |
| public class JwtUtils { |
| |
| |
| |
| |
| public static final long EXPIRE = 1000 * 60 * 60 * 24; |
| |
| |
| |
| |
| public static final String APP_SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO"; |
| |
| |
| |
| |
| |
| |
| |
| public static String getJwtToken(String id, String nickname){ |
| |
| String JwtToken = Jwts.builder() |
| .setHeaderParam("typ", "JWT") |
| .setHeaderParam("alg", "HS256") |
| |
| .setSubject("guli-user") |
| |
| .setIssuedAt(new Date()) |
| .setExpiration(new Date(System.currentTimeMillis() + EXPIRE)) |
| |
| .claim("id", id) |
| .claim("nickname", nickname) |
| |
| .signWith(SignatureAlgorithm.HS256, APP_SECRET) |
| .compact(); |
| |
| return JwtToken; |
| } |
| |
| |
| |
| |
| |
| |
| public static boolean checkToken(String jwtToken) { |
| if(StringUtils.isEmpty(jwtToken)) { |
| return false; |
| } |
| try { |
| Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| return true; |
| } |
| |
| |
| |
| |
| |
| |
| public static boolean checkToken(HttpServletRequest request) { |
| try { |
| String jwtToken = request.getHeader("token"); |
| if(StringUtils.isEmpty(jwtToken)) { |
| return false; |
| } |
| Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken); |
| } catch (Exception e) { |
| e.printStackTrace(); |
| return false; |
| } |
| return true; |
| } |
| |
| |
| |
| |
| |
| |
| public static String getMemberIdByJwtToken(HttpServletRequest request) { |
| String jwtToken = request.getHeader("token"); |
| if(StringUtils.isEmpty(jwtToken)) { |
| return ""; |
| } |
| Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken); |
| Claims claims = claimsJws.getBody(); |
| return (String)claims.get("id"); |
| } |
| } |
MD5加密
| public final class MD5 { |
| |
| public static String encrypt(String strSrc) { |
| try { |
| char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', |
| '9', 'a', 'b', 'c', 'd', 'e', 'f' }; |
| byte[] bytes = strSrc.getBytes(); |
| MessageDigest md = MessageDigest.getInstance("MD5"); |
| md.update(bytes); |
| bytes = md.digest(); |
| int j = bytes.length; |
| char[] chars = new char[j * 2]; |
| int k = 0; |
| for (int i = 0; i < bytes.length; i++) { |
| byte b = bytes[i]; |
| chars[k++] = hexChars[b >>> 4 & 0xf]; |
| chars[k++] = hexChars[b & 0xf]; |
| } |
| return new String(chars); |
| } catch (NoSuchAlgorithmException e) { |
| e.printStackTrace(); |
| throw new RuntimeException("MD5加密出错!!+" + e); |
| } |
| } |
| |
| public static void main(String[] args) { |
| System.out.println(MD5.encrypt("111111")); |
| } |
| |
| } |
HttpClient工具类
| import org.apache.commons.io.IOUtils; |
| import org.apache.commons.lang.StringUtils; |
| import org.apache.http.Consts; |
| import org.apache.http.HttpEntity; |
| import org.apache.http.HttpResponse; |
| import org.apache.http.NameValuePair; |
| import org.apache.http.client.HttpClient; |
| import org.apache.http.client.config.RequestConfig; |
| import org.apache.http.client.config.RequestConfig.Builder; |
| import org.apache.http.client.entity.UrlEncodedFormEntity; |
| import org.apache.http.client.methods.HttpGet; |
| import org.apache.http.client.methods.HttpPost; |
| import org.apache.http.conn.ConnectTimeoutException; |
| import org.apache.http.conn.ssl.SSLConnectionSocketFactory; |
| import org.apache.http.conn.ssl.SSLContextBuilder; |
| import org.apache.http.conn.ssl.TrustStrategy; |
| import org.apache.http.conn.ssl.X509HostnameVerifier; |
| import org.apache.http.entity.ContentType; |
| import org.apache.http.entity.StringEntity; |
| import org.apache.http.impl.client.CloseableHttpClient; |
| import org.apache.http.impl.client.HttpClients; |
| import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; |
| import org.apache.http.message.BasicNameValuePair; |
| |
| import javax.net.ssl.SSLContext; |
| import javax.net.ssl.SSLException; |
| import javax.net.ssl.SSLSession; |
| import javax.net.ssl.SSLSocket; |
| import java.io.IOException; |
| import java.net.SocketTimeoutException; |
| import java.security.GeneralSecurityException; |
| import java.security.cert.CertificateException; |
| import java.security.cert.X509Certificate; |
| import java.util.ArrayList; |
| import java.util.List; |
| import java.util.Map; |
| import java.util.Map.Entry; |
| import java.util.Set; |
| |
| |
| |
| |
| |
| |
| public class HttpClientUtils { |
| |
| public static final int connTimeout=10000; |
| public static final int readTimeout=10000; |
| public static final String charset="UTF-8"; |
| private static HttpClient client = null; |
| |
| static { |
| PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); |
| cm.setMaxTotal(128); |
| cm.setDefaultMaxPerRoute(128); |
| client = HttpClients.custom().setConnectionManager(cm).build(); |
| } |
| |
| public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{ |
| return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout); |
| } |
| |
| public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{ |
| return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout); |
| } |
| |
| public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException, |
| SocketTimeoutException, Exception { |
| return postForm(url, params, null, connTimeout, readTimeout); |
| } |
| |
| public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, |
| SocketTimeoutException, Exception { |
| return postForm(url, params, null, connTimeout, readTimeout); |
| } |
| |
| public static String get(String url) throws Exception { |
| return get(url, charset, null, null); |
| } |
| |
| public static String get(String url, String charset) throws Exception { |
| return get(url, charset, connTimeout, readTimeout); |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout) |
| throws ConnectTimeoutException, SocketTimeoutException, Exception { |
| HttpClient client = null; |
| HttpPost post = new HttpPost(url); |
| String result = ""; |
| try { |
| if (StringUtils.isNotBlank(body)) { |
| HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset)); |
| post.setEntity(entity); |
| } |
| |
| Builder customReqConf = RequestConfig.custom(); |
| if (connTimeout != null) { |
| customReqConf.setConnectTimeout(connTimeout); |
| } |
| if (readTimeout != null) { |
| customReqConf.setSocketTimeout(readTimeout); |
| } |
| post.setConfig(customReqConf.build()); |
| |
| HttpResponse res; |
| if (url.startsWith("https")) { |
| |
| client = createSSLInsecureClient(); |
| res = client.execute(post); |
| } else { |
| |
| client = HttpClientUtils.client; |
| res = client.execute(post); |
| } |
| result = IOUtils.toString(res.getEntity().getContent(), charset); |
| } finally { |
| post.releaseConnection(); |
| if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) { |
| ((CloseableHttpClient) client).close(); |
| } |
| } |
| return result; |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException, |
| SocketTimeoutException, Exception { |
| |
| HttpClient client = null; |
| HttpPost post = new HttpPost(url); |
| try { |
| if (params != null && !params.isEmpty()) { |
| List<NameValuePair> formParams = new ArrayList<NameValuePair>(); |
| Set<Entry<String, String>> entrySet = params.entrySet(); |
| for (Entry<String, String> entry : entrySet) { |
| formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); |
| } |
| UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8); |
| post.setEntity(entity); |
| } |
| |
| if (headers != null && !headers.isEmpty()) { |
| for (Entry<String, String> entry : headers.entrySet()) { |
| post.addHeader(entry.getKey(), entry.getValue()); |
| } |
| } |
| |
| Builder customReqConf = RequestConfig.custom(); |
| if (connTimeout != null) { |
| customReqConf.setConnectTimeout(connTimeout); |
| } |
| if (readTimeout != null) { |
| customReqConf.setSocketTimeout(readTimeout); |
| } |
| post.setConfig(customReqConf.build()); |
| HttpResponse res = null; |
| if (url.startsWith("https")) { |
| |
| client = createSSLInsecureClient(); |
| res = client.execute(post); |
| } else { |
| |
| client = HttpClientUtils.client; |
| res = client.execute(post); |
| } |
| return IOUtils.toString(res.getEntity().getContent(), "UTF-8"); |
| } finally { |
| post.releaseConnection(); |
| if (url.startsWith("https") && client != null |
| && client instanceof CloseableHttpClient) { |
| ((CloseableHttpClient) client).close(); |
| } |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| public static String get(String url, String charset, Integer connTimeout,Integer readTimeout) |
| throws ConnectTimeoutException,SocketTimeoutException, Exception { |
| |
| HttpClient client = null; |
| HttpGet get = new HttpGet(url); |
| String result = ""; |
| try { |
| |
| Builder customReqConf = RequestConfig.custom(); |
| if (connTimeout != null) { |
| customReqConf.setConnectTimeout(connTimeout); |
| } |
| if (readTimeout != null) { |
| customReqConf.setSocketTimeout(readTimeout); |
| } |
| get.setConfig(customReqConf.build()); |
| |
| HttpResponse res = null; |
| |
| if (url.startsWith("https")) { |
| |
| client = createSSLInsecureClient(); |
| res = client.execute(get); |
| } else { |
| |
| client = HttpClientUtils.client; |
| res = client.execute(get); |
| } |
| |
| result = IOUtils.toString(res.getEntity().getContent(), charset); |
| } finally { |
| get.releaseConnection(); |
| if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) { |
| ((CloseableHttpClient) client).close(); |
| } |
| } |
| return result; |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| @SuppressWarnings("unused") |
| private static String getCharsetFromResponse(HttpResponse ressponse) { |
| |
| if (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) { |
| String contentType = ressponse.getEntity().getContentType().getValue(); |
| if (contentType.contains("charset=")) { |
| return contentType.substring(contentType.indexOf("charset=") + 8); |
| } |
| } |
| return null; |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException { |
| try { |
| SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { |
| public boolean isTrusted(X509Certificate[] chain,String authType) throws CertificateException { |
| return true; |
| } |
| }).build(); |
| |
| SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { |
| |
| @Override |
| public boolean verify(String arg0, SSLSession arg1) { |
| return true; |
| } |
| |
| @Override |
| public void verify(String host, SSLSocket ssl) |
| throws IOException { |
| } |
| |
| @Override |
| public void verify(String host, X509Certificate cert) |
| throws SSLException { |
| } |
| |
| @Override |
| public void verify(String host, String[] cns, |
| String[] subjectAlts) throws SSLException { |
| } |
| |
| }); |
| |
| return HttpClients.custom().setSSLSocketFactory(sslsf).build(); |
| |
| } catch (GeneralSecurityException e) { |
| throw e; |
| } |
| } |
| |
| public static void main(String[] args) { |
| try { |
| String str= post("https://localhost:443/ssl/test.shtml","name=12&page=34","application/x-www-form-urlencoded", "UTF-8", 10000, 10000); |
| |
| |
| |
| |
| |
| System.out.println(str); |
| } catch (ConnectTimeoutException e) { |
| |
| e.printStackTrace(); |
| } catch (SocketTimeoutException e) { |
| |
| e.printStackTrace(); |
| } catch (Exception e) { |
| |
| e.printStackTrace(); |
| } |
| } |
| |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!