工厂模式
用户
package com.liu.entity;
import java.io.Serializable;
import java.util.Date;
public class UserBean implements Serializable{
private static final long serialVersionUID = 6507691697025137000L;
private Long id;
private String username;
private transient String password;
private Boolean sex;
private Date brith;
private Double salary;
@Override
public String toString() {
return "UserBean [id=" + id + ", username=" + username + ", sex=" + sex + ", brith=" + brith + ", salary="
+ salary + "]";
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getSex() {
return sex;
}
public void setSex(Boolean sex) {
this.sex = sex;
}
public Date getBrith() {
return brith;
}
public void setBrith(Date brith) {
this.brith = brith;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
定义接口
package com.liu.dao;
import java.util.List;
import com.liu.entity.UserBean;
import com.liu.page.PageBean;
public interface IuserDao {
public boolean save(UserBean user) throws Exception;
public boolean existName(String username) throws Exception;
public List<UserBean> selectAll(PageBean pages)throws Exception;
}
接口实现类
package com.liu.entity;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.liu.dao.IuserDao;
import com.liu.page.PageBean;
import com.liu.util.JdbcUtil;
import com.liu.util.StringUtil;
public class UserDaoImpl implements IuserDao {
private JdbcUtil ju = JdbcUtil.getInstance();
// public static void main(String[] args) throws Exception {
// IuserDao userdao=DaoFactory.getUserDao();
// //UserBean user = new UserBean();
// PageBean pages=new PageBean();
// pages.setRowsPerPage(2);
// pages.setPageNum(1);
// List<UserBean> list=userdao.selectAll(pages);
// System.out.println(pages);
// System.out.println();
// list.forEach(System.out::println);
// }
@Override
public boolean save(UserBean user) throws Exception {
if (user == null)
throw new IllegalAccessException("参数错误!");
if (StringUtil.isBlank(user.getUsername()) || StringUtil.isBlank(user.getPassword()))
throw new IllegalAccessException("参数错误!");
if (!StringUtil.validatelength(user.getUsername(), 6, 20)) {
// throw new IllegalArgumentException("参数错误!");
System.out.println("格式不合法");
return false;
}
if (!StringUtil.validatelength(user.getPassword(), 6, 20)) {
// throw new IllegalArgumentException("参数错误!");
System.out.println("格式不合法");
return false;
}
List<Object> params = new ArrayList<>();
StringBuilder sb1 = new StringBuilder("insert into t_users(username,password");
StringBuilder sb2 = new StringBuilder(") values(?,?");
params.add(user.getUsername());
params.add(user.getPassword());
if (user.getSex() != null) {
sb1.append(",sex");
sb2.append(",?");
params.add(user.getSex());
}
if (user.getBrith() != null) {
sb1.append(",brith");
sb2.append(",?");
params.add(new java.sql.Date(user.getBrith().getTime()));
}
String sql = sb1.toString() + sb2.toString() + ")";
// System.out.println(sql);
// for (Object object : params) {
// System.out.println("\t\t" + object);
// }
boolean res = false;
Connection conn = null;
PreparedStatement ps = null;
try {
conn = ju.getConnection();
int len = ju.executeUpdate(conn, sql, params.toArray());
res = len > 0;
} finally {
ju.close(null, ps, conn);
}
return res;
}
@Override
public boolean existName(String username) throws Exception {
boolean res = false;
Connection conn = null;
ResultSet rs = null;
try {
conn = ju.getConnection();
rs = ju.executeQuery(conn, "select * from t_users where username=?", username);
res = rs.next();
} finally {
ju.close(rs, null, conn);
}
return res;
}
@SuppressWarnings("resource")
@Override
public List<UserBean> selectAll(PageBean pages) throws Exception {
List<UserBean> res = new ArrayList<>();
String sql = "select * from t_users";
List<Object> param = new ArrayList<>();
Connection conn = null;
ResultSet rs = null;
try {
conn = ju.getConnection();
if (pages != null && pages.getRowsPerPage() > 0) {
if (pages.getMaxPage() < 1) {
String ss = "select count(*) " + sql.substring(sql.indexOf(" from "));
rs = ju.executeQuery(conn, ss, param.toArray());
int rowsNum = 0;
if (rs.next())
rowsNum = rs.getInt(1);
if (rowsNum < 1)
return res;
int maxPage = rowsNum / pages.getRowsPerPage();
if (rowsNum % pages.getRowsPerPage() != 0)
maxPage++;
pages.setRowsNum(rowsNum);
pages.setMaxPage(maxPage);
}
if (pages.getPageNum() > pages.getMaxPage())
pages.setPageNum(pages.getMaxPage());
if (pages.getPageNum() < 1)
pages.setPageNum(1);
int begin = (pages.getPageNum() - 1) * pages.getRowsPerPage();
sql = sql + " limit " + begin + "," + pages.getRowsPerPage();
}
rs = ju.executeQuery(conn, sql, param.toArray());
while (rs.next()) {
UserBean temp = new UserBean();
temp.setId(rs.getLong("id"));
temp.setUsername(rs.getString("username"));
temp.setPassword(rs.getString("password"));
temp.setBrith(rs.getDate("brith"));
temp.setSex(rs.getBoolean("sex"));
temp.setSalary(rs.getDouble("salary"));
res.add(temp);
}
} finally {
ju.close(rs, null, conn);
}
return res;
}
}
分页
package com.liu.page;
import java.io.Serializable;
public class PageBean implements Serializable{
private int pageNum;//当前页码值
private int maxPage;//最大页码值
private int rowsNum;//总行数
private int rowsPerPage;//每页行数
@Override
public String toString() {
return "PageBean [pageNum=" + pageNum + ", maxPage=" + maxPage + ", rowsNum=" + rowsNum + ", rowsPerPage="
+ rowsPerPage + "]";
}
public int getPageNum() {
return pageNum;
}
public void setPageNum(int pageNum) {
this.pageNum = pageNum;
}
public int getMaxPage() {
return maxPage;
}
public void setMaxPage(int maxPage) {
this.maxPage = maxPage;
}
public int getRowsNum() {
return rowsNum;
}
public void setRowsNum(int rowsNum) {
this.rowsNum = rowsNum;
}
public int getRowsPerPage() {
return rowsPerPage;
}
public void setRowsPerPage(int rowsPerPage) {
this.rowsPerPage = rowsPerPage;
}
}
JDBC代码块
package com.liu.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class JdbcUtil {
private JdbcUtil() {
}
private static JdbcUtil ju = new JdbcUtil();
public static JdbcUtil getInstance() {
return ju;
}
private static List<Connection> pool;
private static final int MAX_SIZE = 10;
static {
pool = Collections.synchronizedList(new ArrayList<>());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
for (int i = 0; i < 3; i++) {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC",
"root", "123456");
pool.add(conn);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getConnection() throws Exception {
Connection conn = null;
if (pool.size() > 0)
conn = pool.remove(pool.size() - 1);
else
conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=UTC", "root", "123456");
return conn;
}
//连接使用完毕不是关闭连接,而是释放连接到连接池中。
public void realseConnection(Connection conn) throws Exception {
if (conn != null)
if (pool.size() < MAX_SIZE)
pool.add(conn);
else
conn.close();
}
public void close(ResultSet rs, PreparedStatement ps, Connection conn) throws Exception {
try {
if (rs != null)
rs.close();
} finally {
try {
if (ps != null)
ps.close();
} finally {
if (conn != null)
realseConnection(conn);
}
}
}
public PreparedStatement createPreparedStatement(Connection conn, String sql, Object... params)
throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
return ps;
}
public int executeUpdate(Connection conn, String sql, Object... params) throws Exception {
PreparedStatement ps = createPreparedStatement(conn, sql, params);
return ps.executeUpdate();
}
public ResultSet executeQuery(Connection conn, String sql, Object... params) throws Exception {
PreparedStatement ps = createPreparedStatement(conn, sql, params);
return ps.executeQuery();
}
}
判断
package com.liu.util;
public class StringUtil {
private StringUtil() {}
public static boolean isBlank(String str) {
return str==null || str.trim().length()<1;
}
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
public static boolean validatelength(String str,int...lens) {
boolean res=true;
if (lens!=null && lens.length>0) {
res=str.trim().length()>=lens[0];
if(lens.length>1 && res)
res=str.trim().length()<=lens[1];
}
return res;
}
}
注册登录
package com.liu.action;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.liu.dao.IuserDao;
import com.liu.entity.UserBean;
import com.liu.util.DaoFactory;
import com.liu.util.JdbcUtil;
public class UserManger {
private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
private static IuserDao userDao = DaoFactory.getUserDao();
public static void main(String[] args) throws Exception {
UserManger.mainMenu();
}
public static void mainMenu() throws Exception {
System.out.println("欢迎光临本系统");
System.out.println("===========================");
System.out.println("1.用户注册" + "\t" + "2.用户登录");
int res = 0;
try {
String ss = br.readLine();
res = Integer.parseInt(ss);
switch (res) {
case 1:
regist();
break;
case 2:
login();
break;
default:
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void regist() throws Exception {
while (true) {
UserBean user = new UserBean();
System.out.println("请输入用户口令:");
String ss = br.readLine();
if (ss != null && ss.trim().length() > 0) {
if (userDao.existName(ss)) {
System.out.println("用户名已存在!");
break;
}
else {
user.setUsername(ss);
}
}
System.out.println("请输入用户密码:");
ss = br.readLine();
if (ss != null && ss.trim().length() > 0)
user.setPassword(ss);
if (userDao.save(user)) {
System.out.println("注册成功");
break;
} else
System.out.println("用户名或密码不合法!");
}
}
private static void login() throws Exception {
System.out.println("=============");
if (exist()) {
System.out.println("登录成功!");
} else {
System.out.println("登录失败!");
}
}
private static boolean exist( ) throws Exception {
Connection conn=null;
ResultSet rs = null;
System.out.println("请输入用户口令:");
String username=br.readLine();
System.out.println("请输入用户密码:");
String password=br.readLine();
String sql=" select * from t_users where username=? and password=?";
boolean res;
try {
conn=JdbcUtil.getConnection();
rs=JdbcUtil.executeQuery(conn, sql, username,password);
res=rs.next();
} finally {
JdbcUtil.close(rs, null, conn);
}
return res;
}
}