Java 开发个人工具类
Posted Spring-_-Bear
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 开发个人工具类相关的知识,希望对你有一定的参考价值。
文章目录
一、Database
1.1 BaseDao
/**
* @author Spring-_-Bear
* @datetime 2022/3/16 18:54
*/
public abstract class BaseDao
private final QueryRunner queryRunner = new QueryRunner();
/**
* 执行 insert、update、delete 语句
*
* @param sql sql
* @param params sql 实参
* @return 受影响的行数
*/
public int update(String sql, Object... params)
Connection connection = null;
try
connection = JdbcUtil.getConnection();
return queryRunner.update(connection, sql, params);
catch (SQLException e)
e.printStackTrace();
finally
JdbcUtil.close(connection);
return -1;
/**
* 查询数据库表的一条记录
*
* @param clazz JavaBean class 对象
* @param sql sql
* @param params sql 实参
* @param <T> 返回类型泛型
* @return 一条记录 or null
*/
public <T> T getRecord(Class<T> clazz, String sql, Object... params)
Connection connection = null;
try
connection = JdbcUtil.getConnection();
return queryRunner.query(connection, sql, new BeanHandler<>(clazz), params);
catch (SQLException e)
e.printStackTrace();
finally
JdbcUtil.close(connection);
return null;
/**
* 查询返回多条数据库表记录
*
* @param clazz JavaBean 的 class 对象
* @param sql sql
* @param params sql 实参
* @param <T> 返回类型的泛型
* @return 多条记录 or null
*/
public <T> List<T> listRecord(Class<T> clazz, String sql, Object... params)
Connection connection = null;
try
connection = JdbcUtil.getConnection();
return queryRunner.query(connection, sql, new BeanListHandler<>(clazz), params);
catch (SQLException e)
e.printStackTrace();
finally
JdbcUtil.close(connection);
return null;
/**
* 查询返回单个数值
*
* @param sql sql
* @param params sql 实参
* @return 单个数值 or null
*/
public Object getSingleValue(String sql, Object... params)
Connection connection = null;
try
connection = JdbcUtil.getConnection();
return queryRunner.query(connection, sql, new ScalarHandler(), params);
catch (SQLException e)
e.printStackTrace();
finally
JdbcUtil.close(connection);
return null;
1.2 JdbcUtils
/**
* @author Spring-_-Bear
* @datetime 2022/3/16 18:56
*/
public class JdbcUtil
static DataSource dataSource;
private static ThreadLocal<Connection> connectionThreadLocal = new ThreadLocal<>();
// 静态代码块从配置文件读取配置信息
static
Properties properties = new Properties();
try
InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(resourceAsStream);
dataSource = DruidDataSourceFactory.createDataSource(properties);
catch (Exception e)
e.printStackTrace();
/**
* 从 Druid 数据库连接池中获得一个数据库连接对象
*
* @return Connection
* @throws SQLException exception
*/
public static Connection getConnection() throws SQLException
return dataSource.getConnection();
/**
* 归还连接对象到连接池
*
* @param connection Connection
*/
public static void close(Connection connection)
try
if (connection != null)
connection.close();
catch (SQLException e)
throw new RuntimeException(e);
/**
* 使用 ThreadLocal 确保所有操作都是用同一个 Connection 来实现事务管理
*
* @return Connection
*/
public static Connection getConnection() throws SQLException
// 从 ThreadLocal 中获取连接对象,以确保每次获得的 connection 是同一个
Connection connection = connectionThreadLocal.get();
if (connection == null)
// 连接对象不存在,从数据库连接池中获取并关联到 ThreadLocal 中
connection = dataSource.getConnection();
connectionThreadLocal.set(connection);
return connection;
二、Web
2.1 BaseServlet
/**
* @author Spring-_-Bear
* @datetime 2022/3/1 20:17
*/
public class BaseServlet extends HttpServlet
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
String action = req.getParameter("action");
try
// 通过反射机制获取对应的方法对象
Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// 调用方法
declaredMethod.invoke(this, req, resp);
catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
e.printStackTrace();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
String action = req.getParameter("action");
try
// 通过反射机制获取对应的方法对象
Method declaredMethod = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
// 调用方法
declaredMethod.invoke(this, req, resp);
catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e)
e.printStackTrace();
2.2 EmailUtils
/**
* @author Spring-_-Bear
* @datetime 2022/3/15 16:56
*/
public class EmailUtil
public static final int VERIFY_CODE_LEN = 6;
/**
* 发件人邮箱账号
*/
private static String email;
/**
* 发件人邮箱授权码
*/
private static String password;
/**
* 验证码长度
*/
private static int codeLen;
/**
* 验证码
*/
private String verifyCode;
/**
* 会话对象
*/
private static Session session;
/**
* 邮件工具类对象
*/
private static final EmailUtil EMAIL_UTIL_OBJ = new EmailUtil();
private EmailUtil()
public String getVerifyCode()
return verifyCode;
public static EmailUtil getInstance()
return EMAIL_UTIL_OBJ;
static
Properties fileProperties = new Properties();
try
// 加载配置文件,读取配置信息
InputStream resourceAsStream = EmailUtil.class.getClassLoader().getResourceAsStream("email.properties");
fileProperties.load(resourceAsStream);
email = fileProperties.getProperty("email");
password = fileProperties.getProperty("password");
/* 发件人邮箱服务器 */
String smtpHost = fileProperties.getProperty("smtpHost");
codeLen = NumberUtil.objectToInteger(fileProperties.getProperty("codeLen"), EmailUtil.VERIFY_CODE_LEN);
// 配置发送邮件需要的属性信息
Properties properties = new Properties();
// 使用的协议(JavaMail 规范要求)
properties.setProperty("mail.transport.protocol", "smtp");
// 发件人的邮箱的 SMTP 服务器地址
properties.setProperty("mail.smtp.host", smtpHost);
// 需要请求认证
properties.setProperty("mail.smtp.auth", "true");
session = Session.getInstance(properties);
// 设置为debug模式, 可以查看详细的发送
// log session.setDebug(true);
catch (Exception e)
e.printStackTrace();
/**
* 构建邮件内容
*
* @param dstEmail 收件人邮箱地址
* @return 邮件内容
* @throws Exception exception
*/
private MimeMessage createMailContent(String dstEmail) throws Exception
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress(email, "Book House", "UTF-8"));
// 设置收件人
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(dstEmail));
// 邮件主题
message.setSubject("欢迎使用 Book House 身份验证系统", "UTF-8");
// 邮件正文
verifyCode = NumberUtil.generateCodeInLengthRandomly(codeLen);
message.setContent("您好!您的验证码是:" + verifyCode + ",您正在进行身份验证,打死都不要将验证码告诉别人哦!邮件发送时间:" + DateUtil.dateFormatDatetime(new Date()), "text/html;charset=UTF-8");
// 设置发件时间
message.setSentDate(new Date());
// 保存设置
message.saveChanges();
return message;
/**
* 发送邮件
*
* @param dstEmail 收件人邮箱地址
* @throws Exception exception
*/
public synchronized void sendEmail(String dstEmail) throws Exception
Transport transport = session.getTransport();
transport.connect(email, password);
// 生成邮件内容并发送
MimeMessage message = createMailContent(dstEmail);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
2.3 IPUtils
/**
* @author Spring-_-Bear
* @datetime 2022/3/16 19:42
*/
public class WebUtil
private static DatabaseReader cityReader;
// 读取配置文件,加载 GeoLite2-City.mmdb 数据库资源文件
static
URL cityFileUrl = WebUtil.class.getClassLoader().getResource("GeoLite2-City.mmdb");
File cityFile = new File(Objects.requireNonNull(cityFileUrl).getPath());
try
cityReader = (new DatabaseReader.Builder(cityFile).withCache(new CHMCache())).build();
catch (IOException e)
e.printStackTrace();
/**
* 解析 ip 地址,从 GeoLite2-City.mmdb 数据库中获取对应的国家、省份、城市、经纬度信息
*
* @param ip ip
*/
public static void parseIp(String ip) throws IOException, GeoIp2Exception
// 根据 ip 从 GeoLite2-City.mmdb 数据库中获得响应
CityResponse cityResponse = cityReader.city(InetAddress.getByName(ip));
// 从数据库解析响应中获取城市、省份、邮编、位置等对象
Country country = cityResponse.getCountry();
Subdivision mostSpecificSubdivision = cityResponse.getMostSpecificSubdivision();
City city = cityResponse.getCity();
Postal postal = cityResponse.getPostal();
Location location = cityResponse.getLocation();
// 国家和国家代码
String countryName = country.getNames().get("zh-CN");
String countryIsoCode = country.getIsoCode();
// 省份和省份代码
String provinceName = mostSpecificSubdivision.getNames().get("zh-CN");
String provinceIsoCode = mostSpecificSubdivision.getIsoCode();
// 城市和邮政编码
String cityName = city.getNames().get("zh-CN");
String zipCode = postal.getCode();
// 经度和纬度
Double longitude = location.getLongitude();
Double latitude = location.getLatitude();
System.out.println("国家:" + countryName + " - " + countryIsoCode);
System.out.println("省份:" + provinceName + " - " + provinceIsoCode);
System.out.println("城市:" + cityName + " - " + zipCode);
System.out.println("经纬度:(" + longitude + "," + latitude + ")");
/**
* 从请求头中获取请求 ip 地址
*
* @param request 请求头
* @return ip
*/
public static String getIpAddress(HttpServletRequest request)
String ip = request.getHeader("x-forwarded-for");
String unknown = "unknown";
// 依次解析,找到正确的ip
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 Java多线程工具包java.util.concurrent---LinkedBlockingQueue