1、文件上传
package com.example.demo.utils; import com.example.demo.controller.ex.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.UUID; public class FileUpload { //设置上传文件的最大值 public static final int AVATAR_MAX_SIZE = 10*1024*1024;//10M //限制上传文件的类型 public static final List AVATAR_TYPE = new ArrayList(); static { AVATAR_TYPE.add("image/jpeg"); AVATAR_TYPE.add("image/png"); AVATAR_TYPE.add("image/bmp"); AVATAR_TYPE.add("image/gif"); AVATAR_TYPE.add("image/jpg"); } public static String upload(HttpSession session, MultipartFile file){ //判断文件是否为空 if(file.isEmpty()){ throw new FileEmptyException("文件为空"); } if(file.getSize() > AVATAR_MAX_SIZE){ throw new FileSizeException("文件大小不能超过"+AVATAR_MAX_SIZE+"M"); } //判断文件的类型是否是我们规定的后缀类型 String contentType = file.getContentType(); if(!AVATAR_TYPE.contains(contentType)){ throw new FileTypeException("文件类型不支持"); } //上传的文件 ../upload/文件.png String parent = session.getServletContext().getRealPath("upload"); //file对象指向这个路径,file是否存在 File dir = new File(parent); if(!dir.exists()){ dir.mkdirs();//没有则创建当前目录 } //获取到这个文件名称,uuid工具来生成一个新的字符串作为文件名 String originalFilename = file.getOriginalFilename(); System.out.println("originalFilename"+originalFilename); String str = originalFilename.substring(originalFilename.lastIndexOf(".")); String filename = UUID.randomUUID().toString().toUpperCase() + str; File dest = new File(dir,filename); try { file.transferTo(dest); } catch (FileStateException e) { throw new FileUploadIOException("文件状态异常"); }catch (IOException e) { throw new FileUploadIOException("文件读写异常"); } return filename; } }
如何使用
2、密码md5加密
package com.example.demo.utils; import org.springframework.util.DigestUtils; public class getMD5Password { public static String getPasswd(String passwd,String salt){ //md5算法调用,3次加密 for (int i=0;i<3;i++){ passwd = DigestUtils.md5DigestAsHex((salt+passwd+salt).getBytes()) .toString().toUpperCase(); } return passwd; } }
3、jwt-token生成
package com.example.demo.utils; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTCreator; 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; public class TokenUtil { //token过期时间 - 半小时 private static final long EXPIRE_TIME = 30 * 60 * 1000; //token密钥 private static final String TOKEN_SECRET = "BookStore"; /** * 生成签名,30分钟过期 * * @param username 用户名 * @param loginTime 登录时间 * @return 生成的token */ public static String sign(String username, String loginTime) { try { //获取jwt生成器 JWTCreator.Builder jwtBuilder = JWT.create(); //设置过期时间 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 jwtBuilder .withHeader(header) .withClaim("loginName", username) .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) { //设置签名的加密算法:HMAC256 Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); JWTVerifier verifier = JWT.require(algorithm).build(); DecodedJWT jwt; try { jwt = verifier.verify(token); return true; } catch (Exception e) { return false; } } }
4、cors跨域
package com.example.demo.utils; 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; @Configuration public class CORSFilter {//配置跨域 @Bean public CorsFilter corsFilter(){ CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**",corsConfiguration); return new CorsFilter(source); } }