Summary of common JavaWeb tool classes and Jar packages:
-
Send mail jar package: mail.jar
Tool class for sending mail: MailUtils
package cn.rg.goods.utils; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; /** * E-mail tool class: dependent on mail.jar */ public final class MailUtils { private static final String USER = "2422737092@qq.com"; // Sender's title, same as email address private static final String PASSWORD = "cfznjonpuhlndhfj"; // If it is a qq mailbox, you can use the client authorization code or login password /** * * @param to Recipient mailbox * @param text Message body * @param title title */ /* Send verification message */ 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"); // Sender's account number props.put("mail.user", USER); //Sender's password props.put("mail.password", PASSWORD); // Build authorization information for SMTP authentication Authenticator authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { // User name and password String userName = props.getProperty("mail.user"); String password = props.getProperty("mail.password"); return new PasswordAuthentication(userName, password); } }; // Create a mail session using environment properties and authorization information Session mailSession = Session.getInstance(props, authenticator); // Create mail message MimeMessage message = new MimeMessage(mailSession); // Set sender String username = props.getProperty("mail.user"); InternetAddress form = new InternetAddress(username); message.setFrom(form); // Set recipient InternetAddress toAddress = new InternetAddress(to); message.setRecipient(Message.RecipientType.TO, toAddress); // Set message header message.setSubject(title); // Set the content body of the message message.setContent(text, "text/html;charset=UTF-8"); // Send mail Transport.send(message); return true; }catch (Exception e){ e.printStackTrace(); } return false; } public static void main(String[] args) throws Exception { // For testing MailUtils.sendMail("2810837342@qq.com","Hello, sand carving sister,I'm sending you an email with code, hahaha.","Test mail"); System.out.println("Sent successfully"); } }
- Tool class for generating 32-bit random numbers: UUIDUtils
package cn.rg.goods.utils; import java.util.UUID; /** * Generate random number tool class */ public class UUIDUtils { /** * Randomly generated id * @return */ //Same user, same uid public static String getId(){ return UUID.randomUUID().toString().replace("-", "").toUpperCase(); } /** * Generate random code * @return */ public static String getCode(){ return getId(); } public static void main(String[] args) { System.out.println(getId()); System.out.println(getCode()); } }
-
CommonUtils: depends on commons-bean utils-1.8.3.jar (depends on commons-io-1.4.jar), so you need to import two packages if you use
package cn.itcast.commons; import java.util.Map; import java.util.UUID; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; /** * Encapsulate common tool classes * @author qdmmy6 * */ public class CommonUtils { /** * Returns a non repeating string * @return */ public static String uuid() { return UUID.randomUUID().toString().replace("-", "").toUpperCase(); } /** * Convert map to object * @param map * @param clazz * @return * * Convert the Map to the specified type */ @SuppressWarnings("rawtypes") public static <T> T toBean(Map map, Class<T> clazz) { try { /* * 1. Create instance with parameter clazz * 2. Use BeanUtils.populate to enclose the map data into the 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); } } }
-
JDBC utils: it is used to simplify the operation of the database. The underlying layer uses c3p0 connection pool and requires mysql driver
Jar packages to be imported: c3p0-0.9.1.2.jar,mchange-commons-0.2.jar,mysql-connector-java-5.1.13-bin.jar
In addition, you need to import the configuration file of the connection pool
package cn.itcast.jdbc; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; /** * To use the methods of this class, you must provide the c3p0-copnfig.xml file * @author qdmmy6 */ public class JdbcUtils { // Hungry Han style private static DataSource ds = new ComboPooledDataSource(); /** * It is null to indicate that there is no transaction * It is not null, indicating that there is a transaction * When a transaction is started, it needs to be assigned a value * When the transaction ends, it needs to be assigned null * When a transaction is started, multiple dao methods share the Connection */ private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); public static DataSource getDataSource() { return ds; } /** * dao Use this method to get the connection * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { /* * If there is a transaction, return the con of the current transaction * If there are no transactions, a new con is returned through the connection pool */ Connection con = tl.get();//Gets the transaction connection of the current thread if(con != null) return con; return ds.getConnection(); } /** * Open transaction * @throws SQLException */ public static void beginTransaction() throws SQLException { Connection con = tl.get();//Gets the transaction connection of the current thread if(con != null) throw new SQLException("Transaction has been started, cannot be started again!"); con = ds.getConnection();//Assign a value to con, indicating that the transaction is started con.setAutoCommit(false);//Set to manual submission tl.set(con);//Put the current transaction connection into tl } /** * Commit transaction * @throws SQLException */ public static void commitTransaction() throws SQLException { Connection con = tl.get();//Gets the transaction connection of the current thread if(con == null) throw new SQLException("Cannot commit without transaction!"); con.commit();//Commit transaction con.close();//Close connection con = null;//Indicates the end of the transaction! tl.remove(); } /** * Rollback transaction * @throws SQLException */ public static void rollbackTransaction() throws SQLException { Connection con = tl.get();//Gets the transaction connection of the current thread if(con == null) throw new SQLException("No transaction can be rolled back!"); con.rollback(); con.close(); con = null; tl.remove(); } /** * Release Connection * @param con * @throws SQLException */ public static void releaseConnection(Connection connection) throws SQLException { Connection con = tl.get();//Gets the transaction connection of the current thread if(connection != con) {//If the parameter connection is different from the current transaction connection, it means that the connection is not the current transaction and can be closed! if(connection != null &&!connection.isClosed()) {//If the parameter connection is not closed, close it! connection.close(); } } } }
JDBC utilstest class:
public class JdbcUtilsTest { /** * Obtain connection objects through C3P0 connection pool * @throws SQLException */ @Test public void testGetConnection() throws SQLException { Connection con = JdbcUtils.getConnection();//Get connection System.out.println(con); JdbcUtils.releaseConnection(con);//If the parameter con is not the connection object of the current thread, close it } /** * When the transaction is started, calling getConnection() will create Connection for the current thread, and multiple calls to getConnection() will return the same object. * @throws SQLException */ @Test public void testTansaction() throws SQLException { JdbcUtils.beginTransaction();//Open transaction Connection c1 = JdbcUtils.getConnection();//Get the transaction connection object of the current thread for the first time Connection c2 = JdbcUtils.getConnection();//Get the transaction connection object of the current thread for the second time Assert.assertEquals(true, c1 == c2);//Whether the two comparisons are the same JdbcUtils.commitTransaction();//Commit transaction } }
-
Common dbutils class
DBUtils encapsulates the operation of JDBC, and its core functions are as follows:
-
The query runner provides API s for sql statement operations
-
ResultSetHandler interface is used to define how to encapsulate the result set after the select operation. It contains the implementation of a large number of result sets
-
The DbUtils class is a tool class that defines methods to close resources and transactions
If you want to use it, you need to import the common-dbutils.jar tool class
TxQueryRunner
TxQueryRunner class is a subclass of QueryRunner class under common dbutils, which is used to simplify JDBC operations. The TxQueryRunner class internally uses the JdbcUtils.getConnection() class to get the connection object, and uses JdbcUtils.releaseConnection() to close the connection.
lint[] batch(String sql, Object[][] params): execute batch processing. The parameter SQL is the SQL statement template and params is the parameter;
T query(String sql, ResultSetHandler rh): execute query, execute query, parameter sql is the query statement template to be executed, and rh is the result set processing, which is used to map the result set to the result you want;
T query(String sql, ResultSetHandler rh, Object... params): execute the query. The parameter sql is the template of the query statement to be executed, rh is the result set processing, which is used to map the result set to the result you want, and params is the parameter of the sql statement;
int update(String sql): execute add, delete and change statements. Parameter SQL is the SQL statement to be executed;
int update(Stringsql, Object param): execute add, delete and change statements. Parameter SQL is the SQL statement to be executed, and parameter param is a parameter (a parameter);
int update(String sql, Object... params): execute add, delete and modify statements. Parameter SQL is the SQL statement to be executed, and parameter params is the parameter (multiple parameters);
-
Coding filter
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);//Process get request encoding } } else { req.setCharacterEncoding(charset);//Process post request encoding } 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) { // Get parameters String value = request.getParameter(name); if(value == null) return null;//If NULL, return null directly try { // Return after encoding the parameter 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; // Traverse the map and encode each value 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 after processing 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 class of one-time verification code:
VerifyCodeServlet: generate a one-time verification code
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();//Get one-time verification code picture // This method must be called after the getImage() method // System.out.println(vc.getText());// Get text on picture VerifyCode.output(image, response.getOutputStream());//Writes the picture to the specified stream // Save the text to the session in preparation for login servlet validation 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(); // {"song style", "Chinese regular script", "bold", "Chinese New Wei", "Chinese official script", "Microsoft YaHei", "regular script _GB2312"} private String[] fontNames = {"Song typeface", "Chinese regular script", "Blackbody", "Microsoft YaHei ", "Regular script_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(); // Draw 4 characters into the picture 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); } }
Generate verification code 2 at one time
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; /** * Verification Code */ @WebServlet("/checkCode") public class CheckCodeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { //The server tells the browser not to cache response.setHeader("pragma","no-cache"); response.setHeader("cache-control","no-cache"); response.setHeader("expires","0"); //Create a picture 80 long and 30 wide in memory, with a default black background //Parameter 1: length //Parameter 2: width //Parameter 3: color int width = 80; int height = 30; BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //Get brush Graphics g = image.getGraphics(); //Set the brush color to gray g.setColor(Color.GRAY); //Fill picture g.fillRect(0,0, width,height); //Generate 4 random verification codes, 12Ey String checkCode = getCheckCode(); //System. Out. Println ("in checkcode:" + checkCode); //Put the verification code into HttpSession request.getSession().setAttribute("CHECKCODE_SERVER",checkCode); //Set the brush color to yellow g.setColor(Color.YELLOW); //Set font size g.setFont(new Font("Blackbody",Font.BOLD,24)); //Write verification code to picture g.drawString(checkCode,15,25); //Output pictures in memory to the browser //Parameter 1: picture object //Parameter 2: image format, such as PNG,JPG,GIF //Parameter 3: where is the picture output ImageIO.write(image,"PNG",response.getOutputStream()); } /** * Generates a 4-bit random string */ 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++){ //Generate random values from 0 to size-1 int index = r.nextInt(size); //Gets the character with index in the base string char c = base.charAt(index); //Put c into StringBuffer sb.append(c); } return sb.toString(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request,response); } }
-
-
8. Database tools:
When transactions are not used: 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; /** * Connection pool tool class (when transactions are not used) */ public class DataSourceUtils { private static ComboPooledDataSource ds=new ComboPooledDataSource(); private static ThreadLocal<Connection> tl=new ThreadLocal<>(); /** * Get data source * @return Connection pool */ public static DataSource getDataSource(){ return ds; } /** * Get connection from thread * @return connect * @throws SQLException */ public static Connection getConnection() throws SQLException{ Connection conn = tl.get(); //If you need to get a connection from the pool for the first time, bind the connection to the current thread if(conn==null){ conn=ds.getConnection(); //Bind this connection to the current thread tl.set(conn); } return conn; } /** * Release resources * * @param conn * connect * @param st * Statement executor * @param rs * Result set */ public static void closeResource(Connection conn, Statement st, ResultSet rs) { closeResultSet(rs); closeStatement(st); closeConn(conn); } /** * Release connection * * @param conn * connect */ public static void closeConn(Connection conn) { if (conn != null) { try { conn.close(); //Unbind with current thread tl.remove(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } } /** * Release statement executor * * @param st * Statement executor */ public static void closeStatement(Statement st) { if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } st = null; } } /** * Release result set * * @param rs * Result set */ public static void closeResultSet(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs = null; } } /** * Start transaction * @throws SQLException */ public static void startTransaction() throws SQLException{ //1. Get connection Connection conn=getConnection(); //2. Start conn.setAutoCommit(false); } /** * Transaction commit */ public static void commitAndClose(){ try { //0. Get connection Connection conn = getConnection(); //1. Submission of services conn.commit(); //2. Close and remove closeConn(conn); } catch (SQLException e) { } } /** * Submit review */ public static void rollbackAndClose(){ try { //0. Get connection Connection conn = getConnection(); //1. Business Review conn.rollback(); //2. Close and remove closeConn(conn); } catch (SQLException e) { } } }
Use transaction
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 Database tool class for transactions * To use the methods of this class, you must provide the c3p0-copnfig.xml file * @author qdmmy6 */ public class JdbcUtils { // Hungry Han style private static DataSource ds = new ComboPooledDataSource(); /** * It is null to indicate that there is no transaction * It is not null, indicating that there is a transaction * When a transaction is started, it needs to be assigned a value * When the transaction ends, it needs to be assigned null * When a transaction is started, multiple dao methods share the Connection */ private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); public static DataSource getDataSource() { return ds; } /** * dao Use this method to get the connection * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { /* * If there is a transaction, return the con of the current transaction * If there are no transactions, a new con is returned through the connection pool */ Connection con = tl.get();//Gets the transaction connection of the current thread if(con != null) return con; return ds.getConnection(); } /** * Open transaction * @throws SQLException */ public static void beginTransaction() throws SQLException { Connection con = tl.get();//Gets the transaction connection of the current thread if(con != null) throw new SQLException("Transaction has been started, cannot be started again!"); con = ds.getConnection();//Assign a value to con, indicating that the transaction is started con.setAutoCommit(false);//Set to manual submission tl.set(con);//Put the current transaction connection into tl } /** * Commit transaction * @throws SQLException */ public static void commitTransaction() throws SQLException { Connection con = tl.get();//Gets the transaction connection of the current thread if(con == null) throw new SQLException("Cannot commit without transaction!"); con.commit();//Commit transaction con.close();//Close connection con = null;//Indicates the end of the transaction! tl.remove(); } /** * Rollback transaction * @throws SQLException */ public static void rollbackTransaction() throws SQLException { Connection con = tl.get();//Gets the transaction connection of the current thread if(con == null) throw new SQLException("No transaction can be rolled back!"); con.rollback(); con.close(); con = null; tl.remove(); } /** * Release Connection * @param con * @throws SQLException */ public static void releaseConnection(Connection connection) throws SQLException { Connection con = tl.get();//Gets the transaction connection of the current thread if(connection != con) {//If the parameter connection is different from the current transaction connection, it means that the connection is not the current transaction and can be closed! if(connection != null &&!connection.isClosed()) {//If the parameter connection is not closed, close it! connection.close(); } } } }