1. jdbc工具类,获取连接池中的连接工具类(不包括事务的处理)
package jdbc;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JdbcUtils {
//饿汉式(避免同步问题)
private static DataSource ds = new ComboPooledDataSource();
/**
* 获取dataSourse
* @return
*/
public static DataSource getDataSource() {
return ds;
}
/**
* 获取连接
* @return
* @throws SQLException
*/
public static Connection getConection() throws SQLException{
return ds.getConnection();
}
}
2.CommonUtils(生成32位随机字符、Map转javabean)
package commons;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.beanutils.BeanUtils;
/**
* 小小工具1
* @author J
*
*/
public class CommonUtils {
/**
* 得到一个32不重复的字符串,可用作主键
* @return
*/
public static String uuuid() {
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
/**
* 把map转换成指定的类型
* @param map
* @param clazz
* @return
*/
@SuppressWarnings({ "rawtypes", "deprecation" })
public static <T> T mapToBean(Map map,Class<T> clazz) {
try {
//创建实例(T为可变实体类)
T bean = clazz.newInstance();
BeanUtils.populate(bean, map);
return bean;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
3.BaseServlet(处理网页请求,简化servlet操作)
package Servlet;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 作为其他servlet的父类
* @author J
* 原型 = 返回值类型 + 方法名称 + 参数列表
*/
@SuppressWarnings("serial")
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* 1.获得method参数,该参数就是想要调用的方法名
*/
String methodName = request.getParameter("method");
Method method = null;
try {
/**
* 2.通过方法名称获取Method对象
*/
method = this.getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("调用的"+methodName+"不存在!");
}
/**
* 通过method对象来调用方法
*/
try {
String returnvalue = (String) method.invoke(this, request, response);
if(returnvalue != null && !returnvalue.trim().isEmpty()) {
String[] values = returnvalue.split(":");
// f:重定向 r:转发
if(values[0].equals("f")) {
/**
* 重定向
*/
request.getRequestDispatcher(values[1]).forward(request, response);
}else if(values[0].equals("r")){
/**
* 转发
*/
response.sendRedirect(request.getContextPath()+values[1]);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
4.jar生成方式
1.项目右键–>export–>java–>JAR–>选择要生成jar包的pageage
5.jar包使用(百度均可免费找到)
c3p0-0.9.2.1.jar
commons-beanutils-1.8.3.jar
commons-logging-1.1.1.jar
mchange-commons-java-0.2.3.4.jar
mysql-connector-java-5.1.39-bin.jar