目录
一,项目搭建与工具整理
1,引入数据库相关工具包和工具类
package com.xxy.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import javax.xml.transform.Result;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class DruidUtil {
private static DataSource ds;
static{
try {
Properties ppt = new Properties();
ppt.load(DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(ppt);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 从连接池中取出一个连接给用户
* @return
*/
public static Connection getConnection(){
try {
return ds.getConnection();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
public static void close(Connection conn, Statement state, ResultSet rs){
try {
rs.close();
} catch (Exception throwables) {
throwables.printStackTrace();
}
try {
state.close();
} catch (Exception throwables) {
throwables.printStackTrace();
}
try {
conn.close();
} catch (Exception throwables) {
throwables.printStackTrace();
}
}
}
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8
username=root
password=2017217905
initialSize=5
# 最大连接池数量
maxActive=10
# 最小连接池数量
minIdle=5
# 获取连接时最大等待时间,单位毫秒
maxWait=5000
2,编写其他工具类
DateFormatUtil
package com.xxy.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatUtil {
private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static String format(Date date) {
return format.format(date);
}
}
bean目录中创建Message类
package com.xxy.bean;
public class Message {
// {status:0, result:"", data:{}}
// 状态码 0成功 -1失败
private int status;
// 消息内容
private String result;
// 消息携带的数据
private Object data;
public Message(int status, String result, Object data) {
this.status = status;
this.result = result;
this.data = data;
}
public Message() {
}
public Message(int status) {
this.status = status;
}
public Message(String result) {
this.result = result;
}
public Message(int status, String result) {
this.status = status;
this.result = result;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
JSONUtil
需要在lib中引入两个工具包:
package com.xxy.util;
import com.google.gson.Gson;
public class JSONUtil {
private static Gson g;
public static String toJSON(Object obj) {
return g.toJson(obj);
}
}