java Servlet实现前端对MySQL数据库的增删改查

java Servlet实现前端对MySQL数据库的增删改查

注:此版并未实现date类型的跨域转换,待更新

  • 前端代码


	
		
		人员基本信息
		
		
		
		
		

		
		
		


		
		
		
		

		
		
		
		
		
		
		
		
		

		
		

	
	
		

		
  • 后端
    属性层
package com.model;

import java.util.Date;

/**
 * 人员基本信息表的属性
 * @author 王炳祥
 *
 */
public class User {
	private int userid;//主键
	private String personid;//人员编号
	private String uname;//人员姓名
	private String sex;//性别
	private String phone;//电话
	private String personnumber;//身份证号
	private Date createtime;//创建时间
	private String nativeplace;//籍贯
	private Date birthdate;//出生日期
	private String state;//状态
	private String duty;//职务
	private String administrativeoffice;//科室
	public int getUserid() {
		return userid;
	}
	public void setUserid(int userid) {
		this.userid = userid;
	}
	public String getPersonid() {
		return personid;
	}
	public void setPersonid(String personid) {
		this.personid = personid;
	}
	public String getUname() {
		return uname;
	}
	public void setUname(String name) {
		this.uname = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getPersonnumber() {
		return personnumber;
	}
	public void setPersonnumber(String personnumber) {
		this.personnumber = personnumber;
	}
	public Date getCreatetime() {
		return createtime;
	}
	public void setCreatetime(Date createtime) {
		this.createtime = createtime;
	}
	public String getNativeplace() {
		return nativeplace;
	}
	public void setNativeplace(String nativeplace) {
		this.nativeplace = nativeplace;
	}
	public Date getBirthdate() {
		return birthdate;
	}
	public void setBirthdate(Date birthdate) {
		this.birthdate = birthdate;
	}
	public String getState() {
		return state;
	}
	public void setState(String state) {
		this.state = state;
	}
	public String getDuty() {
		return duty;
	}
	public void setDuty(String duty) {
		this.duty = duty;
	}
	public String getAdministrativeoffice() {
		return administrativeoffice;
	}
	public void setAdministrativeoffice(String administrativeoffice) {
		this.administrativeoffice = administrativeoffice;
	}
	

}

连接层:

package com.conn;
/**
 * 连接层
 * @author 王炳祥
 *
 */

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class UserCon {
	// 创建一个连接驱动的对象
	Connection con = null;

	// 创建一个连接驱动的方法,方便调用
	//问题:这里为什么用Connection型的返回值?要返回连接对象 必须是这个类型的
	public Connection getCon() {

		try {
			// 加载驱动
			Class.forName("com.mysql.jdbc.Driver");

			// 连接数据库
			con = DriverManager.getConnection("jdbc:mysql://10.96.126.184:3306/system_power_factory", "root", "root");

			//
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			System.out.println("加载驱动时放生错误,详情为:" + e.getMessage());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("连接数据库时放生错误,详情为:" + e.getMessage());
		}

		return con;

	}

	// 设置关闭
	public void setClose() {
		try {
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("关闭数据库时放生错误,详情为:" + e.getMessage());
		}
	}

}

DAO层:

package com.Dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.conn.UserCon;
import com.model.User;


/**
 * 对人员信息表进行操作
 * @author 王炳祥
 *
 */
public class UserDao {
	
	//创建连接数据库的对象
	Connection con = null;
	//创建连接层的对象
	UserCon conn = new UserCon();
	
	/**
	 * 给用用户表添加数据
	 * @param user
	 * @return
	 */
	public int add(User user) {
		System.out.println("进入添加方法");
		int num = 0;
		//创建sql对象
		String str = "INSERT INTO `user` (createtime,administrativeoffice,personnumber,personid,uname,sex,phone,nativeplace,birthdate,state,duty)VALUE(?,?,?,?,?,?,?,?,?,?,?)";
		//创建执行sql语句的对象
		PreparedStatement ps;
		//执行sql语句
		con = conn.getCon();
		try {
			ps = con.prepareStatement(str);
			//设置查询条件
			ps.setDate(1,new java.sql.Date(new java.util.Date().getTime()));
			ps.setString(2, user.getAdministrativeoffice());//科室
			ps.setString(3, user.getPersonnumber());//身份证号
			ps.setString(4, user.getPersonid());//人员编号
			ps.setString(5, user.getUname());
			ps.setString(6, user.getSex());
			ps.setString(7, user.getPhone());
			ps.setString(8, user.getNativeplace());//籍贯
			ps.setDate(9, new java.sql.Date(new java.util.Date().getTime()));
			ps.setString(10, user.getState());//状态
			ps.setString(11, user.getDuty());//职务
			//打印验证
			System.out.println("D层身份证号:"+user.getPersonnumber());
			//返回添加条数
			num = ps.executeUpdate();
			System.out.println("添加条数:"+num);
			//设置关闭
			ps.close();
			con.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			System.out.println("添加方法执行sql语句时出错,详情为:"+e.getMessage());
		}
		return num;
	}
	
	
	
