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

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

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

  • 前端代码
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>人员基本信息</title>
		<!-- jquery要在时间插件前引入 -->
		<script src="../../command/jquery-3.4.0.min.js" type="text/javascript" charset="utf-8"></script>
		<!-- 时间插件引入 -->
		<link rel="stylesheet" href="../../command/Bootstrap/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.css" />
		<link rel="stylesheet" href="../../command/Bootstrap/bootstrap-datetimepicker-master/css/bootstrap-datetimepicker.min.css" />

		<script src="../../command/Bootstrap/bootstrap-datetimepicker-master/js/bootstrap-datetimepicker.js"></script>
		<script src="../../command/Bootstrap/bootstrap-datetimepicker-master/js/bootstrap-datetimepicker.min.js"></script>
		<script src="../../command/Bootstrap/bootstrap-datetimepicker-master/js/locales/bootstrap-datetimepicker.zh-CN.js"></script>


		<link rel="stylesheet" type="text/css" href="../../command/Bootstrap/bootstrap-3.3.0/css/bootstrap.min.css" />
		<link rel="stylesheet" type="text/css" href="../../command/Bootstrap/bootstrap-3.3.0/css/bootstrap-theme.min.css" />
		<link rel="stylesheet" type="text/css" href="../css/first.css" />
		<!-- 子界面文件引入 -->

		<script src="../../command/Bootstrap/bootstrap-3.3.0/js/bootstrap.min.js"></script>
		<script src="../../command/bower_components/bootbox/bootbox.min.js"></script>
		<script src="../../command/bower_components/bootstrap-select/js/bootstrap-select.js"></script>
		<script src="../../command/bower_components/bootstrap-switch/dist/js/bootstrap-switch.min.js"></script>
		<script src="../../command/bower_components/bootstrap-table/dist/bootstrap-table.min.js"></script>
		<script src="../../command/bower_components/bootstrap-table/dist/locale/bootstrap-table-zh-CN.js"></script>
		<script src="../../command/bower_components/moment/min/moment-with-locales.min.js"></script>
		<!-- 下拉框引用 -->
		<script src="../../command/bower_components/bootstrap-select/js/bootstrap-select.js"></script>

		<!-- 子界面脚本 -->
		<script type="application/javascript">
			$(function() {
				//读取列表数据
				
				$.ajax({
					type: "get", //提交类型
					dataType: "json", //数据类型
					url: "http://localhost:8080/User/User", //数据访问路径
					success: function(reslt) {
						console.log("kkk"); //返回成功后所调用的函数
						creatTable(reslt); //函数调用
						// alert(reslt);
					},
					error: function(date) {
						alert("初始化错误")
					}
				});

				//新增按钮点击事件
				$("#btnNew").click(function() {
					$("#divData").modal();
					//新增模态框
					$("#btnsave").click(function() {
						var uname = $("#txtDatausername").val();
						var sex = $("#txtGender").val();
						var phone = $("#txtPhone").val();
						var personnumber = $("#txtShenfenzhenghao").val();
						var nativeplace = $("#txtJiGuan").val();
						var createtime = $("#txtCreteTime").val();
						var birthdate = $("#txtChuSheng").val();
						var state = $("#txtZhuangTai").val();
						Hxz("1", uname, sex, phone, personnumber, nativeplace, createtime, birthdate, state)
						Console.log(uname);
					});
				});

				//删除按钮事件
				$("#btnDelete").click(function() {
					var userid = HgetSelect();
					console.log(userid);

					//获取json串中的所有数据
					$.ajax({
						type: "get", //提交类型
						dataType: "json", //数据类型
						url: "http://localhost:8080/User/User",
						success: function(data) {
							// console.log(data);
							//遍历解析的json数据
							$.each(data, function(index02, value02) {
								console.log(value02["userid"]);
								// 对比解析的数据与获取列表的数据是否一致
								if (value02["userid"] == userid) {
									console.log(userid);
									console.log(value02["userid"]);
									HdelMySQL("2", userid);
								}
							})
						}
					});

				});

				//修改按钮事件
				$("#btnModify").click(function() {
					//获取列表当中的主键
					var userid = HgetSelect();
					console.log(userid);
					//获取json串中的所有数据
					$.ajax({
						type: "get", //提交类型
						dataType: "json", //数据类型
						url: "http://localhost:8080/User/User",//数据访问路径
						success: function(data) {
							console.log(data);
							//遍历解析的json数据
							$.each(data, function(index02, value02) {
								console.log(value02["userid"]);
								// 对比解析的数据与获取列表的数据是否一致
								if (value02["userid"] == userid) {
									console.log(value02["userid"]);
									// console.log("------------------------");
									//将一致的数据赋值到所对应的的控件当中;
									$("#txtDatausername").val(value02["uname"]);
									$("#txtGender").val(value02["sex"]);
									$("#txtPhone").val(value02["phone"]);
									$("#txtShenfenzhenghao").val(value02["personnumber"]);
									$("#txtJiGuan").val(value02["nativeplace"]);
									$("#txtCreteTime").val(value02["createtime"]);
									$("#txtChuSheng").val(value02["birthdate"]);
									$("#txtZhuangTai").val(value02["state"]);
								}

							})
							$("#divData").modal();
							//模态框保存按钮点击事件
							$("#btnsave").click(function() {
								var userid = HgetSelect();
								console.log(userid);
								//获取json串中的所有数据
								$.ajax({
									type: "get", //提交类型
									dataType: "json", //数据类型
									url: "http://localhost:8080/User/User",
									success:function(data){
										// console.log(data);
										//遍历解析的json数据
										$.each(data,function(index02,value02){
											// console.log(value02["userid"]);
											// 对比解析的数据与获取列表的数据是否一致
											if (value02["userid"]==userid){
											var uname = $("#txtDatausername").val();
											var sex = $("#txtGender").val();
											var phone = $("#txtPhone").val();
											var personnumber = $("#txtShenfenzhenghao").val();
											var nativeplace = $("#txtJiGuan").val();
											var createtime = $("#txtCreteTime").val();
											var birthdate = $("#txtChuSheng").val();
											var state = $("#txtZhuangTai").val();
											Hxg("3",uname, sex, phone, personnumber, nativeplace, createtime, birthdate, state,userid);
											console.log("-------------------");
											console.log(createtime);
											// console.log(userid);
											}
											
										})
										
									}
									
								});
							
							
							})	

						}

					});
				});


				//1,对列表中的数据进行查询;
				$("#btnSelect").click(function() {
					var userid = $("#selectName").val();
					//判断
					if(userid!=""){
						Hchaxun("1",userid);
						$.ajax({
							type:"get",
							dataType:"json",
							url: "http://localhost:8080/User/User",
							success:function(data){
								console.log(data);
								var jsonArray = [];
								//遍历json中解析处理的数据
								$.each(data,function(index01,value01){
									//精确查找json中的值
									console.log(value01["userid"]);
									if(value01["userid"]==userid){
										//显示json数据
										console.log(value01);
										console.log("--------------");
										jsonArray.push(value01);
									}
								});
								//对表格重新进行绑定
								creatTable(jsonArray);
								
							}
							
						});
					}else{
						alert("请输入要查询的主键");
					}
					
				});

				//初始化结束(此括号经常忘,请记住)
			});

			function creatTable(userData) {
				//控制台打印
				console.log(userData);
				$("#tableUser").bootstrapTable("destroy"); //清空表格
				$("#tableUser").bootstrapTable({
					data: userData, //加载json格式的数据

					loadMsg: "正在加载数据",
					sidePagination: "client", // 设置在哪里进行分页,可选值为 'client' 或者 'server'。设置 'server'时,必须设置 服务器数据地址(url)或者重写ajax方法
					pageSize: "10", //如果设置了分页,页面数据条数
					pagination: true, //设置为 true 会在表格底部显示分页条
					showRefresh: true, //是否显示刷新按钮
					striped: true, //是否显示行间隔色
					singleSelect: false,
					columns: [{
							// field: "state", //列字段名称。
							checkbox: true,
							// align: "center"

						},

						{
							field: "userid",
							title: "主键",
							align: "center"

						},

						{
							field: "uname",
							title: "姓名",
							align: "center"

						},

						{
							field: "sex",
							title: "性别",
							align: "center"

						},

						{
							field: "phone",
							title: "电话号码",
							align: "center"

						},

						{
							field: "personnumber",
							title: "身份证号",
							align: "center"

						},

						{
							field: "nativeplace",
							title: "籍贯",
							align: "center"

						},

						{
							field: "createtime",
							title: "创建时间",
							align: "center"

						},

						{
							field: "birthdate",
							title: "出生日期",
							align: "center"

						},
						{
							field: "state",
							title: "状态",
							align: "center"

						},
					]
				});
			}

			//获取所选行数据
			function HgetSelect() {
				//获取列表选择的行
				var row = $("#tableUser").bootstrapTable('getSelections');
				// alert(row);
				if (row.length > 0) {
					return row[0].userid;
				} else {
					alert("请选择要修改的数据");
				}
			}
			//新增方法
			function Hxz(oper, uname, sex, phone, personnumber, nativeplace, createtime, birthdate, state) {
				$.ajax({
					type: 'get',
					url: "http://localhost:8080/User/User",
					data: {
						oper: oper,
						uname: uname,
						sex: sex,
						phone: phone,
						personnumber: personnumber,
						nativeplace: nativeplace,
						createtime: createtime,
						birthdate: birthdate,
						birthdate: birthdate
					},
					success: function(resp) {
						console.log(resp);
						var data = JSON.parse(resp);
						//alert(data.results);
					}

				});

			}

			//删除后端数据库的方法
			function HdelMySQL(oper, userid) {
				console.log(oper + userid);
				$.ajax({
					type: 'get',
					url: "http://localhost:8080/User/User",
					data: {
						oper: oper,
						userid: userid,
					},
					success: function(resp) {
						console.log(resp);
						var data = JSON.parse(resp);
						//alert(data.results);
					}

				});
			}

			//后端修改方法
			function Hxg(oper, uname, sex, phone, personnumber, nativeplace, createtime, birthdate, state,userid) {
				console.log(oper + uname);
				$.ajax({
					type: 'get',
					url: "http://localhost:8080/User/User",
					data: {
						oper: oper,
						uname: uname,
						sex: sex,
						phone: phone,
						personnumber: personnumber,
						nativeplace: nativeplace,
						createtime: createtime,
						birthdate: birthdate,
						birthdate: birthdate,
						userid: userid
					},
					//resp从后端接收的数据 跨域过来的是字符串 下边进行了打印
					success: function(resp) {
						console.log(resp);
						//将字符串类型的转化成了json格式
						var data = JSON.parse(resp);
						//alert(data.results);
					}

				});
			}
			
			//后端查询方法
			function Hchaxun(oper, userid) {
				$.ajax({
					type: 'get',
					url: "http://localhost:8080/User/User",
					data: {
						oper: oper,
						userid: userid
					},
					success: function(resp) {
						// console.log(resp);
						// var data = JSON.parse(resp);
						// alert(data.results);
					}
			
				});
			}
		</script>

	</head>
	<body>
		<!-- 子界面布局 -->

		<div class="container-fluid">

			<!-- 查询区域开始 -->
			<div class="row col-md-10">
				<div id="divSelect" class="form-inline">
					<div class="form-group">
						<label class="control-label sousuotxt" for>主键</label>
						<input type="text" name="txtName" id="selectName" class="form-control sousuo" maxlength="20" />
					</div>
					<div class="form-group">
						<button type="button" id="btnSelect" class="btn btn-danger">查询</button>
					</div>
					<!-- 时间插件开始 -->
					<div class="form-group">
						<label class="control-label sjtxt" for="" style="margin-left: 10px;">时间查询</label>
						<div class="input-group date form_date col-md-6">
							<input type="text" id="CreationTime" class="form-control sjfirst" placeholder="暂不可用" />
							<span class="input-group-addon" style="width: 25%;"><span class="glyphicon glyphicon-calendar"></span></span>
						</div>
						<!-- 时间插件js   js一定要放在div后边 否则不可输入日期-->
						<script src="../js/Time-Meter-1.js"></script>
					</div>
					<!-- 时间插件结束 -->

				</div>

			</div>

			<!-- 功能区域开始 -->

			<div class="form-group row col-md-5" style="margin-top: 20px; float: left;">
				<button type="button" id="btnNew" class="btn btn-success">添加</button>
				<button type="button" id="btnModify" class="btn btn-default">修改</button>
				<button type="button" id="btnDelete" class="btn btn-default">删除</button>
				<!-- <button type="button" id="btnArchive" class="btn btn-default">离职</button> -->
			</div>

			<!-- 功能区域结束 -->

			<!-- 列表区域开始 -->
			<div class="row col-md-11 " style="margin-top: 20px;">
				<table border="1px solid black" id="tableUser">
				</table>
			</div>
		</div>

		<!-- 模态框处理 -->
		<div class="modal fade" id="divData" tabindex="-1" role="dialog" aria-lableledby="myModelLable" aria-hidden="hidden">
			<div class="modal-dialog">
				<div class="modal-content">
					<!-- 模态标题 -->
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal" aria-hidden="true">关闭</button>
						<h4 class="modal-title" id="">详细信息</h4>

					</div>
					<!-- 主题表单 -->
					<div class="modal-body form-inline">
						<div class="form-group">
							<label class="control-label" for="">姓名</label>
							<input type="text" name="Datausername" id="txtDatausername" class="form-control" maxlength="20" />

						</div>
						<div class="form-group">
							<label class="control-label" for="">身份证号</label>
							<input type="text" name="Datausername" id="txtShenfenzhenghao" class="form-control" maxlength="30" />

						</div>
						<div class="form-group" style="margin-top: 10px;">
							<label class="control-label" for="">性别</label>
							<input type="text" name="Datausername" id="txtGender" class="form-control" maxlength="20" />

						</div>
						<div class="form-group" style="margin-top: 10px;">
							<label class="control-label" for="">出生日期</label>
							<input type="text" name="Datausername" id="txtChuSheng" class="form-control" maxlength="20" />

						</div>
						<div class="form-group" style="margin-top: 10px;">
							<label class="control-label" for="">籍贯</label>
							<input type="text" name="Datausername" id="txtJiGuan" class="form-control" maxlength="20" />

						</div>
						<div class="form-group" style="margin-top: 10px;>
							<label class=" control-label" for="">创建时间</label>
							<input type="text" name="Datausername" id="txtCreteTime" class="form-control" maxlength="20" />

						</div>
						<div class="form-group" style="margin-top: 10px;>
							<label class=" control-label" for="">状态</label>
							<input type="text" name="Datausername" id="txtZhuangTai" class="form-control" maxlength="20" />

						</div>
						<div class="form-group" style="margin-top: 10px;>
							<label class=" control-label" for="">电话号码</label>
							<input type="text" name="Datausername" id="txtPhone" class="form-control" maxlength="20" />

						</div>

					</div>
					<div class="modal-footer">
						<button type="button" id="btnsave" class="btn btn-info" data-dismiss="modal" aria-hidden="true">保存</button>

					</div>

				</div>
			</div>
		</div>
	</body>
</html>

  • 后端
    属性层
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<User> Cx(User user){
		System.out.println("进入查询方法");
		List<User> lister = new ArrayList<User>();
		//创建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<User> CxAll(User user){
		System.out.println("进入查询所有方法");
		
		List<User> lister = new ArrayList<User>();
		
		//创建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<User> 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<User> Cx(User user){
		System.out.println("进入查询业务");
		List<User> lister = new ArrayList<User>();
		lister = udao.Cx(user);
		return lister;
	}
	
	/**
	 * 查询所有业务
	 */
	
	public List<User> CxALL(User user){
		System.out.println("进入查询所有业务");
		List<User> lister = new ArrayList<User>();
		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();
		//显示所有数据
		List<User>lister=new ArrayList<User>();
		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("初始化过滤器");
	}

}

©️2020 CSDN 皮肤主题: 技术黑板 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值