javaWeb项目(完整)MVC-Demo02

MVC-Demo02

开发环境

java的jdk:jdk1.8.0_66
java的开发工具:eclipse(eclipse-photon)
数据库:MySQL Server 5.1
Web容器:apache-tomcat-8.5.32
MySQL可视化工具:Navicat 8.0 Lite MySQL

项目目录如下图

javaWeb项目(完整)MVC-Demo02_第1张图片

任务如下图

javaWeb项目(完整)MVC-Demo02_第2张图片

需要的jar包在这里插入图片描述

数据库表

注意:tbl_dept.sql的主键id和tbl_employee.sql的did外键是关联的
tbl_dept.sql

/*
MySQL Data Transfer
Source Host: localhost
Source Database: test
Target Host: localhost
Target Database: test
Date: 2019/9/17 15:10:43
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tbl_dept
-- ----------------------------
DROP TABLE IF EXISTS `tbl_dept`;
CREATE TABLE `tbl_dept` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `tbl_dept` VALUES ('1', '物业');
INSERT INTO `tbl_dept` VALUES ('2', '保安');
INSERT INTO `tbl_dept` VALUES ('3', '保洁');
INSERT INTO `tbl_dept` VALUES ('4', '厨房');
INSERT INTO `tbl_dept` VALUES ('5', '电工');

tbl_employee.sql

/*
MySQL Data Transfer
Source Host: localhost
Source Database: test
Target Host: localhost
Target Database: test
Date: 2019/9/17 15:10:02
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for tbl_employee
-- ----------------------------
DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `email` varchar(255) DEFAULT NULL,
  `did` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `tbl_employee_id` (`did`),
  CONSTRAINT `tbl_employee_id` FOREIGN KEY (`did`) REFERENCES `tbl_dept` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `tbl_employee` VALUES ('1', 'zhangs', '[email protected]', '1');
INSERT INTO `tbl_employee` VALUES ('2', 'lisi', '[email protected]', '2');
INSERT INTO `tbl_employee` VALUES ('3', 'ww', '[email protected]', '1');
INSERT INTO `tbl_employee` VALUES ('5', 'ff', '[email protected]', '1');
INSERT INTO `tbl_employee` VALUES ('6', 'vv', '[email protected]', '2');
INSERT INTO `tbl_employee` VALUES ('7', 'd', 'd', '1');
INSERT INTO `tbl_employee` VALUES ('8', 'c', 'c', '1');
INSERT INTO `tbl_employee` VALUES ('10', 'dd', 'dd', '2');
INSERT INTO `tbl_employee` VALUES ('11', 'dd', 'ddd', '1');
INSERT INTO `tbl_employee` VALUES ('12', 'dd', 'fff', '1');
INSERT INTO `tbl_employee` VALUES ('13', '王阳', '[email protected]', '5');

数据库设计表

tbl_dept.sql
javaWeb项目(完整)MVC-Demo02_第3张图片
tbl_employee.sql
javaWeb项目(完整)MVC-Demo02_第4张图片
==tbl_employee.sql外键 did ==
在这里插入图片描述

执行效果如图

执行WebContent下的index.jsp
在这里插入图片描述
javaWeb项目(完整)MVC-Demo02_第5张图片
在这里插入图片描述
在这里插入图片描述
javaWeb项目(完整)MVC-Demo02_第6张图片

c3p0的配置文件

c3p0-config.xml



	
	
		10
		30
		100
		10
		200
	

	
	
		com.mysql.jdbc.Driver
		jdbc:mysql://localhost:3306/demo
		root
		123456
		10
		30
		100
		10
		200
	


src下

com.mvc.demo.action

Action.java

package com.mvc.demo.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface Action {
	public void execute(HttpServletRequest request,HttpServletResponse response);
}

com.mvc.demo.action.employee

DeleteEmployeeAction.java

package com.mvc.demo.action.employee;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.demo.action.Action;
import com.mvc.demo.dao.EmployeeDao;

public class DeleteEmployeeAction implements Action {

	private EmployeeDao employeeDao;

	public DeleteEmployeeAction() {
		employeeDao = new EmployeeDao();
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		Integer id=new Integer(request.getParameter("id"));
		request.setAttribute("msg", "删除员工信息失败,点击这里返回重新操作");
		if(employeeDao.deleteEmployeeById(id)) {
			request.setAttribute("msg", "删除员工信息成功,点击这里查看操作结果");
		}
		try {
			request.getServletContext().getRequestDispatcher("/WEB-INF/employee/message.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

ForwardEmployeeAction.java

package com.mvc.demo.action.employee;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.demo.action.Action;
import com.mvc.demo.dao.DeptDao;

public class ForwardEmployeeAction implements Action {

	private DeptDao deptDao;

	public ForwardEmployeeAction() {
		deptDao = new DeptDao();
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setAttribute("list", deptDao.queryAllDept());
			request.getServletContext().getRequestDispatcher("/WEB-INF/employee/insert.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

InsertEmployeeAction.java

package com.mvc.demo.action.employee;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.demo.action.Action;
import com.mvc.demo.dao.EmployeeDao;
import com.mvc.demo.pojo.Employee;

public class InsertEmployeeAction implements Action {
	private EmployeeDao employeeDao;

	public InsertEmployeeAction() {
		employeeDao = new EmployeeDao();
	}

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		String name=request.getParameter("name");
		String email=request.getParameter("email");
		Integer did=new Integer(request.getParameter("did"));
		Employee employee=new Employee(name, email, did);
		request.setAttribute("msg", "添加员工信息失败,点击这里返回重新操作");
		if(employeeDao.insertEmployee(employee)) {
			request.setAttribute("msg", "添加员工信息成功,点击这里查看操作结果");
		}
		try {
			request.getServletContext().getRequestDispatcher("/WEB-INF/employee/message.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

ListEmployeeAction.java

package com.mvc.demo.action.employee;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mvc.demo.action.Action;
import com.mvc.demo.dao.DeptDao;
import com.mvc.demo.dao.EmployeeDao;
import com.mvc.demo.pojo.Employee;

public class ListEmployeeAction implements Action{
	
	private EmployeeDao employeeDao;
	private DeptDao deptDao;
	
	public ListEmployeeAction() {
		employeeDao=new EmployeeDao();
		deptDao=new DeptDao();
	}
	
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		ArrayList list=employeeDao.queryAllEmployee();
		HashMap map=deptDao.getDeptName(list);
		request.setAttribute("list",list);
		request.setAttribute("map",map);
		try {
			request.getServletContext().getRequestDispatcher("/WEB-INF/employee/list.jsp").forward(request, response);
		} catch (ServletException | IOException e) {
			e.printStackTrace();
		}
	}

}

com.mvc.demo.controller

ActionServlet.java

package com.mvc.demo.controller;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

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

import com.mvc.demo.action.Action;

public class ActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Properties properties;
	
	public void init() {
//		注意:
//		因为web应用程序是运行在服务器上的,不能直接通过开发目录下的文件路径定义文件.
		String file=Thread.currentThread().getContextClassLoader().getResource("config.properties").getFile();
		properties=new Properties();
		try {
			properties.load(new FileInputStream(file));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		String struri=request.getRequestURI();
		struri=struri.substring(struri.lastIndexOf("/")+1);
		String className=properties.getProperty(struri);
		try {
			Action action = (Action) Class.forName(className).newInstance();
			action.execute(request,response);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

com.mvc.demo.dao

DeptDao.java

package com.mvc.demo.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;

import com.mvc.demo.pojo.Dept;
import com.mvc.demo.pojo.Employee;
import com.mvc.demo.util.C3P0Utils;

public class DeptDao {
	public String getDeptNameById(Integer id) {
		String name=null;
		String sql="select name from tbl_dept where id="+id;
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		try {
			con=C3P0Utils.getConn();
			st=con.createStatement();
			rs=st.executeQuery(sql);
			if(rs.next()) {
				name=rs.getString("name");
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			C3P0Utils.closeJDBC(con, st, rs);
		}
		return name;
	}

//	根据所有员工部门编号获得部门名称.返回HashMap
	public HashMap getDeptName(ArrayList elist) {
		HashMap map = new HashMap();
		for (Employee employee : elist) {
			Integer did=employee.getDid();
			String dname=getDeptNameById(did);
			map.put(did, dname);
		}
		return map;
	}

//	获得所有部门信息
	public ArrayList queryAllDept(){
		ArrayList list=new ArrayList();
		String sql="select id,name from tbl_dept";
		Connection con=null;
		Statement st=null;
		ResultSet rs=null;
		try {
			con=C3P0Utils.getConn();
			st=con.createStatement();
			rs=st.executeQuery(sql);
			while(rs.next()) {
				Dept dept=new Dept();
				dept.setId(rs.getInt("id"));
				dept.setName(rs.getString("name"));
				list.add(dept);
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			C3P0Utils.closeJDBC(con, st, rs);
		}
		return list;
	}
	
}	

EmployeeDao.java

package com.mvc.demo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;

import com.mvc.demo.pojo.Employee;
import com.mvc.demo.util.C3P0Utils;

public class EmployeeDao {

//	添加员工信息
	public boolean insertEmployee(Employee employee) {
		boolean flag = false;
		
		String sql = "insert into tbl_employee values(default,?,?,?)";
		Connection con = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			con = C3P0Utils.getConn();
			st = con.prepareStatement(sql);
			st.setString(1, employee.getName());
			st.setString(2, employee.getEmail());
			st.setInt(3, employee.getDid());
			if(st.executeUpdate()>0) {
				flag=true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			C3P0Utils.closeJDBC(con, st, rs);
		}
		
		return flag;
	}

//	查询所有员工信息
	public ArrayList queryAllEmployee() {
		ArrayList list = new ArrayList();
		String sql = "select id,name,email,did from tbl_employee";
		Connection con = null;
		Statement st = null;
		ResultSet rs = null;
		try {
			con = C3P0Utils.getConn();
			st = con.createStatement();
			rs = st.executeQuery(sql);
			while (rs.next()) {
				Employee employee = new Employee();
				employee.setId(rs.getInt("id"));
				employee.setName(rs.getString("name"));
				employee.setEmail(rs.getString("email"));
				employee.setDid(rs.getInt("did"));
				list.add(employee);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			C3P0Utils.closeJDBC(con, st, rs);
		}
		return list;
	}

//	根据编号删除员工信息
	public boolean deleteEmployeeById(Integer id) {
		boolean flag = false;
		String sql = "delete from tbl_employee where id=?";
		Connection con = null;
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			con = C3P0Utils.getConn();
			st = con.prepareStatement(sql);
			st.setInt(1,id);
			if(st.executeUpdate()>0) {
				flag=true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			C3P0Utils.closeJDBC(con, st, rs);
		}
		return flag;
	}
}

com.mvc.demo.pojo

Dept.java

package com.mvc.demo.pojo;

public class Dept {
	private Integer id;
	private String name;

	public Dept() {
		super();
	}

	public Dept(String name) {
		super();
		this.name = name;
	}

	public Dept(Integer id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

Employee.java

package com.mvc.demo.pojo;

public class Employee {
	private Integer id;
	private String name;
	private String email;
	private Integer did;

	public Employee() {
		super();
	}

	public Employee(String name, String email, Integer did) {
		super();
		this.name = name;
		this.email = email;
		this.did = did;
	}

	public Employee(Integer id, String name, String email, Integer did) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
		this.did = did;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Integer getDid() {
		return did;
	}

	public void setDid(Integer did) {
		this.did = did;
	}

}

com.mvc.demo.util

C3P0Utils.java

package com.mvc.demo.util;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class C3P0Utils {
	static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");

	public static Connection getConn() {
		try {
			Connection conn = dataSource.getConnection();
			return conn;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public static void closeJDBC(Connection con,Statement st,ResultSet rs) {
		if(rs!=null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if(st!=null) {
			try {
				st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		try {
			if(con!=null && con.isClosed()==false) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}

config.properties

#Employee
employee-list.action=com.mvc.demo.action.employee.ListEmployeeAction
employee-insertforward.action=com.mvc.demo.action.employee.ForwardEmployeeAction
employee-insert.action=com.mvc.demo.action.employee.InsertEmployeeAction
employee-delete.action=com.mvc.demo.action.employee.DeleteEmployeeAction

WebContent下

WEB-INF/employee
insert.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




Insert title here


	

添加员工信息

员工姓名:

电子邮箱:

所在部门:

list.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




Insert title here


	

员工信息列表

员工编号 员工姓名 电子邮箱 所在部门 数据管理
${employee.id} ${employee.name} ${employee.email} ${map[employee.did]} 修改 | 删除
添加员工信息

message.jsp

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




Insert title here


	

${msg}

WEB-INF下
web.xml



	MVC-Demo02
	
		index.html
		index.htm
		index.jsp
		default.html
		default.htm
		default.jsp
	
	
		
		ActionServlet
		ActionServlet
		com.mvc.demo.controller.ActionServlet
	
	
		ActionServlet
		*.action
	

WebContent下
index.jsp

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




Insert title here


	部门管理
	员工管理


你可能感兴趣的:(MVC,Java,JavaWeb,MySQL)