	/**
	 * 删除方法
	 * 
	 */

	public int Del(User user) {
		int num = 0;
		System.out.println("进入删除方法");
		//1创建sql对象
		String str = "DELETE FROM `user` WHERE userid=?"; 
		//2 创建执行sql语句的对象
		PreparedStatement ps;
		con = conn.getCon();
		try {
			//执行sql
			ps=con.prepareStatement(str);
			//设置查询
			ps.setInt(1, user.getUserid());
			System.out.println("D层删除id:"+user.getUserid());
			
			num = ps.executeUpdate();
			System.out.println("删除的行数"+num);
			
			ps.close();
			con.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return num;
	}
	
	
	
	/**
	 * 
	 * 修改方法
	 */
	
	public int Xg(User user) {
		System.out.println("进入修改方法");
		int num = 0;
		// 1 创建sql对象
		String str = "UPDATE `user` SET uname=?,sex=?,personnumber=?,administrativeoffice=?,personid=?,phone=?,nativeplace=?,state=?,duty=? WHERE userid=?";
		// 2 创建执行sql的对象
		PreparedStatement ps;
		con = conn.getCon();
		try {
			//执行sql
			ps=con.prepareStatement(str);
			//设置查询
			ps.setString(1, user.getUname());
			ps.setString(2, user.getSex());
			ps.setString(3, user.getPersonnumber());
			ps.setString(4, user.getAdministrativeoffice());
			ps.setString(5, user.getPersonid());
			ps.setString(6, user.getPhone());
			ps.setString(7, user.getNativeplace());
			ps.setString(8, user.getState());
			ps.setString(9, user.getDuty());
			ps.setInt(10, user.getUserid());
			//返回修改条数
			num = ps.executeUpdate();
			System.out.println("修改条数:"+num);
			//设置关闭
			ps.close();
			con.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return num;
	}
	
	/**
	 * 查询方法(有条件的查询)
	 */
	
	public List Cx(User user){
		System.out.println("进入查询方法");
		List lister = new ArrayList();
		//创建sql语句
		String str = "SELECT * from user WHERE userid = ?";	
		con = conn.getCon();
		try {
			//创建执行sql语句的对象  执行sql
			PreparedStatement ps = con.prepareStatement(str);
			//设置查?的条件
			ps.setInt(1, user.getUserid());
			//将查询的结果保存到记录集
			ResultSet rs = ps.executeQuery();
			//ResultSet 对象具有指向其当前数据行的光标。最初,光标被置于第一行之前。next 方法将光标移动到下一行;
			//因为该方法在 ResultSet 对象没有下一行时返回 false,所以可以在 while 循环中使用它来迭代结果集。
			while(rs.next()) {
				//声明一个实体
				User user1 = new User();
				// 给对象赋值 传的是索引值 不是变量
				user1.setUserid(rs.getInt("userid"));
				user1.setPersonid(rs.getString("personid"));
				user1.setUname(rs.getString("uname"));
				user1.setSex(rs.getString("sex"));
				user1.setPhone(rs.getString("phone"));
				user1.setPersonnumber(rs.getString("personnumber"));
				user1.setCreatetime(rs.getDate("createtime"));
				user1.setNativeplace(rs.getString("nativeplace"));
				user1.setBirthdate(rs.getDate("birthdate"));
				user1.setState(rs.getString("state"));
				user1.setDuty(rs.getString("duty"));
				user1.setAdministrativeoffice(rs.getString("administrativeoffice"));
				System.out.println("查询的id是:"+user1.getUserid());
				//添加到集合中
				lister.add(user);
			}
			// 关闭记录集
			rs.close();
			// 关闭执行的sql对象
			ps.close();
			// 关闭连接
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return lister;
	}
	
	/**
	 * 查询方法(所有)
	 */
	public List CxAll(User user){
		System.out.println("进入查询所有方法");
		
		List lister = new ArrayList();
		
		//创建sql语句
		String str = "SELECT * from user";
		
		con = conn.getCon();
		
		try {
			//创建执行sql语句的对象  执行sql
			PreparedStatement ps = con.prepareStatement(str);
			System.out.println(str);
			//将查询的结果保存到记录集
			ResultSet rs = ps.executeQuery();
			//ResultSet 对象具有指向其当前数据行的光标。最初,光标被置于第一行之前。next 方法将光标移动到下一行;
			//因为该方法在 ResultSet 对象没有下一行时返回 false,所以可以在 while 循环中使用它来迭代结果集。

			while(rs.next()) {
				//声明一个实体
				User user1 = new User();

				// 给对象赋值 传的是索引值 不是变量
				user1.setUserid(rs.getInt("userid"));
				user1.setPersonid(rs.getString("personid"));
				user1.setUname(rs.getString("uname"));
				user1.setSex(rs.getString("sex"));
				user1.setPhone(rs.getString("phone"));
				user1.setPersonnumber(rs.getString("personnumber"));
				user1.setCreatetime(rs.getDate("createtime"));
				user1.setNativeplace(rs.getString("nativeplace"));
				user1.setBirthdate(rs.getDate("birthdate"));
				user1.setState(rs.getString("state"));
				user1.setDuty(rs.getString("duty"));
				user1.setAdministrativeoffice(rs.getString("administrativeoffice"));
//				System.out.println(rs.getInt("userid"));
				//添加到集合中
//				System.out.println(rs.getString("uname"));
				lister.add(user1);
			}
			// 关闭记录集
			rs.close();
			// 关闭执行的sql对象
			ps.close();
			// 关闭连接
			con.close();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		return lister;
		
	}
}

业务逻辑层:

package com.Services;

import java.util.ArrayList;
import java.util.List;

import com.Dao.UserDao;
import com.model.User;

/**
 * 对人员表的业务逻辑判断
 * @author 王炳祥
 *
 */


public class UserServices {
	
	UserDao udao = new UserDao();
	
	/**
	 * 对添加方法的业务逻辑进行判断
	 */
	public int add(User user) {
		System.out.println("进入添加业务");
		int num = 0;
//		//通过查找方法获取数据库中的身份证号
//		User user1 = new User();
//		user1.setPersonnumber(user.getPersonnumber());
//		List lister = udao.CxAll(user1);
//		//判断是否可以添加
//		if(lister.size()>1) {
//			num=-1;
//			udao.add(user);
//			System.out.println("添加时发现身份证号重复");
//		}else {
			udao.add(user);
			System.out.println("S层身份证号:"+user.getPersonnumber());
//		}
		return num;
		
	}
	
	
	/**
	 * 删除业务
	 * 
	 */
	
	public int Del(User user) {
		System.out.println("进入删除业务:");
		int num = 0;
		System.out.println("S层删除的id:"+user.getUserid());
		udao.Del(user);
		return num;
	}
	
	/**
	 * 修改业务
	 */
	public int Xg(User user) {
		System.out.println("进入修改业务");
		int num = 0;
		udao.Xg(user);
		return num;
	}
	
	/**
	 * 查询业务
	 */
	
	public List Cx(User user){
		System.out.println("进入查询业务");
		List lister = new ArrayList();
		lister = udao.Cx(user);
		return lister;
	}
	
	/**
	 * 查询所有业务
	 */
	
	public List CxALL(User user){
		System.out.println("进入查询所有业务");
		List lister = new ArrayList();
		lister = udao.CxAll(user);
		
		
		
		return lister;
	}
	

}

controller层:

package com.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Services.UserServices;
import com.google.gson.Gson;
import com.model.User;
import com.mysql.fabric.xmlrpc.base.Data;
//地址 
@WebServlet("/User")
public class UserController extends HttpServlet{

	//转json格式
	private static Gson gson = new Gson();
	@Override
	protected void doGet(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		//解决乱码问题
		response.setContentType("text/html;charset=UTF-8");
		//字符串转data类型
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		//创建业务层对象
		UserServices userServices = new UserServices();
		//创建属性层对象
		User user = new User();
		//显示所有数据
		Listlister=new ArrayList();
		lister=userServices.CxALL(user);
		//转化成json格式(前端用)
		String str = gson.toJson(lister);
		response.getWriter().print(str);
		//选择进行的方法
		String oper = requset.getParameter("oper");
		System.out.println("获取地址栏当中的方法编号:" + oper);
		
		//执行方法
		if(oper!=null) {
			switch(oper) {
			case "1":
				//增加方法
				if(requset.getParameter("uname")!=null) {
				try {
					Date birthdate = sdf.parse(requset.getParameter("birthdate"));
					Date createtime = sdf.parse(requset.getParameter("createtime"));
					//赋值
					user.setBirthdate(birthdate);
					user.setCreatetime(createtime);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
		
				}
				String duty = requset.getParameter("duty");//职务
				user.setDuty(duty);
				String administrativeoffice = requset.getParameter("administrativeoffice");//科室
				user.setAdministrativeoffice(administrativeoffice);
				String personnumber = requset.getParameter("personnumber");//身份证号
				user.setPersonnumber(personnumber);
				String uname = requset.getParameter("uname");
				user.setUname(uname);
				String personid = requset.getParameter("personid");//人员编号
				user.setPersonid(personid);
				String sex = requset.getParameter("sex");
				user.setSex(sex);
				String phone = requset.getParameter("phone");
				user.setPhone(phone);
				String nativeplace = requset.getParameter("nativeplace");//籍贯
				user.setNativeplace(nativeplace);
				String state = requset.getParameter("state");//状态
				user.setState(state);
				//进行方法调用
				userServices.add(user);
				System.out.println("添加结束");
				}else {
					System.out.println("C层增加时获取的身份证号为空");
				}
				break;
				
				
			case "2":
				//删除方法
				if(requset.getParameter("userid")!=null) {
				int userid = Integer.parseInt(requset.getParameter("userid"));
				user.setUserid(userid);
				//进行方法调用
				userServices.Del(user);
				System.out.println("删除结束");
				}else {
					System.out.println("C层删除获取的id为空");
				}
				break;
			case "3":
				//修改方法
				if(requset.getParameter("uname")!=null) {
				String duty = requset.getParameter("duty");//职务
				user.setDuty(duty);
				String administrativeoffice = requset.getParameter("administrativeoffice");//科室
				user.setAdministrativeoffice(administrativeoffice);
				String personnumber = requset.getParameter("personnumber");//身份证号
				user.setPersonnumber(personnumber);
				String uname = requset.getParameter("uname");
				user.setUname(uname);
				String personid = requset.getParameter("personid");//人员编号
				user.setPersonid(personid);
				String sex = requset.getParameter("sex");
				user.setSex(sex);
				String phone = requset.getParameter("phone");
				user.setPhone(phone);
				String nativeplace = requset.getParameter("nativeplace");//籍贯
				user.setNativeplace(nativeplace);
				String state = requset.getParameter("state");//状态
				user.setState(state);
				int userid = Integer.parseInt(requset.getParameter("userid"));
				user.setUserid(userid);
				//方法调用
				userServices.Xg(user);
				}else {
					System.out.println("C层修改时获取id为空");
				}
				break;
				
			case "4":
				int userid = Integer.parseInt(requset.getParameter("userid"));
				user.setUserid(userid);
				//进行方法调用
				userServices.Cx(user);
				System.out.println("查询结束");	

			}	
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doPost(requset, response);
	}

}

过滤器:

package com.Filter;

import java.io.IOException;
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.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet Filter implementation class UserFilter
 */
@WebFilter("/*")
public class UserFilter implements Filter {

    /**
     * Default constructor. 
     */
    public UserFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

	//解决web地址访问跨越问题代码如下
		
		HttpServletResponse res = (HttpServletResponse)response;
		res.setHeader("Access-Control-Allow-Origin", "*");
		res.setHeader("Access-Control-Allow-Methods", "POST,GET");
		res.setHeader("Access-Control-Allow-Credentials", "true");
		//解决web地址访问跨越问题代码以上代码
		
		request.setCharacterEncoding("UTF-8");
		System.out.println("进行过滤器方法");
		System.out.println("对参数进行拦截,"+request.getParameter("oper"));
		chain.doFilter(request, response);
		// pass the request along the filter chain
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
		System.out.println("初始化过滤器");
	}

}

你可能感兴趣的:(日常学习,欢迎指教,总结记录)