Java通过反射机制简化Dao层的繁琐操作
配置文件 jdbc.properties
jdbc=jdbc:mysql://localhost:3306/wangyi
Driver=com.mysql.jdbc.Driver
name=root
password=123456
Config.java
package com.Wangyi.config;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by Administrator on 2017/1/1.
*/
public class Config {
public static void main(String[] args) {
System.out.println(getConfig("Driver"));
}
public static String getConfig(String nKey){
try {
Properties pro=new Properties();
InputStream is=Config.class.getClassLoader().getResourceAsStream("jdbc.properties");
pro.load(is);
return pro.getProperty(nKey);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
BaseDao.java
package com.Dao;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import com.Wangyi.config.Config;
/**
* Created by Administrator on 2017/1/1.
* Dao层 实现与数据库的交互工作
*/
public class BaseDao {
private static Connection con = null;
private static PreparedStatement ps = null;
private static ResultSet rs = null;
/**
* 静态初始化块
* 加载驱动
* 获取连接
*/
static {
try {
Class.forName(Config.getConfig("Driver"));
con = DriverManager.getConnection(Config.getConfig("jdbc"), Config.getConfig("name"), Config.getConfig("password"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 执行从Dao层提交的sql语句
* @param sql sql语句
* @param parameter sql语句需要设置的属性
* @param cla 将查询的属性赋予给一个对象(比如:查询user表 则新建一个user表的模型与之对应)
* @return 返回结果
*/
public static List<?> setsql(String sql, Object[] parameter, Class<?> cla) {
List<Object> list = new ArrayList();
try {
con = getCon();
ps = con.prepareStatement(sql);
if (parameter != null && parameter.length > 0) {
for (int i = 0; i < parameter.length; i++) {
ps.setObject((i + 1), parameter[i]);
}
}
if (sql.toLowerCase().startsWith("select")) {
rs = ps.executeQuery();
while (rs.next()) {
ResultSetMetaData meta = rs.getMetaData();
int count = meta.getColumnCount();
Object nClass = cla.newInstance();
for (int i = 0; i < count; i++) {
String metaName = meta.getColumnName(i + 1);
Object metaValue = rs.getObject(metaName);
Field fieldName = cla.getDeclaredField(metaName);
fieldName.setAccessible(true);
fieldName.set(nClass, metaValue);
}
list.add(nClass);
}
} else {
list.add(ps.executeUpdate());
}
} catch (SQLException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return list;
}
/**
* 调用连接
* @return
*/
public static Connection getCon() {
return con;
}
/**
* 关闭连接释放资源
* @param con 关闭Connection
* @param ps 关闭PreparedStatement
* @param rs 关闭ResultSet
*/
public static void getClose(Connection con, PreparedStatement ps, ResultSet rs) {
try {
if (con != null) con.close();
if (ps != null) ps.close();
if (rs != null) rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Dao.java
package com.Dao;
import com.model.user;
import java.util.List;
/**
* Created by Administrator on 2017/1/1.
*/
public class Dao extends BaseDao{
public static void main(String[] args) {
System.out.println(uNameIsFlag("ss"));
}
/**
* 将注册的信息添加到数据库中
* @param uName 用户名
* @param uPassword 用户密码
* @param Sex 性别
* @param Name 真实姓名
* @param nickName 昵称
* @param Telephone 电话号码
* @param Email 电子邮箱
* @return
*/
public static Boolean AddUser(String uName,String uPassword,int Sex,String Name,String nickName,String Telephone,String Email){
String sql="Insert into user(uName,uPassword,Sex,Name,nickName,Telephone,Email) Values(?,?,?,?,?,?,?)";
Object[] Parameter={uName,uPassword,Sex,Name,nickName,Telephone,Email};
int num=(Integer)Dao.setsql(sql,Parameter,null).get(0);
if(num>0) return true;
return false;
}
/**
* 判断数据库中是否存在该用户
* @param uName 用户名
* @return 返回匹配结果
*/
public static boolean uNameIsFlag(String uName){
String sql="select uName from user";
List<user> list= (List<user>) Dao.setsql(sql,null, user.class);
for (user user:list) {
if(user.getuName().equals(uName)){
return true;
}
}
return false;
}
}
services.java
package com.Services;
import com.Dao.Dao;
import com.model.user;
/**
* Created by Administrator on 2017/1/1.
* 业务逻辑层 进行各种逻辑处理
*/
public class Services {
public static boolean doRegister(user user) {
if (!user.getuName().matches("^[a-zA-Z0-9][a-zA-Z0-9\\-\\._]{2,16}[a-zA-Z0-9]$")) return false;
if (Dao.uNameIsFlag(user.getuName())) return false;
if (!user.getuPassword().equals(user.getConfirmPassword())) return false;
if (!user.getTelephone().matches("^(13|15|18|17)\\d{9}$")) return false;
if (!user.getEmail().matches("^\\w+@\\w+(\\.[a-zA-Z]{2,3}){1,2}$")) return false;
Boolean Flag = Dao.AddUser(user.getuName(), user.getuPassword(), user.getSex(), user.getName(), user.getNickName(), user.getTelephone(), user.getEmail());
if (!Flag) return false;
return true;
}
}
ServletForRegister.jsp
package com.Wangyi.Action;
import com.Services.Services;
import com.model.user;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by Administrator on 2017/1/1.
* Action层 调用Services层的方法来处理页面的 请求
*/
public class ServletForRegister extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String uName=req.getParameter("uName");
String uPassword=req.getParameter("uPassword");
String confirmPassword=req.getParameter("confirmPassword");
int Sex=Integer.parseInt(req.getParameter("Sex"));
String Name=req.getParameter("Name");
String nickName=req.getParameter("nickName");
String Telephone=req.getParameter("Telephone");
String Email=req.getParameter("Email");
user user=new user(uName,uPassword,confirmPassword,Sex,Name,nickName,Telephone,Email);
if(Services.doRegister(user)) {
req.setAttribute("user", user);
req.getRequestDispatcher("pages/Success.jsp").forward(req, resp);
}else {
req.getRequestDispatcher("pages/Fail.jsp").forward(req,resp);
}
}
}
user.java (模型对象)
package com.model;
/**
* Created by Administrator on 2017/1/1.
* 模型层
*/
public class user {
private String uName;
private String uPassword;
private String confirmPassword;
private int Sex;
private String Name;
private String nickName;
private String Telephone;
private String Email;
public user() {
}
public user(String uName, String uPassword, String confirmPassword, int sex, String name, String nickName, String telephone, String email) {
this.uName = uName;
this.uPassword = uPassword;
this.confirmPassword = confirmPassword;
Sex = sex;
Name = name;
this.nickName = nickName;
Telephone = telephone;
Email = email;
}
@Override
public String toString() {
return "用户名:"+uName+"\n密码:"+uPassword+"\n性别:"+Sex+"\n真实姓名:"+Name+"\n昵称:"+nickName+"\n电话号码:"+Telephone+"\nEmail:"+Email;
}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public String getuPassword() {
return uPassword;
}
public void setuPassword(String uPassword) {
this.uPassword = uPassword;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public int getSex() {
return Sex;
}
public void setSex(int sex) {
Sex = sex;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getTelephone() {
return Telephone;
}
public void setTelephone(String telephone) {
Telephone = telephone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
}
前端页面就不给啦
相关文章