JavaWeb常用工具类以及Jar包总结:
-
发送邮件jar包:mail.jar
发送邮件的工具类:MailUtils
package cn.rg.goods.utils;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
/**
* 发邮件工具类:依赖于mail.jar
*/
public final class MailUtils {
private static final String USER = "2422737092@qq.com"; // 发件人称号,同邮箱地址
private static final String PASSWORD = "cfznjonpuhlndhfj"; // 如果是qq邮箱可以使户端授权码,或者登录密码
/**
*
* @param to 收件人邮箱
* @param text 邮件正文
* @param title 标题
*/
/* 发送验证信息的邮件 */
public static boolean sendMail(String to, String text, String title){
try {
final Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.qq.com");
// 发件人的账号
props.put("mail.user", USER);
//发件人的密码
props.put("mail.password", PASSWORD);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
// 使用环境属性和授权信息,创建邮件会话
Session mailSession = Session.getInstance(props, authenticator);
// 创建邮件消息
MimeMessage message = new MimeMessage(mailSession);
// 设置发件人
String username = props.getProperty("mail.user");
InternetAddress form = new InternetAddress(username);
message.setFrom(form);
// 设置收件人
InternetAddress toAddress = new InternetAddress(to);
message.setRecipient(Message.RecipientType.TO, toAddress);
// 设置邮件标题
message.setSubject(title);
// 设置邮件的内容体
message.setContent(text, "text/html;charset=UTF-8");
// 发送邮件
Transport.send(message);
return true;
}catch (Exception e){
e.printStackTrace();
}
return false;
}
public static void main(String[] args) throws Exception { // 做测试用
MailUtils.sendMail("2810837342@qq.com","你好啊,沙雕妹,我正在用代码给你发送邮件哈哈哈。","测试邮件");
System.out.println("发送成功");
}
}
- 生成32位随机数的工具类:UUIDUtils
package cn.rg.goods.utils;
import java.util.UUID;
/**
* 生成随机数工具类
*/
public class UUIDUtils {
/**
* 随机生成id
* @return
*/
//同一个用户同一个uid
public static String getId(){
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
/**
* 生成随机码
* @return
*/
public static String getCode(){
return getId();
}
public static void main(String[] args) {
System.out.println(getId());
System.out.println(getCode());
}
}
-
CommonUtils:依赖于 commons-beanutils-1.8.3.jar(依赖于commons-io-1.4.jar),所以如果使用需要导入两个包
package cn.itcast.commons; import java.util.Map; import java.util.UUID; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; /** * 对于常用的工具类进行封装 * @author qdmmy6 * */ public class CommonUtils { /** * 返回一个不重复的字符串 * @return */ public static String uuid() { return UUID.randomUUID().toString().replace("-", "").toUpperCase(); } /** * 把map转换成对象 * @param map * @param clazz * @return * * 把Map转换成指定类型 */ @SuppressWarnings("rawtypes") public static <T> T toBean(Map map, Class<T> clazz) { try { /* * 1. 通过参数clazz创建实例 * 2. 使用BeanUtils.populate把map的数据封闭到bean中 */ T bean = clazz.newInstance(); ConvertUtils.register(new DateConverter(), java.util.Date.class); BeanUtils.populate(bean, map); return bean; } catch(Exception e) { throw new RuntimeException(e); } } }
-
JDBCUtils:用来简化对数据库的操作,底层使用了c3p0连接池,同时还需要mysql驱动
需要导入的jar包:c3p0-0.9.1.2.jar,mchange-commons-0.2.jar,mysql-connector-java-5.1.13-bin.jar
另外还需要导入连接池的配置文件.
package cn.itcast.jdbc; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * 使用本类的方法,必须提供c3p0-copnfig.xml文件 * @author qdmmy6 */ public class JdbcUtils { // 饿汉式 private static DataSource ds = new ComboPooledDataSource(); /** * 它为null表示没有事务 * 它不为null表示有事务 * 当开启事务时,需要给它赋值 * 当结束事务时,需要给它赋值为null * 并且在开启事务时,让dao的多个方法共享这个Connection */ private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); public static DataSource getDataSource() { return ds; } /** * dao使用本方法来获取连接 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { /* * 如果有事务,返回当前事务的con * 如果没有事务,通过连接池返回新的con */ Connection con = tl.get();//获取当前线程的事务连接 if(con != null) return con; return ds.getConnection(); } /** * 开启事务 * @throws SQLException */ public static void beginTransaction() throws SQLException { Connection con = tl.get();//获取当前线程的事务连接 if(con != null) throw new SQLException("已经开启了事务,不能重复开启!"); con = ds.getConnection();//给con赋值,表示开启了事务 con.setAutoCommit(false);//设置为手动提交 tl.set(con);//把当前事务连接放到tl中 } /** * 提交事务 * @throws SQLException */ public static void commitTransaction() throws SQLException { Connection con = tl.get();//获取当前线程的事务连接 if(con == null) throw new SQLException("没有事务不能提交!"); con.commit();//提交事务 con.close();//关闭连接 con = null;//表示事务结束! tl.remove(); } /** * 回滚事务 * @throws SQLException */ public static void rollbackTransaction() throws SQLException { Connection con = tl.get();//获取当前线程的事务连接 if(con == null) throw new SQLException("没有事务不能回滚!"); con.rollback(); con.close(); con = null; tl.remove(); } /** * 释放Connection * @param con * @throws SQLException */ public static void releaseConnection(Connection connection) throws SQLException { Connection con = tl.get();//获取当前线程的事务连接 if(connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭! if(connection != null &&!connection.isClosed()) {//如果参数连接没有关闭,关闭之! connection.close(); } } } }
JDBCUTilsTest类:
public class JdbcUtilsTest { /** * 通过C3P0连接池获取连接对象 * @throws SQLException */ @Test public void testGetConnection() throws SQLException { Connection con = JdbcUtils.getConnection();//获取连接 System.out.println(con); JdbcUtils.releaseConnection(con);//如果参数con不是当前线程的连接对象,那么关闭之 } /** * 当开始事务后,调用getConnection()会为当前线程创建Connection,而且多次调用getConnection()返回的是同一个对象 * @throws SQLException */ @Test public void testTansaction() throws SQLException { JdbcUtils.beginTransaction();//开启事务 Connection c1 = JdbcUtils.getConnection();//第一次获取当前线程的事务连接对象 Connection c2 = JdbcUtils.getConnection();//第二次获取当前线程的事务连接对象 Assert.assertEquals(true, c1 == c2);//比较两次是否相同 JdbcUtils.commitTransaction();//提交事务 } }
-
common-dbutils类
DBUtils封装了JDBC的操作,核心功能如下:
-
QueryRunner
中提供对sql语句操作的API. -
ResultSetHandler
接口,用于定义select操作后,怎样封装结果集.包含大量结果集的实现 -
DbUtils类是一个工具类,定义了关闭资源与事务处理的方法
使用的话需要导入common-dbutils.jar工具类
TxQueryRunner
TxQueryRunner类是common-dbutils下QueryRunner类的子类,用来简化JDBC操作。TxQueryRunner类内部使用了JdbcUtils.getConnection()类来获取连接对象,以及使用JdbcUtils.releaseConnection()关闭连接。
lint[] batch(String sql, Object[][] params):执行批处理,参数sql是SQL语句模板,params为参数;
T query(String sql, ResultSetHandler rh):执行查询,执行查询,参数sql为要执行的查询语句模板,rh是结果集处理,用来把结果集映射成你想要的结果;
T query(String sql, ResultSetHandler rh, Object… params):执行查询,参数sql为要执行的查询语句模板,rh是结果集处理,用来把结果集映射成你想要的结果,params是sql语句的参数;
int update(String sql):执行增、删、改语句,参数sql是要执行的SQL语句;
int update(Stringsql, Object param):执行增、删、改语句,参数sql是要执行的SQL语句,参数param是参数(一个参数);
int update(String sql, Object… params):执行增、删、改语句,参数sql是要执行的SQL语句,参数params是参数(多个参数);
-
编码过滤器
package cn.rg.goods.web.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; public class EncodingFilter implements Filter { private String charset = "UTF-8"; @Override public void destroy() {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; if(req.getMethod().equalsIgnoreCase("GET")) { if(!(req instanceof GetRequest)) { req = new GetRequest(req, charset);//处理get请求编码 } } else { req.setCharacterEncoding(charset);//处理post请求编码 } chain.doFilter(req, response); } @Override public void init(FilterConfig fConfig) throws ServletException { String charset = fConfig.getInitParameter("charset"); if(charset != null && !charset.isEmpty()) { this.charset = charset; } } } class GetRequest extends HttpServletRequestWrapper { private HttpServletRequest request; private String charset; public GetRequest(HttpServletRequest request, String charset) { super(request); this.request = request; this.charset = charset; } @Override public String getParameter(String name) { // 获取参数 String value = request.getParameter(name); if(value == null) return null;//如果为null,直接返回null try { // 对参数进行编码处理后返回 return new String(value.getBytes("ISO-8859-1"), charset); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Map getParameterMap() { Map<String,String[]> map = request.getParameterMap(); if(map == null) return map; // 遍历map,对每个值进行编码处理 for(String key : map.keySet()) { String[] values = map.get(key); for(int i = 0; i < values.length; i++) { try { values[i] = new String(values[i].getBytes("ISO-8859-1"), charset); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } } // 处理后返回 return map; } @Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); for(int i = 0; i < values.length; i++) { try { values[i] = new String(values[i].getBytes("ISO-8859-1"), charset); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } return values; } }
7.一次性验证码的Servlet类:
VerifyCodeServlet:生成一次性验证码
package cn.rg.goods.web.servlet; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Random; @WebServlet("/verifyCodeServlet") public class VerifyCodeServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { VerifyCode vc = new VerifyCode(); BufferedImage image = vc.getImage();//获取一次性验证码图片 // 该方法必须在getImage()方法之后来调用 // System.out.println(vc.getText());//获取图片上的文本 VerifyCode.output(image, response.getOutputStream());//把图片写到指定流中 // 把文本保存到session中,为LoginServlet验证做准备 request.getSession().setAttribute("vCode", vc.getText()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } } class VerifyCode { private int w = 70; private int h = 35; private Random r = new Random(); // {"宋体", "华文楷体", "黑体", "华文新魏", "华文隶书", "微软雅黑", "楷体_GB2312"} private String[] fontNames = {"宋体", "华文楷体", "黑体", "微软雅黑", "楷体_GB2312"}; private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ"; private Color bgColor = new Color(255, 255, 255); private String text ; private Color randomColor () { int red = r.nextInt(150); int green = r.nextInt(150); int blue = r.nextInt(150); return new Color(red, green, blue); } private Font randomFont () { int index = r.nextInt(fontNames.length); String fontName = fontNames[index]; int style = r.nextInt(4); int size = r.nextInt(5) + 24; return new Font(fontName, style, size); } private void drawLine (BufferedImage image) { int num = 3; Graphics2D g2 = (Graphics2D)image.getGraphics(); for(int i = 0; i < num; i++) { int x1 = r.nextInt(w); int y1 = r.nextInt(h); int x2 = r.nextInt(w); int y2 = r.nextInt(h); g2.setStroke(new BasicStroke(1.5F)); g2.setColor(Color.BLUE); g2.drawLine(x1, y1, x2, y2); } } private char randomChar () { int index = r.nextInt(codes.length()); return codes.charAt(index); } private BufferedImage createImage () { BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = (Graphics2D)image.getGraphics(); g2.setColor(this.bgColor); g2.fillRect(0, 0, w, h); return image; } public BufferedImage getImage () { BufferedImage image = createImage(); Graphics2D g2 = (Graphics2D)image.getGraphics(); StringBuilder sb = new StringBuilder(); // 向图片中画4个字符 for(int i = 0; i < 4; i++) { String s = randomChar() + ""; sb.append(s); float x = i * 1.0F * w / 4; g2.setFont(randomFont()); g2.setColor(randomColor()); g2.drawString(s, x, h-5); } this.text = sb.toString(); drawLine(image); return image; } public String getText () { return text; } public static void output (BufferedImage image, OutputStream out) throws IOException { ImageIO.write(image, "JPEG", out); } }
一次性生成验证码2
package cn.rg.web.Servlet; import javax.imageio.ImageIO; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; /** * 验证码 */ @WebServlet("/checkCode") public class CheckCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //服务器通知浏览器不要缓存 response.setHeader("pragma","no-cache"); response.setHeader("cache-control","no-cache"); response.setHeader("expires","0"); //在内存中创建一个长80,宽30的图片,默认黑色背景 //参数一:长 //参数二:宽 //参数三:颜色 int width = 80; int height = 30; BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //获取画笔 Graphics g = image.getGraphics(); //设置画笔颜色为灰色 g.setColor(Color.GRAY); //填充图片 g.fillRect(0,0, width,height); //产生4个随机验证码,12Ey String checkCode = getCheckCode(); //System.out.println("checkCode中的:"+checkCode); //将验证码放入HttpSession中 request.getSession().setAttribute("CHECKCODE_SERVER",checkCode); //设置画笔颜色为黄色 g.setColor(Color.YELLOW); //设置字体的小大 g.setFont(new Font("黑体",Font.BOLD,24)); //向图片上写入验证码 g.drawString(checkCode,15,25); //将内存中的图片输出到浏览器 //参数一:图片对象 //参数二:图片的格式,如PNG,JPG,GIF //参数三:图片输出到哪里去 ImageIO.write(image,"PNG",response.getOutputStream()); } /** * 产生4位随机字符串 */ private String getCheckCode() { String base = "0123456789ABCDEFGabcdefg"; int size = base.length(); Random r = new Random(); StringBuffer sb = new StringBuffer(); for(int i=1;i<=4;i++){ //产生0到size-1的随机值 int index = r.nextInt(size); //在base字符串中获取下标为index的字符 char c = base.charAt(index); //将c放入到StringBuffer中去 sb.append(c); } return sb.toString(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } }
-
-
8.数据库工具类:
当不使用事务时:DataSourceUtils
package cn.rg.goods.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* 连接池工具类 (不使用事务时候)
*/
public class DataSourceUtils {
private static ComboPooledDataSource ds=new ComboPooledDataSource();
private static ThreadLocal<Connection> tl=new ThreadLocal<>();
/**
* 获取数据源
* @return 连接池
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 从线程中获取连接
* @return 连接
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
Connection conn = tl.get();
//若是第一次获取 需要从池中获取一个连接,将这个连接和当前线程绑定
if(conn==null){
conn=ds.getConnection();
//将这个连接和当前线程绑定
tl.set(conn);
}
return conn;
}
/**
* 释放资源
*
* @param conn
* 连接
* @param st
* 语句执行者
* @param rs
* 结果集
*/
public static void closeResource(Connection conn, Statement st, ResultSet rs) {
closeResultSet(rs);
closeStatement(st);
closeConn(conn);
}
/**
* 释放连接
*
* @param conn
* 连接
*/
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
//和当前线程解绑
tl.remove();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
/**
* 释放语句执行者
*
* @param st
* 语句执行者
*/
public static void closeStatement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
}
}
/**
* 释放结果集
*
* @param rs
* 结果集
*/
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
}
/**
* 开始事务
* @throws SQLException
*/
public static void startTransaction() throws SQLException{
//1.获取连接
Connection conn=getConnection();
//2.开始
conn.setAutoCommit(false);
}
/**
* 事务提交
*/
public static void commitAndClose(){
try {
//0.获取连接
Connection conn = getConnection();
//1.提交事务
conn.commit();
//2.关闭且移除
closeConn(conn);
} catch (SQLException e) {
}
}
/**
* 提交回顾
*/
public static void rollbackAndClose(){
try {
//0.获取连接
Connection conn = getConnection();
//1.事务回顾
conn.rollback();
//2.关闭且移除
closeConn(conn);
} catch (SQLException e) {
}
}
}
使用事务
JdbcUtils
package cn.rg.goods.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* C3P0的数据库工具类,适用事务
* 使用本类的方法,必须提供c3p0-copnfig.xml文件
* @author qdmmy6
*/
public class JdbcUtils {
// 饿汉式
private static DataSource ds = new ComboPooledDataSource();
/**
* 它为null表示没有事务
* 它不为null表示有事务
* 当开启事务时,需要给它赋值
* 当结束事务时,需要给它赋值为null
* 并且在开启事务时,让dao的多个方法共享这个Connection
*/
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
public static DataSource getDataSource() {
return ds;
}
/**
* dao使用本方法来获取连接
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
/*
* 如果有事务,返回当前事务的con
* 如果没有事务,通过连接池返回新的con
*/
Connection con = tl.get();//获取当前线程的事务连接
if(con != null) return con;
return ds.getConnection();
}
/**
* 开启事务
* @throws SQLException
*/
public static void beginTransaction() throws SQLException {
Connection con = tl.get();//获取当前线程的事务连接
if(con != null) throw new SQLException("已经开启了事务,不能重复开启!");
con = ds.getConnection();//给con赋值,表示开启了事务
con.setAutoCommit(false);//设置为手动提交
tl.set(con);//把当前事务连接放到tl中
}
/**
* 提交事务
* @throws SQLException
*/
public static void commitTransaction() throws SQLException {
Connection con = tl.get();//获取当前线程的事务连接
if(con == null) throw new SQLException("没有事务不能提交!");
con.commit();//提交事务
con.close();//关闭连接
con = null;//表示事务结束!
tl.remove();
}
/**
* 回滚事务
* @throws SQLException
*/
public static void rollbackTransaction() throws SQLException {
Connection con = tl.get();//获取当前线程的事务连接
if(con == null) throw new SQLException("没有事务不能回滚!");
con.rollback();
con.close();
con = null;
tl.remove();
}
/**
* 释放Connection
* @param con
* @throws SQLException
*/
public static void releaseConnection(Connection connection) throws SQLException {
Connection con = tl.get();//获取当前线程的事务连接
if(connection != con) {//如果参数连接,与当前事务连接不同,说明这个连接不是当前事务,可以关闭!
if(connection != null &&!connection.isClosed()) {//如果参数连接没有关闭,关闭之!
connection.close();
}
}
}
}