java常用工具类
1.IP地址获取
public class IPUtil { public static String getIpAddress(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); if("127.0.0.1".equals(ip)||"0:0:0:0:0:0:0:1".equals(ip)){ //根据网卡取本机配置的IP InetAddress inet=null; try { inet = InetAddress.getLocalHost(); } catch (UnknownHostException e) { e.printStackTrace(); } ip= inet.getHostAddress(); } } return ip; } }
2.MD5加密
public class Md5Util { public static String md5(String plainText){ try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte[] digest = md.digest(); int i; StringBuilder sb = new StringBuilder(); for (int offset = 0; offset < digest.length; offset++) { i = digest[offset]; if (i < 0) { i += 256; } if (i < 16) { sb.append(0); } sb.append(Integer.toHexString(i)); } return sb.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } }
3.获取端
public class WebUtil { public static String getPlatform(HttpServletRequest request){ /**User Agent中文名为用户代理,简称 UA,它是一个特殊字符串头,使得服务器 能够识别客户使用的操作系统及版本、CPU 类型、浏览器及版本、浏览器渲染引擎、浏览器语言、浏览器插件等*/ String agent= request.getHeader("user-agent"); //客户端类型常量 String type = ""; if(agent.contains("iPhone")||agent.contains("iPod")||agent.contains("iPad")){ type = "ios"; } else if(agent.contains("Android") || agent.contains("Linux")) { type = "apk"; } else if(agent.indexOf("micromessenger") > 0){ type = "wx"; }else { type = "pc"; } return type; } }
4.获取session,response
public class WebUtil { /** * 获取session * @return */ public static HttpSession getSession (){ HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession session = request.getSession(); return session; } /** * 获取response * @return */ public static HttpServletResponse getResponse(){ HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse(); return response; } }
5.restful统一返回格式
public class Response implements Serializable { public static final String FAILURE = "failure"; public static final String SUCCESS = "success"; private String status; private Object data; public static Response success(Object data){ Response bean = new Response(data); bean.setStatus(SUCCESS); return bean; } public static Response failure(Object data){ Response bean = new Response(data); bean.setStatus(FAILURE); return bean; } public Response(Object data) { this.data = data; } public Response() {} public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } }
6.多线程日志记录
public class LogsUtil {private static LogsUtil instance = new LogsUtil(); private LogsUtil(){} public static LogsUtil getInstance(){ return instance; } public void log(HttpServletRequest request, String action, String info){ String ip = IPUtil.getIpAddress(request); int uid = WebUtil.getUser().getId(); String equip = WebUtil.getPlatform(request); try { new Thread(new WriteLog(info,equip,ip,action,uid)).start(); } catch (Exception e) { e.printStackTrace(); System.out.println("日志记录异常"); } } /** * 多线程日志记录器 */ private class WriteLog implements Runnable { private String info; private String equip; private String ip; private String action; private Integer uid; public WriteLog(String info, String equip, String ip, String action, Integer uid) { this.info = info; this.equip = equip; this.ip = ip; this.action = action; this.uid = uid; } public void run() { try { //insert into table } catch (Exception e) { e.printStackTrace(); System.out.println("SQL执行异常"); } } } }
7.redis工具
@Service public class RedisUtil { private static final Long SUCCESS = 1L; @Autowired private RedisTemplate<String, Object> redisTemplate; /** * 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) * @return */ public boolean expire(String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { return false; } } /** * 根据key 获取过期时间 * * @param key 键 不能为null * @return 时间(秒) 返回0代表为永久有效 */ public long getExpire(String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * 判断key是否存在 * * @param key 键 * @return true 存在 false不存在 */ public boolean hasKey(String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { return false; } } /** * 删除缓存 * * @param key 可以传一个值 或多个 */ @SuppressWarnings("unchecked") public void del(String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } /** * 普通缓存获取 * * @param key 键 * @return 值 */ public Object get(String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * 普通缓存放入 * * @param key 键 * @param value 值 * @return true成功 false失败 */ public boolean set(String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { return false; } } /** * 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期 * @return true成功 false 失败 */ public boolean set(String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(key, value); } return true; } catch (Exception e) { return false; } } /** * 递增 * * @param key 键 * @param delta 要增加几(大于0) * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return 147 */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } /** * 获取分布式锁 * @param lockKey 锁 * @param requestId 请求标识 * @param expireTime 单位秒 * @param waitTimeout 单位毫秒 * @return 是否获取成功 */ public boolean tryLock(String lockKey, String requestId, int expireTime,long waitTimeout) { long nanoTime = System.nanoTime(); // 当前时间 try{ String script = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end"; int count = 0; do{ RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class); Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey),requestId,expireTime); if(SUCCESS.equals(result)) { return true; } Thread.sleep(500L);//休眠500毫秒 count++; }while ((System.nanoTime() - nanoTime) < TimeUnit.MILLISECONDS.toNanos(waitTimeout)); }catch(Exception e){ e.printStackTrace(); } return false; } /** * 释放锁 * @param lockKey 锁 * @param requestId 请求标识 * @return 是否释放成功 */ public boolean releaseLock(String lockKey, String requestId) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; RedisScript<String> redisScript = new DefaultRedisScript<>(script, String.class); Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), requestId); if (SUCCESS.equals(result)) { return true; } return false; } }
8.token工具
public class TokenUtil { //密钥 private static final String TOKEN_SECRET = "5R5roUcuAu3o5C3o"; //30分钟超时 private static final long TIME_OUT = 30 * 60 * 1000; //加密 public static String sign(Long uid) { try { Date expiration_time = new Date(System.currentTimeMillis() + TIME_OUT); Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); Map<String, Object> headerMap = new HashMap<>(2); headerMap.put("type", "JWT"); headerMap.put("alg", "HS256"); return JWT.create().withHeader(headerMap).withClaim("uid", uid).withExpiresAt(expiration_time).sign(algorithm); } catch (Exception e) { return null; } } //解密 public static DecodedJWT verify(String token) { try { JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build(); DecodedJWT jwt = verifier.verify(token); return jwt; } catch (Exception e) { //解码异常 return null; } } public static void main(String[] args) { String token = sign(170L); System.out.println("token::" + token); DecodedJWT jwt = verify(token); if (jwt != null) { //UID System.out.println("uid::" + jwt.getClaim("uid").asLong()); //TIMEOUT System.out.println("timeout::" + jwt.getExpiresAt()); //ALG System.out.println("alg::" + jwt.getAlgorithm()); //TOKEN System.out.println("token::" + jwt.getToken()); //HEADER System.out.println("header::" + jwt.getHeader()); //PAYLOAD System.out.println("payload::" + jwt.getPayload()); //SIGNATURE System.out.println("signature::" + jwt.getSignature()); } else { System.out.println("Decoded JWT Failure"); } } }
9.mail工具
<dependency> <groupId>javax.mail</groupId> <artifactId>mail</artifactId> <version>1.4.7</version> </dependency>
public class MailUtil { /** * 25端口http发送 * @param subject * @param emailMsg * @return */ public static boolean sendMailBy25(String subject,String emailMsg) { try { Properties config = mailConfig(); //定义Properties对象,设置环境信息 Properties props = System.getProperties(); //设置邮件服务器的地址 props.setProperty("mail.smtp.host", config.getProperty("mail.host")); // 指定的smtp服务器 props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.transport.protocol", "smtp");//设置发送邮件使用的协议 props.put("mail.smtp.starttls.enable", "true"); //创建Session对象,session对象表示整个邮件的环境信息 Session session = Session.getInstance(props); //设置输出调试信息 session.setDebug(true); //Message的实例对象表示一封电子邮件 MimeMessage message = new MimeMessage(session); //设置发件人的地址 message.setFrom(new InternetAddress(config.getProperty("mail.username"))); //设置主题 message.setSubject(subject); //设置邮件的文本内容 //message.setText("Welcome to JavaMail World!"); message.setContent((emailMsg), "text/html;charset=utf-8"); //设置附件 //message.setDataHandler(dh); //从session的环境中获取发送邮件的对象 Transport transport = session.getTransport(); //连接邮件服务器 transport.connect(config.getProperty("mail.host"), Integer.parseInt(config.getProperty("mail.port")), config.getProperty("mail.username"), config.getProperty("mail.pwd")); //设置收件人地址,并发送消息 transport.sendMessage(message, new Address[]{new InternetAddress(config.getProperty("mail.receiver"))}); transport.close(); return true; } catch (MessagingException e) { e.printStackTrace(); return false; } } /** * 994端口https发送 * @param subject * @param emailMsg * @param realPath * @param fileName * @return * @throws UnsupportedEncodingException */ public static boolean sendMailBy994(String subject,String emailMsg,String realPath,String fileName) throws UnsupportedEncodingException { try { Properties config = mailConfig(); //定义Properties对象,设置环境信息 Properties props = System.getProperties(); //设置邮件服务器的地址 props.setProperty("mail.smtp.host", config.getProperty("mail.host")); // 指定的smtp服务器 props.setProperty("mail.smtp.auth", "true"); props.setProperty("mail.transport.protocol", "smtp");//设置发送邮件使用的协议 props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); props.setProperty("mail.smtp.socketFactory.fallback", "false"); //创建Session对象,session对象表示整个邮件的环境信息 Session session = Session.getInstance(props); //设置输出调试信息 session.setDebug(true); //Message的实例对象表示一封电子邮件 MimeMessage message = new MimeMessage(session); //设置发件人的地址 message.setFrom(new InternetAddress(config.getProperty("mail.username"))); //设置主题 message.setSubject(subject); //设置邮件的文本内容 //message.setText("Welcome to JavaMail World!"); message.setContent((emailMsg), "text/html;charset=utf-8"); //创建附件 if(StringUtils.isNotBlank(realPath)){ MimeMultipart msgMultipart = new MimeMultipart("mixed"); //文本内容 BodyPart txt = new MimeBodyPart(); txt.setContent(emailMsg, "text/html;charset=utf-8"); MimeBodyPart attch1 = new MimeBodyPart(); msgMultipart.addBodyPart(attch1); msgMultipart.addBodyPart(txt); //设置附件的名称 attch1.setFileName(MimeUtility.encodeText(fileName, "UTF-8", "B")); //设置数据源(即数据的来源) DataSource ds1 = new FileDataSource(new File(realPath)); DataHandler dh1 = new DataHandler(ds1); //设置附件的句柄给这个附件对象 attch1.setDataHandler(dh1); message.setContent(msgMultipart); } //从session的环境中获取发送邮件的对象 Transport transport = session.getTransport(); //连接邮件服务器 transport.connect(config.getProperty("mail.host"), Integer.parseInt(config.getProperty("mail.port")), config.getProperty("mail.username"), config.getProperty("mail.pwd")); //设置收件人地址,并发送消息 transport.sendMessage(message, new Address[]{new InternetAddress(config.getProperty("mail.receiver"))}); transport.close(); return true; } catch (MessagingException e) { e.printStackTrace(); return false; } } public static Properties mailConfig(){ try { Properties properties = new Properties(); // 使用ClassLoader加载properties配置文件生成对应的输入流 InputStream in = MailUtil.class.getClassLoader().getResourceAsStream("mail.properties"); // 使用properties对象加载输入流 properties.load(in); return properties; } catch (IOException e) { e.printStackTrace(); } return null; } }
10.properties工具
public static Properties mailConfig(){ try { Properties properties = new Properties(); // 使用ClassLoader加载properties配置文件生成对应的输入流 InputStream in = MailUtil.class.getClassLoader().getResourceAsStream("mail.properties"); // 使用properties对象加载输入流 properties.load(in); return properties; } catch (IOException e) { e.printStackTrace(); } return null; }