java web简单的职工管理系统

今天接了一个职工管理系统,大学生的期末作业。总的而来说实现功能比较简单,围绕增删查改进行。当然最后还有实验报告要写。

功能如下:

存储职工编号,职工姓名,日期,每次打卡时间(一天可多次打卡,第一次为上班时间、最后一次为下班时间)等信息。

考勤信息的增加、删除、修改和查询(如按月统计打卡次数,某人在指定日期的考勤记录等)。

所采用的的技术:jquery+easyui+servlet+mysql5.0

由于放上所有代码过于冗余,仅介绍核心。

登录界面:(网上搜的模板)

职工考勤的增删查改以及查询功能。

java web简单的职工管理系统_第1张图片

jsp:

employee.jsp(职工考勤页面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>职工考勤管理</title>
<link rel="stylesheet" type="text/css"
	href="easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/easyui/css/demo.css">
<script type="text/javascript" src="easyui/jquery.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/easyui/js/validateExtends.js"></script>
<script type="text/javascript">
	$(function() {
		//datagrid初始化 
		var indexFlag=-1;//用于单选时判断是否控制复选框的勾选状态
		$('#dataList').datagrid({
			title : '考勤列表',
			iconCls : 'icon-more',//图标 
			border : true,
			collapsible : false,//是否可折叠的 
			fit : true,//自动大小 
			method : "post",
			url : "EmployeeServlet?method=EmployeeList&t="+ new Date().getTime(),
			idField : 'id',
			singleSelect : true,//是否单选 
			pagination : true,//分页控件 
			rownumbers : true,//行号 
			sortName : 'id',
			sortOrder : 'DESC',
			fitColumns : true,
			remoteSort : false,
			onCheck:function(index,row){//第一次选中该行,让他的index赋值给indexFlag,第二层选中该行就把对勾取消
	        	if(indexFlag==index){
        			$("#dataList").datagrid('uncheckRow',index);//执行方法,取消该行
	        		indexFlag=-1;
	        	}else{
	        		indexFlag=index;
	        	}
	        },
			columns: [[  
				{field:'chk',checkbox: true,width:50},
 		        {field:'id',title:'职工号',width:50, sortable: true},    
 		        {field:'name',title:'姓名',width:50, sortable: true},    
 		        {field:'time',title:'日期',width:150},
 		        {field:'first_clock',title:'第一次打卡',width:150},
 		       {field:'end_clock',title:'最后一次打卡',width:150},
	 		]], 
			toolbar : "#toolbar",
			onBeforeLoad : function() {
			}
		});
		//设置分页控件 
		var p = $('#dataList').datagrid('getPager');
		$(p).pagination({
			pageSize : 10,//每页显示的记录条数,默认为10 
			pageList : [10, 20, 30, 40, 50 ],//可以设置每页记录条数的列表 
			beforePageText : '第',//页数文本框前显示的汉字 
			afterPageText : '页    共 {pages} 页',
			displayMsg : '当前显示 {from} - {to} 条记录   共 {total} 条记录',
		});
		//设置工具类按钮
		$("#add").click(function() {
			$("#addDialog").dialog("open");
		});
		//修改
		$("#edit").click(function() {
			var selectRow = $("#dataList").datagrid("getSelected");//必须选中某一行才能进行修改
			//console.log(selectRow);
	  		if(selectRow == null){
            	$.messager.alert("消息提醒", "请选择数据进行修改!", "warning");
            	return;
            }
	  		$("#editDialog_").dialog("open");//修改窗口打开
		});
	    //删除
	   $("#delete").click(function(){
	    	var selectRow = $("#dataList").datagrid("getSelected");
        	if(selectRow == null){
            	$.messager.alert("消息提醒", "请选择数据进行删除!", "warning");
            } else{
            	var empid = selectRow.id;
            	$.messager.confirm("消息提醒", "将删除员工信息,确认继续?", function(r){
            		if(r){
            			$.ajax({
							type: "post",
							url: "EmployeeServlet?method=Deleteemp",
							data: {empid: empid},
							success: function(msg){
								if(msg == "success"){
									$.messager.alert("消息提醒","删除成功!","info");
									//刷新表格
									$("#dataList").datagrid("reload");
								} else{
									$.messager.alert("消息提醒","删除失败!","warning");
									return;
								}
							}
						});
            		}
            	});
            }
	    });
		//下拉框通用属性
		$("#add_department, #edit_department").combobox({
			width : "200",
			height : "30",
			valueField : "id",
			textField : "name",
			multiple : false, //可多选
			editable : false, //不可编辑
			method : "post",
		});

		$("#add_department").combobox({
			url : "DepartmentServlet?method=getDepartmentlist&t="
					+ new Date().getTime() + "&from=combox",
			onLoadSuccess : function() {
				//默认选择第一条数据
				var data = $(this).combobox("getData");
				$(this).combobox("setValue", data[0].id);
			}
		});

		$("#edit_department").combobox({
			url : "DepartmentServlet?method=getDepartmentlist&t="
					+ new Date().getTime() + "&from=combox",
			onLoadSuccess : function() {
				//默认选择第一条数据
				var data = $(this).combobox("getData");
				$(this).combobox("setValue", data[0].id);
			}
		});

		//设置添加员工窗口
	    $("#addDialog").dialog({
	    	title: "添加员工记录",
	    	width: 650,
	    	height: 460,
	    	iconCls: "icon-add",
	    	modal: true,
	    	collapsible: false,
	    	minimizable: false,
	    	maximizable: false,
	    	draggable: true,
	    	closed: true,
	    	buttons: [
	    		{
					text:'添加',
					plain: true,
					iconCls:'icon-user_add',
					handler:function(){
						var validate = $("#addForm").form("validate");
						if(!validate){
							$.messager.alert("消息提醒","请检查你输入的数据!","warning");
							return;
						} else{
							$.ajax({
								type: "post",
								url: "EmployeeServlet?method=AddEmployee",
								data: $("#addForm").serialize(),
								success: function(msg){
									if(msg == "success"){
										$.messager.alert("消息提醒","添加成功!","info");
										//关闭窗口
										$("#addDialog").dialog("close");
										//清空原表格数据
										$("#add_name").textbox('setValue', "");
										$("#add_time").datebox('setValue',"");
										$("#add_first_clock").textbox('setValue', "");
										$("#add_end_clock").textbox('setValue', "");
							  			$('#dataList').datagrid("reload");
									} else{
										$.messager.alert("消息提醒","添加失败!","warning");
										return;
									}
								}
							});
						}
					}
				},
				{
					text:'重置',
					plain: true,
					iconCls:'icon-reload',
					handler:function(){
						//清空表单
						$("#add_name").textbox('setValue', "");
						$("#add_time").datebox('setValue',"");
						$("#add_first_clock").textbox('setValue', "");
						$("#add_end_clock").textbox('setValue', "");
					}
				},
			],
			
	    });
	  //设置编辑员工窗口
	    $("#editDialog_").dialog({
	    	title: "修改员工信息",
	    	width: 650,
	    	height: 460,
	    	iconCls: "icon-edit",
	    	modal: true,
	    	collapsible: false,
	    	minimizable: false,
	    	maximizable: false,
	    	draggable: true,
	    	closed: true,
	    	buttons: [
	    		{
					text:'提交',
					plain: true,
					iconCls:'icon-user_add',
					handler:function(){
						var validate = $("#editForm").form("validate");
						if(!validate){
							$.messager.alert("消息提醒","请检查你输入的数据!","warning");
							return;
						} else{
							$.ajax({
								type: "post",
								url: "EmployeeServlet?method=Editemp&t="+new Date().getTime(),
								data: $("#editForm").serialize(),
								success: function(msg){
									if(msg == "success"){
										$.messager.alert("消息提醒","更新成功!","info");
										//关闭窗口
										$("#editDialog_").dialog("close");
										//刷新表格
										$("#dataList").datagrid("reload");
									} else{
										$.messager.alert("消息提醒","更新失败!","warning");
										return;
									}
								}
							});
						}
					}
				},
				{
					text:'重置',
					plain: true,
					iconCls:'icon-reload',
					handler:function(){
						//清空表单
						$("#edit_name").textbox('setValue', "");
						$("#edit_time").datebox('setValue',"");
						$("#edit_first_clock").textbox('setValue', "");
						$("#edit_end_clock").textbox('setValue', "");
					}
				}
			],
			onBeforeOpen: function(){
				var selectRow = $("#dataList").datagrid("getSelected");
				//console.log(selectRow);
				//设置值
				$("#edit_name").textbox('setValue',selectRow.name );
				$("#edit_time").datebox('setValue',selectRow.time);
				$("#edit_first_clock").textbox('setValue', selectRow.first_clock);
				$("#edit_end_clock").textbox('setValue', selectRow.end_clock);
				$("#edit-id").val(selectRow.id);
			}
	    });
		//搜索按钮监听事件
		$("#search-btn").click(function() {
			$('#dataList').datagrid('load',{
				emp_name : $('#search_emp_name').val(),
				search_time:$("#search_time").datebox('getValue')
			});
			 $('#search_emp_name').textbox('setValue','');
		});

	});
</script>
<script type="text/javascript">
		function myformatter(date){
			var y = date.getFullYear();
			var m = date.getMonth()+1;
			var d = date.getDate();
			return y+'-'+(m<10?('0'+m):m)+'-'+(d<10?('0'+d):d);
		}
		function myparser(s){
			if (!s) return new Date();
			var ss = (s.split('-'));
			var y = parseInt(ss[0],10);
			var m = parseInt(ss[1],10);
			var d = parseInt(ss[2],10);
			if (!isNaN(y) && !isNaN(m) && !isNaN(d)){
				return new Date(y,m-1,d);
			} else {
				return new Date();
			}
		}
	</script>
</head>
<body>
	<!-- 薪资列表 -->
	<table id="dataList" cellspacing="0" cellpadding="0">

	</table>
	<!-- 工具框 -->
	<div id="toolbar">
			<div style="float: left;">
				<a id="add" href="javascript:;" class="easyui-linkbutton"
					data-options="iconCls:'icon-add',plain:true">添加</a>
			</div>
			<div style="float: left;" class="datagrid-btn-separator"></div>
		<div style="float: left;">
			<a id="edit" href="javascript:;" class="easyui-linkbutton"
				data-options="iconCls:'icon-edit',plain:true">修改</a>
		</div>
		<div style="float: left;" class="datagrid-btn-separator"></div>
			<div style="float: left;">
				<a id="delete" href="javascript:;" class="easyui-linkbutton"
					data-options="iconCls:'icon-some-delete',plain:true">删除</a>
			</div>
			<div style="float: left;" class="datagrid-btn-separator"></div>
		<div style="float: left; margin: 3px 5px 0 5px;">
			姓名:<input id="search_emp_name" class="easyui-textbox"
				name="search_emp_name" />
		</div>
		<div style="float: left;" class="datagrid-btn-separator"></div>
		<div style="margin: 3px 5px 0 5px;">
			日期:<input id="search_time" data-options="formatter:myformatter,parser:myparser" class="easyui-datebox" name="search_time" />
			 <a id="search-btn" href="javascript:;" class="easyui-linkbutton" data-options="iconCls:'icon-search',plain:true">搜索</a>
		</div>

	</div>

	<!-- 添加员工窗口 -->
	<div id="addDialog" style="padding: 10px">
		<form id="addForm" method="post">
			<table cellpadding="8">
				<tr>
					<td>姓名:</td>
					<td><input id="add_name" style="width: 200px; height: 30px;"
						class="easyui-textbox" type="text" name="add_name"
						data-options="required:true, missingMessage:'请填写姓名'" /></td>
				</tr>
				<tr>
					<td>日期:</td>
					<td>
					<input id="add_time" data-options="formatter:myformatter,parser:myparser" class="easyui-datebox" name="add_time" />
					</td>
				</tr>
				<tr>
					<td>第一次打卡:</td>
					<td><input id="add_first_clock"
						style="width: 200px; height: 30px;" class="easyui-textbox"
						name="add_first_clock" /></td>
				</tr>
				<tr>
					<td>最后一次打卡:</td>
					<td><input id="add_end_clock"
						style="width: 200px; height: 30px;" class="easyui-textbox"
						name="add_end_clock" /></td>
				</tr>
			</table>
		</form>
	</div>

	<!-- 修改员工窗口 -->
	<div id="editDialog_" style="padding: 10px">
		<form id="editForm" method="post">
			<input type="hidden" name="edit-id" id=edit-id>
			<table cellpadding="8">
				<tr>
					<td>姓名:</td>
					<td><input id="edit_name" style="width: 200px; height: 30px;"
						class="easyui-textbox" type="text" name="edit_name"
						data-options="required:true, missingMessage:'请填写姓名'" /></td>
				</tr>
				<tr>
					<td>日期:</td>
					<td>
					<input id="edit_time" data-options="formatter:myformatter,parser:myparser" class="easyui-datebox" name="edit_time" />
					</td>
				</tr>
				<tr>
					<td>第一次打卡:</td>
					<td><input id="edit_first_clock"
						style="width: 200px; height: 30px;" class="easyui-textbox"
						name="edit_first_clock" /></td>
				</tr>
				<tr>
					<td>最后一次打卡:</td>
					<td><input id="edit_end_clock"
						style="width: 200px; height: 30px;" class="easyui-textbox"
						name="edit_end_clock" /></td>
				</tr>
			</table>
		</form>
	</div>
	<!-- 提交表单处理iframe框架 -->
	<iframe id="photo_target" name="photo_target"></iframe>  
</body>
</html>

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>


	
		
		
		
		职工考勤管理程序
		
		
		
		
 

	
		

职工考勤管理程序

Servlet:

EmployeeServlet(完成后台的增删查改)

package com.item.test.Servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.alibaba.fastjson.JSONObject;
import com.item.test.dao.Employeesdao;
import com.item.test.model.Employee;
import com.item.test.model.Page;

/**
 * Servlet implementation class EmployeeServlet
 */
@WebServlet("/EmployeeServlet")
public class EmployeeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method=request.getParameter("method");
		if("toListemployee".equals(method)) {
			Listemployee(request,response);
		}else if("AddEmployee".equals(method)) {
			AddEmployee(request,response);
		}else if("EmployeeList".equals(method)) {
			EmployeeList(request,response);
		}else if("Deleteemp".equals(method)) {
			Deleteemp(request,response);
		}else if("Editemp".equals(method)) {
			Editemp(request,response);
		}
	}

	private void Editemp(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int id=Integer.parseInt(request.getParameter("edit-id"));
		String name = request.getParameter("edit_name");
		String edit_time=request.getParameter("edit_time");
		String edit_first_clock=request.getParameter("edit_first_clock");
		String edit_end_clock=request.getParameter("edit_end_clock");
		Date edit_times=null;
		try {
			edit_times=new SimpleDateFormat("yyyy-MM-dd").parse(edit_time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Employee emp=new Employee();
		emp.setId(id);
		emp.setName(name);
		emp.setTime(edit_times);
		emp.setFirst_clock(edit_first_clock);
		emp.setEnd_clock(edit_end_clock);
		Employeesdao dao=new Employeesdao();
		if(dao.editemp(emp)) {
			try {
				response.getWriter().print("success");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else {
			try {
				response.getWriter().print("error");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}

	private void Deleteemp(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		int id=Integer.parseInt(request.getParameter("empid"));
		Employeesdao dao=new Employeesdao();
		if(dao.deleteemp(id)) {
			try {
				response.getWriter().print("success");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {
			try {
				response.getWriter().print("error");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	private void EmployeeList(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		try {
			request.setCharacterEncoding("UTF-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String name=request.getParameter("emp_name");
		String serach_time=request.getParameter("search_time");
		Integer currentPage = request.getParameter("page") == null ? 1 : Integer.parseInt(request.getParameter("page"));
		Integer pageSize = request.getParameter("rows") == null ? 999 : Integer.parseInt(request.getParameter("rows"));
		Employee emp=new Employee();
		emp.setName(name);
		Employeesdao dao=new Employeesdao();
		
		List<Employee>list=dao.getEmploteelist(emp,new Page(currentPage, pageSize),serach_time);
//		for(Employee emps:list) {
//			System.out.println(emps);
//		}
		//System.out.println(JSONObject.toJSONString(list));
		response.setCharacterEncoding("UTF-8");
		int total = dao.getEmplist(emp);
		Map<String, Object> ret = new HashMap<String, Object>();
		ret.put("total", total);
		ret.put("rows", list);
		String from = request.getParameter("from");
		if("combox".equals(from)){
			try {
				response.getWriter().write(JSONObject.toJSONString(list));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else{
			try {
				response.getWriter().write(JSONObject.toJSONString(ret));
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void AddEmployee(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		String name = request.getParameter("add_name");
		String add_time=request.getParameter("add_time");
		String add_first_clock=request.getParameter("add_first_clock");
		String add_end_clock=request.getParameter("add_end_clock");
		//System.out.println(name+" "+add_time+" "+add_first_clock+" "+add_end_clock);
		Date add_times=null;
		try {
			add_times=new SimpleDateFormat("yyyy-MM-dd").parse(add_time);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Employee emp=new Employee();
		emp.setName(name);
		emp.setTime(add_times);
		emp.setFirst_clock(add_first_clock);
		emp.setEnd_clock(add_end_clock);
		Employeesdao dao=new Employeesdao();
		if(dao.addemployee(emp)) {
			try {
				response.getWriter().print("success");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}else {
			try {
				response.getWriter().print("error");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//System.out.println(name+" "+add_times+" "+add_first_clock+" "+add_end_clock);
	}

	private void Listemployee(HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		try {
			request.getRequestDispatcher("/view/employee.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

LoginServlet(验证登录)

package com.item.test.Servlet;

import java.io.IOException;
import java.sql.SQLException;

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 javax.servlet.http.HttpSession;

import com.item.test.dao.Userdao;
import com.item.test.model.Userlogin;

/**
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		//获取携带的参数中有LoginOut,则退出
		String method=request.getParameter("method");
		//进行退出操作
		if(method.equals("LoginOut")) {
			LoginOut(request,response);
			return ;
		}
		String loginStatus = "loginError";
		String user=request.getParameter("user");
		String pwd = request.getParameter("pwd");
		Userlogin login=new Userlogin();
		login.setUser(user);
		login.setPwd(pwd);
		Userdao dao=new Userdao();
		try {
			Userlogin login_res=dao.login(login);
			if(login_res==null) {
				response.getWriter().print(loginStatus);
				return ;
			}
			HttpSession session=request.getSession();
			session.setAttribute("user",login_res);
			loginStatus="loginSuccess";
			response.getWriter().print(loginStatus);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void LoginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		//删除存放在session中的用户信息,并转发到登录界面
		request.getSession().removeAttribute("user");
		response.sendRedirect("view/login.jsp");
	}

	/**
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

SystemServletemp(系统管理)

package com.item.test.Servlet;

import java.io.IOException;
import java.sql.SQLException;

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.item.test.dao.Userdao;
import com.item.test.model.Userlogin;


/**
 * Servlet implementation class SystemServlet
 */
@WebServlet("/SystemServletemp")
public class SystemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String method = request.getParameter("method");
		if ("toPersonalView".equals(method)) {
			personalView(request, response);
			return;
		} else if ("EditPasswod".equals(method)) {
			try {
				editPassword(request, response);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return;
		}
		request.getRequestDispatcher("view/system.jsp").forward(request, response);
	}

	/**
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	private void personalView(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.getRequestDispatcher("view/personalView.jsp").forward(request, response);
	}
	private void editPassword(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
		// TODO Auto-generated method stub
		String password = request.getParameter("password");
		String newPassword = request.getParameter("newpassword");
		response.setCharacterEncoding("UTF-8");
		Userlogin user=(Userlogin) request.getSession().getAttribute("user");
		if(!user.getPwd().equals(password)) {
			response.getWriter().write("原密码错误!");
			return ;
		}
		Userdao dao=new Userdao();
		if(dao.editPassword(user, newPassword)) {
			response.getWriter().print("success");
		}else {
			response.getWriter().print("数据库修改错误");
		}
	}

}

实体类:

Employee(职工考勤信息,由于使用dbutiles保持和表中的字段一致)

package com.item.test.model;

import java.util.Date;

import com.alibaba.fastjson.annotation.JSONField;

public class Employee {
	private int id;
	private String name;
	@JSONField(format="yyyy-MM-dd")
	private Date time;
	private String first_clock;
	private String end_clock;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Date getTime() {
		return time;
	}
	public void setTime(Date time) {
		this.time = time;
	}
	public String getFirst_clock() {
		return first_clock;
	}
	public void setFirst_clock(String first_clock) {
		this.first_clock = first_clock;
	}
	/**
	 * @return
	 */
	public String getEnd_clock() {
		return end_clock;
	}
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", time=" + time + ", first_clock=" + first_clock
				+ ", end_clock=" + end_clock + "]";
	}
	public void setEnd_clock(String end_clock) {
		this.end_clock = end_clock;
	}
	
}

Page(前端分页)

package com.item.test.model;

public class Page {
	private int start;//起始页
	private int currentPage;//当前页
	private int pageSize;//每页显示数量
	public Page(int currentpage,int pageSize) {
		this.start=(currentpage-1)*pageSize;//根据拿到的当前页和每页显示的数量,去mysql中进行查找
		//start表示起始查询位置。
		this.currentPage=currentpage;
		this.pageSize=pageSize;
	}
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getCurrentPage() {
		return currentPage;
	}
	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
}

Userlogin(用户登录实体)

package com.item.test.model;

public class Userlogin {
	private int id;
	private String user;
	private String pwd;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUser() {
		return user;
	}
	public void setUser(String user) {
		this.user = user;
	}
	public String getPwd() {
		return pwd;
	}
	public void setPwd(String pwd) {
		this.pwd = pwd;
	}
}

dao层

Employeesdao(职工的增删查改)

package com.item.test.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.item.test.model.Employee;
import com.item.test.model.Page;
import com.item.test.utiles.C3P0Utiles;
import com.item.test.utiles.StringUtiles;

public class Employeesdao {
	QueryRunner queryRunner=new QueryRunner(C3P0Utiles.getDataSource());
	//添加员工信息
	public boolean addemployee(Employee emp) {
		String sql="insert into employees values(null,?,?,?,?)";
		int cnt=-1;
		try {
			cnt=queryRunner.update(sql,emp.getName(),emp.getTime(),emp.getFirst_clock(),emp.getEnd_clock());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cnt>0?true:false;
	}
	//查询到所有员工信息并以list集合返回
	public  List<Employee> getEmploteelist(Employee emp, Page page,String search_time) {
		List<Employee> ret = new ArrayList<Employee>();
		String sql = "select * from employees ";
		if(!StringUtiles.isEmpty(emp.getName())){
			sql += "and name like '%" + emp.getName() +"%' ";
		}
		if(search_time!=null&&!search_time.equals("")) {
			sql+=" and time like'%"+search_time+"%'";
		}
		sql += " limit " + page.getStart() + "," + page.getPageSize();
		try {
			ret=queryRunner.query(sql.replaceFirst("and", "where"), new BeanListHandler<Employee>(Employee.class));
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ret;
	}
	//获取员工的总数
	public int getEmplist(Employee emp) {
		String sql = "select count(*)as total from employees ";
		if(!StringUtiles.isEmpty(emp.getName())){
			sql += "and name like '%" + emp.getName() + "%'";
		}
		Long total=(long)-1;
		try {
			total = queryRunner.query(sql.replaceFirst("and", "where"), new ScalarHandler<Long>());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return total.intValue();
	}
	//删除员工信息
	public boolean deleteemp(int id) {
		String sql="delete from employees where id=?";
		int cnt=-1;
		try {
			cnt = queryRunner.update(sql,id);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cnt>0?true:false;
	}
	//编辑员工信息
	public boolean editemp(Employee emp) {
		// TODO Auto-generated method stub
		String sql = "update employees set name = ?,time=?,first_clock=?,end_clock=? where id=?";
		int cnt=-1;
		try {
			cnt = queryRunner.update(sql,emp.getName(),emp.getTime(),emp.getFirst_clock(),emp.getEnd_clock(),emp.getId());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return cnt>0?true:false;
	}
}

Userdao(用户的查询以及修改密码)

package com.item.test.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.item.test.model.Userlogin;
import com.item.test.utiles.C3P0Utiles;



public class Userdao {
	public Userlogin login(Userlogin user) throws SQLException{
		//查询登录用户,并返回该登录用户
		String sql="select * from login where user=? and pwd=?";
		QueryRunner queryRunner=new QueryRunner(C3P0Utiles.getDataSource());
		Userlogin res=(Userlogin) queryRunner.query(sql, new BeanHandler<>(Userlogin.class),user.getUser(),user.getPwd());
		return res;	
	}

	public boolean editPassword(Userlogin user, String pwd) throws SQLException {
		//更新密码
		String sql = "update login set pwd = '"+pwd+"' where id = " +"'"+user.getId()+"'";
		QueryRunner queryRunner=new QueryRunner(C3P0Utiles.getDataSource());
		int cnt=queryRunner.update(sql);
		return cnt>0?true:false;
	}
}

过滤器(防止非法用户进入)

Loginfilter

package com.item.test.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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截用户未登录状态下的操作
 */
@WebFilter(filterName="/Loginfilter",value="/SystemServletemp")
public class Loginfilter implements Filter {

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

	/**
	 */
	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 {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse rep = (HttpServletResponse)response;
		Object user = req.getSession().getAttribute("user");
		//验证user
		if(user==null) {
			rep.sendRedirect("index.jsp");
			return ;
		}else {
			chain.doFilter(request, response);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}

utiles(工具类)

C3P0Utiles(获取数据库的连接)

package com.item.test.utiles;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utiles {
	private static ComboPooledDataSource dataSource=new ComboPooledDataSource();
	public static DataSource getDataSource() {
		return dataSource;
	}
}

StringUtiles(字符串检查)

package com.item.test.utiles;

public class StringUtiles {
	public static boolean isEmpty(String str) {
		if(str == null || "".equals(str))return true;
		return false;
	}
}

数据库:用C3p0进行连接。

总结:返回到前端的是json格式,有一点问题就是职工实体类和数据库中的表都是Date类型,放到页面上的格式不太好,最后用了在实体类中time类型上使用注解@JSONField(format=“yyyy-MM-dd”)格式化一下即可。用的jar包fastjson。同时查询某个日期是模糊查询,可以查询某年或某月或某日或指定日期的考勤记录。

你可能感兴趣的:(java,项目)