一、BaseDao
import com.bear.tools.db.util.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public abstract class BaseDao {
private final QueryRunner queryRunner = new QueryRunner();
public int update(String sql, Object... args) {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
return queryRunner.update(connection, sql, args);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.close(connection);
}
return -1;
}
public <T> T getRecord(Class<T> clazz, String sql, Object... args) {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
return queryRunner.query(connection, sql, new BeanHandler<>(clazz), args);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.close(connection);
}
return null;
}
public <T> List<T> listRecord(Class<T> clazz, String sql, Object... args) {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
return queryRunner.query(connection, sql, new BeanListHandler<>(clazz), args);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.close(connection);
}
return null;
}
public Object getSingleValue(String sql, Object... args) {
Connection connection = null;
try {
connection = JdbcUtils.getConnection();
return queryRunner.query(connection, sql, new ScalarHandler(), args);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.close(connection);
}
return null;
}
}
二、BaseServlet
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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();
}
}
}
三、ThreadPoolUtil
import java.util.concurrent.*;
public class ThreadPoolUtil {
private static final ExecutorService EXECUTOR_SERVICE = new ThreadPoolExecutor(
12,
24,
0L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(512),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy()
);
public static void execute(Runnable task) {
EXECUTOR_SERVICE.execute(task);
}
public static void shutdown() {
EXECUTOR_SERVICE.shutdown();
}
}
四、JdbcUtil
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcUtils {
static DataSource dataSource;
static {
Properties properties = new Properties();
try {
InputStream resourceAsStream = JdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
properties.load(resourceAsStream);
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
public static void close(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
五、DatabaseUtil
import java.io.*;
import java.util.Properties;
public class DatabaseUtil {
private static final String PATH = "resources\\druid.properties";
private static String serverIp;
private static String username;
private static String password;
private static String dbName;
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream(PATH));
serverIp = properties.getProperty("serverIp");
username = properties.getProperty("username");
password = properties.getProperty("password");
dbName = "ebrss";
} catch (IOException e) {
e.printStackTrace();
}
}
public static void databaseBackup(String fileSavePath) {
String command = "mysqldump -h" + serverIp + " -u" + username + " -p" + password + " -B " + dbName + " > " + fileSavePath + "\\" + dbName + ".sql";
try {
Runtime.getRuntime().exec("cmd /c" + command);
} catch (IOException e) {
e.printStackTrace();
}
}
}
六、AppendObjectOutputStream
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class AppendObjectOutputStream extends ObjectOutputStream {
private static File file = null;
public static void setFile(File file) {
AppendObjectOutputStream.file = file;
}
public AppendObjectOutputStream(File file) throws IOException {
super(new FileOutputStream(file, true));
}
@Override
public void writeStreamHeader() throws IOException {
if (file == null) {
super.writeStreamHeader();
} else {
if (file.length() == 0) {
super.writeStreamHeader();
} else {
this.reset();
}
}
}
}
七、FileUtil
import java.io.*;
import java.util.Objects;
public class FileUtil {
public static byte[] getFileDataFromDisk(String filePath) {
File file = new File(filePath);
if (!file.exists() && file.isFile()) {
return null;
}
ByteArrayOutputStream byteArrayOutputStream = null;
FileInputStream fileInputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
fileInputStream = new FileInputStream(file);
int readLen;
byte[] buf = new byte[1024];
while ((readLen = fileInputStream.read(buf)) != -1) {
byteArrayOutputStream.write(buf, 0, readLen);
}
return byteArrayOutputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
Objects.requireNonNull(byteArrayOutputStream).close();
Objects.requireNonNull(fileInputStream).close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static boolean saveFileToDisk(byte[] fileData, String savePath) {
if (fileData == null) {
return false;
}
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(savePath);
fileOutputStream.write(fileData);
fileOutputStream.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
try {
Objects.requireNonNull(fileOutputStream).close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
八、EmailUtil
package com.bear.bookhouse.util;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
public class EmailUtil {
private static final String FROM_EMAIL = "";
private static final String FROM_EMAIL_PW = "";
private static final String MY_EMAIL_SMTP_HOST = "smtp.163.com";
private static final int VERIFY_CODE_LEN = 6;
private String verifyCode;
private static Session session;
private static final EmailUtil EMAIL_UTIL_OBJ = new EmailUtil();
public String getVerifyCode() {
return verifyCode;
}
public static EmailUtil getInstance() {
return EMAIL_UTIL_OBJ;
}
private EmailUtil() {
Properties properties = new Properties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.host", MY_EMAIL_SMTP_HOST);
properties.setProperty("mail.smtp.auth", "true");
session = Session.getInstance(properties);
}
private MimeMessage createMailContent(String dstEmail) throws Exception {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(FROM_EMAIL, "Book House", "UTF-8"));
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(dstEmail));
message.setSubject("身份验证", "UTF-8");
verifyCode = randomGenerateCode();
message.setContent("您好!您的验证码是:" + verifyCode + " ,您正在进行身份验证,打死都不要告诉别人哦!", "text/html;charset=UTF-8");
message.setSentDate(new Date());
message.saveChanges();
return message;
}
public void sendEmail(String dstEmail) throws Exception {
Transport transport = session.getTransport();
transport.connect(FROM_EMAIL, FROM_EMAIL_PW);
MimeMessage message = createMailContent(dstEmail);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
private String randomGenerateCode() {
StringBuilder builder = new StringBuilder();
for (int j = 1; j <= VERIFY_CODE_LEN; j++) {
int randomNum = new Random().nextInt(36);
builder.append("1QAZ2WSX3EDC4RFV5TGB6YHN7UJM8IK9OL0P".charAt(randomNum));
}
return builder.toString();
}
}