Connection conn = tl.get();
if(conn==null){
conn=ds.getConnection();
//和当前线程绑定
tl.set(conn);
}
return conn;
}
// 获取数据源
public static DataSource getDataSource() {
return ds;
}
// 释放资源
public static void closeResource( Statement st, ResultSet rs) {
closeResultSet(rs);
closeStatement(st);
}
// 释放资源
public static void closeResource(Connection conn, Statement st, ResultSet rs) {
closeResource(st, rs);
closeConn(conn);
}
// 释放 connection
public static void closeConn(Connection conn) {
if (conn != null) {
try {
conn.close();
//和线程解绑
tl.remove();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
// 释放 statement ctrl + shift + f 格式化代码
public static void closeStatement(Statement st) {
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
st = null;
}
}
// 释放结果集
public static void closeResultSet(ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
}
//开启事务
public static void startTransaction() throws SQLException{
getConnection().setAutoCommit(false);
}
/**
- 事务提交且释放连接
*/
public static void commitAndClose(){
Connection conn = null;
try {
conn=getConnection();
//事务提交
conn.commit();
//关闭资源
conn.close();
//解除版定
tl.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
- 事务回滚且释放资源
*/
public static void rollbackAndClose(){
Connection conn = null;
try {
conn=getConnection();
//事务回滚
conn.rollback();
//关闭资源
conn.close();
//解除版定
tl.remove();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
System.out.println(getConnection().toString());
}
}
package cn.itzheng.store.utils;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class MailUtils {
public static void sendMail(String email, String emailMsg)
throws AddressException, MessagingException {
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
//设置发送的协议
//props.setProperty(“mail.transport.protocol”, “SMTP”);
//设置发送邮件的服务器
//props.setProperty(“mail.host”, “smtp.126.com”);
//props.setProperty(“mail.smtp.auth”, “true”);// 指定验证为true
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
//设置发送人的帐号和密码
return new PasswordAuthentication(“admin”, “admin@store.com”);
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
//设置发送者
message.setFrom(new InternetAddress(“admin@store.com”));
//设置发送方式与接收者
message.setRecipient(RecipientType.TO, new InternetAddress(email));
//设置邮件主题
message.setSubject(“用户激活”);
// message.setText(“这是一封激活邮件,请点击”);
String url=“http://localhost:8080/MyTomcat/UserServlet?method=active&code=”+emailMsg;
String content=“
来自购物天堂的激活邮件!激活请点击以下链接!
”+url+“
”;//设置邮件内容
message.setContent(content, “text/html;charset=utf-8”);
// 3.创建 Transport用于将邮件发送
Transport.send(message);
}
public static void main(String[] args) throws AddressException, MessagingException {
MailUtils.sendMail(“aaa@store.com”, “abcdefg”);
}
}
package cn.itzheng.store.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
/**
- 使用md5的算法进行加密
*/
public static String md5(String plainText) {
byte[] secretBytes = null;
try {
secretBytes = MessageDigest.getInstance(“md5”).digest(
plainText.getBytes());
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(“没有md5这个算法!”);
}
String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
// 如果生成数字未满32位,需要前面补0
for (int i = 0; i < 32 - md5code.length(); i++) {
md5code = “0” + md5code;
}
return md5code;
}
}
package cn.itzheng.store.utils;
import java.util.Map;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;
public class MyBeanUtils {
public static void populate(Object obj, Map<String, String[]> map) {
try {
// 由于BeanUtils将字符串"1992-3-3"向user对象的setBithday();方法传递参数有问题,手动向BeanUtils注册一个时间类型转换器
// 1_创建时间类型的转换器
DateConverter dt = new DateConverter();
// 2_设置转换的格式
dt.setPattern(“yyyy-MM-dd”);
// 3_注册转换器
ConvertUtils.register(dt, java.util.Date.class);
BeanUtils.populate(obj, map);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static T populate(Class clazz, Map<String, String[]> map) {
try {
T obj=clazz.newInstance();
// 由于BeanUtils将字符串"1992-3-3"向user对象的setBithday();方法传递参数有问题,手动向BeanUtils注册一个时间类型转换器
// 1_创建时间类型的转换器
DateConverter dt = new DateConverter();
// 2_设置转换的格式
dt.setPattern(“yyyy-MM-dd”);
// 3_注册转换器
ConvertUtils.register(dt, java.util.Date.class);
BeanUtils.populate(obj, map);
return obj;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
package cn.itzheng.store.utils;
import java.util.UUID;
public class UploadUtils {
/**
-
获取随机名称
-
@param realName 真实名称
-
@return uuid
*/
public static String getUUIDName(String realName){
//realname 可能是 1.jpg 也可能是 1
//获取后缀名
int index = realName.lastIndexOf(“.”);
if(index==-1){
return UUID.randomUUID().toString().replace(“-”, “”).toUpperCase();
}else{
return UUID.randomUUID().toString().replace(“-”, “”).toUpperCase()+realName.substring(index);
}
}
/**
-
获取文件真实名称
-
@param name
-
@return
*/
public static String getRealName(String name){
// c:/upload/1.jpg 1.jpg
//获取最后一个"/"
int index = name.lastIndexOf(“\”);
return name.substring(index+1);
}
/**
-
获取文件目录
-
@param name 文件名称
-
@return 目录
*/
public static String getDir(String name){
int i = name.hashCode();
String hex = Integer.toHexString(i);
int j=hex.length();
for(int k=0;k<8-j;k++){
hex=“0”+hex;
}
return “/”+hex.charAt(0)+“/”+hex.charAt(1);
}
@SuppressWarnings(“unused”)
public static void main(String[] args) {
//String s=“G:\day17-基础加强\resource\1.jpg”;
String s=“1.jgp”;
String realName = getRealName(s);
//System.out.println(realName);
String uuidName = getUUIDName(realName);
//System.out.println(uuidName);
String dir = getDir(realName);
System.out.println(dir);
}
}
package cn.itzheng.store.utils;
import java.util.UUID;
public class UUIDUtils {
/**
-
随机生成id
-
@return
*/
public static String getId() {
return UUID.randomUUID().toString().replace(“-”, “”).toUpperCase();
}
public static String getUUID64() {
return getId() + getId();
}
/**
-
生成随机码
-
@return
*/
public static String getCode() {
return getId();
}
public static void main(String[] args) {
System.out.println(getId());
/*
- String str = UUID.randomUUID().toString(); System.out.println(str);
*/
}
}
c3p0配置文件
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/store_40
root
root
30000
30
10
30
100
10
200
10
1
0
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/store_40
root
root
5
20
10
40
0
5
导入最后一个工具类解决编码乱码的问题,导入到filter
package cn.itzheng.store.web.filter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
/**
-
统一编码
-
@author Administrator
*/
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
//1.强转
HttpServletRequest request=(HttpServletRequest) req;
HttpServletResponse response=(HttpServletResponse) resp;
//System.out.println(“@@@@@@@@@@@@@@@@@@”);
//2.放行
chain.doFilter(new MyRequest(request), response);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
//之前的MyRequest增强了request.getParameter(“name”);方法
//增强了所有的获取参数的方法request.getParameterValues(“name”);
//增强了所有的获取参数的方法request.getParameterMap();
class MyRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
private boolean flag=true;
public MyRequest(HttpServletRequest request) {
super(request);
this.request=request;
}
@Override
public String getParameter(String name) {
if(name==null || name.trim().length()==0){
return null;
}
String[] values = getParameterValues(name);
if(valuesnull || values.length0){
return null;
}
return values[0];
}
@Override
/**
- hobby=[eat,drink]
*/
public String[] getParameterValues(String name) {
if(name==null || name.trim().length()==0){
return null;
}
Map<String, String[]> map = getParameterMap();
if(map==null || map.size()==0){
return null;
}
return map.get(name);
}
@Override
/**
- map{ username=[tom],password=[123],hobby=[eat,drink]}
*/
public Map<String,String[]> getParameterMap() {
/**
-
首先判断请求方式
-
若为post request.setchar…(utf-8)
-
若为get 将map中的值遍历编码就可以了
*/
String method = request.getMethod();
if(“post”.equalsIgnoreCase(method)){
try {
request.setCharacterEncoding(“utf-8”);
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(“get”.equalsIgnoreCase(method)){
Map<String,String[]> map = request.getParameterMap();
if(flag){
for (String key:map.keySet()) {
String[] arr = map.get(key);
//继续遍历数组
for(int i=0;i<arr.length;i++){
//编码
try {
arr[i]=new String(arr[i].getBytes(“iso-8859-1”),“utf-8”);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
flag=false;
}
//需要遍历map 修改value的每一个数据的编码
return map;
}
return super.getParameterMap();
}
}
配置过滤器对应的web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xmlns=“http://java.sun.com/xml/ns/javaee”
xsi:schemaLocation=“http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd”