1. 程式人生 > 其它 >Servlet之員工管理系統

Servlet之員工管理系統

技術標籤:servletjavaoraclejsp資料庫

目錄

1.專案結構

2.db.properties

3.WEB-INF下的web.xml

4.dao中的EmployeeDAO類

5.entity中的Employee類

6.util中的DBUtil類

7.web中對的ActionServlet類

8.hello.jsp

date.jsp

empList1.jsp

empList2.jsp

empList3.jsp


1.專案結構

2.db.properties

連線資料庫

# database connection parameters
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:xe
user=root
pwd=root
# datasource parameters
init_size=1
max_size=3

3.WEB-INF下的web.xml

<servlet>
  	<servlet-name>actionServlet</servlet-name>
  	<servlet-class>web.ActionServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>actionServlet</servlet-name>
  	<url-pattern>*.do</url-pattern>
 </servlet-mapping>

4.dao中的EmployeeDAO類

public class EmployeeDAO {
	public void save(Employee e){
		Connection conn = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "INSERT INTO t_emp "
					+ "VALUES(t_emp_seq.nextval,?,?,?)";
			PreparedStatement ps = 
				conn.prepareStatement(sql);
			ps.setString(1, e.getEname());
			ps.setDouble(2, e.getSalary());
			ps.setInt(3, e.getAge());
			ps.executeUpdate();
		} catch (SQLException e1) {
			//step1.記日誌(保留現場)
			e1.printStackTrace();
			/*
			 * step2.看異常能否恢復,如果不能夠
			 * 恢復(比如,資料庫服務暫停等,一般我們
			 * 稱之為系統異常),要提示使用者稍後重試。
			 * 如果能夠恢復,則立即恢復。
			 */
			throw new RuntimeException(e1);
		}finally{
			DBUtil.close(conn);
		}
		
	}
	
	public List<Employee> findAll(){
		List<Employee> employees = 
			new ArrayList<Employee>();
		Connection conn = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "SELECT * FROM t_emp";
			PreparedStatement ps = 
				conn.prepareStatement(sql);
			ResultSet rs = 
					ps.executeQuery();
			
			while(rs.next()){
				Employee e = new Employee();
				e.setId(rs.getInt("id"));
				e.setEname(rs.getString("ename"));
				e.setSalary(rs.getDouble("salary"));
				e.setAge(rs.getInt("age"));
				employees.add(e);
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			DBUtil.close(conn);
		}
		return employees;
	}
	
	public void delete(int id){
		Connection conn = null;
		try {
			conn = DBUtil.getConnection();
			String sql = 
					"DELETE FROM t_emp WHERE id=?";
			PreparedStatement ps = 
				conn.prepareStatement(sql);
			ps.setInt(1, id);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}finally{
			DBUtil.close(conn);
		}
	}
	
	public Employee findById(int id){
		Employee e = null;
		Connection conn = null;
		try {
			conn = DBUtil.getConnection();
			String sql = "SELECT * FROM t_emp "
					+ "WHERE id = ?";
			PreparedStatement ps = 
				conn.prepareStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = 
					ps.executeQuery();
			if(rs.next()){
				e = new Employee();
				e.setId(id);
				e.setEname(rs.getString("ename"));
				e.setSalary(rs.getDouble("salary"));
				e.setAge(rs.getInt("age"));
			}
		} catch (SQLException e1) {
			e1.printStackTrace();
			throw new RuntimeException(e1);
		}finally{
			DBUtil.close(conn);
		}
		return e;
	}
	
	public void update(Employee e){
		Connection conn = null;
		try {
			conn = DBUtil.getConnection();
			String sql = 
					"UPDATE t_emp SET ename=?,"
					+ "salary=?,age=? WHERE id=?";
			PreparedStatement ps = 
				conn.prepareStatement(sql);
			ps.setString(1, e.getEname());
			ps.setDouble(2,e.getSalary());
			ps.setInt(3, e.getAge());
			ps.setInt(4, e.getId());
			ps.executeUpdate();
		} catch (SQLException e1) {
			e1.printStackTrace();
			throw new RuntimeException(e1);
		}finally{
			DBUtil.close(conn);
		}
	}
}

5.entity中的Employee類

public class Employee {
	private int id;
	private String ename;
	private double salary;
	private int age;
	
	
	@Override
	public String toString() {
		return "Employee [id=" + id 
				+ ", ename=" + ename 
				+ ", salary=" + salary + ", age=" + age + "]";
	}
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getEname() {
		return ename;
	}
	public void setEname(String ename) {
		this.ename = ename;
	}
	public double getSalary() {
		return salary;
	}
	public void setSalary(double salary) {
		this.salary = salary;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}

6.util中的DBUtil類

public class DBUtil {
	private static BasicDataSource ds;
	static {
		//載入引數
		Properties p = new Properties();
		try {
			p.load(DBUtil.class.getClassLoader()
				.getResourceAsStream("db.properties"));
			//獲取這些引數
			String driver = p.getProperty("driver");
			String url = p.getProperty("url");
			String user = p.getProperty("user");
			String pwd = p.getProperty("pwd");
			String initSize = p.getProperty("init_size");
			String maxSize = p.getProperty("max_size");
			//建立連線池
			ds = new BasicDataSource();
			//給它設定引數
			ds.setDriverClassName(driver);
			ds.setUrl(url);
			ds.setUsername(user);
			ds.setPassword(pwd);
			ds.setInitialSize(Integer.parseInt(initSize));
			ds.setMaxActive(Integer.parseInt(maxSize));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(
				"載入db.properties失敗", e);
		}
	}
	
	/**
	 * 由連線池建立的連線,其實現類由連線池提供.
	 */
	public static Connection getConnection() 
		throws SQLException {
		return ds.getConnection();
	}
	
	/**
	 * 連線池提供的實現類,其close方法內部邏輯是,
	 * 將連線歸還給連線池,即它會清空連線物件中的資料,
	 * 並且將連線標記為空閒態.
	 */
	public static void close(Connection conn) {
		if(conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(
					"歸還連線失敗", e);
			}
		}
	}
	
	public static void rollback(Connection conn) {
		if(conn != null) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(
					"回滾事務失敗", e);
			}
		}
	}
	
}

7.web中對的ActionServlet類

public class ActionServlet extends HttpServlet{
	public void service(
			HttpServletRequest request,
			HttpServletResponse response)
	throws ServletException,IOException{
		
		request.setCharacterEncoding("utf-8");
		response.setContentType(
				"text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		
		String uri = request.getRequestURI();
		String action = 
			uri.substring(uri.lastIndexOf("/"),
					uri.lastIndexOf("."));
		System.out.println("action:" + action);
		
		if("/list".equals(action)){
			EmployeeDAO dao = 
					new EmployeeDAO();
			try{
				List<Employee> employees = 
						dao.findAll();
				//step1.綁訂資料到request。
				request.setAttribute("employees",
						employees);
				//step2.獲得轉發器
				RequestDispatcher rd = 
					request.getRequestDispatcher(
							"empList3.jsp");
				//step3.轉發
				rd.forward(request, response);
			}catch(Exception e){
				e.printStackTrace();
				out.println("系統繁忙,稍後重試");
			}
		}else if("/add".equals(action)){
			//處理 新增員工的請求
			//讀取員工資訊
			String ename =
					request.getParameter("ename");
			String salary = 
					request.getParameter("salary");
			String age = 
					request.getParameter("age");
			System.out.println(ename + " "
					+ salary + " " + age);
			
			//將員工資訊插入到資料庫
			EmployeeDAO dao = new EmployeeDAO();
			Employee e = new Employee();
			e.setEname(ename);
			e.setSalary(Double.parseDouble(salary));
			e.setAge(Integer.parseInt(age));
			try{
				dao.save(e);
				
				//重定向到員工列表
				response.sendRedirect("list.do");
				
			}catch(Exception e1){
				e1.printStackTrace();
				out.println("<h1>系統繁忙,稍後重試</h1>");
			}
			//容器會自動關閉out,這兒不呼叫out.close()也可以
			out.close();
		}
	}
}

8.hello.jsp

<%@ page import="java.util.*"  
contentType="text/html;charset=utf-8"
pageEncoding="utf-8"%>
<html>
	<head></head>
	<body style="font-size:30px;">
		待我長髮及腰,用來拖地可好 <br/>
		current time:
		<%
			Date date = new Date();
			out.println(date);
		%>
		<br/>
		
		current time2: <%= new Date()%>
		
		<%
			for(int i = 0; i < 100; i ++){
				out.println("Hello World<br/>");
			}
		%>
	</body>
</html>

date.jsp

<%@ page contentType="text/html; charset=utf-8" 
pageEncoding="utf-8" %>
<%@ page import="java.util.*,java.text.*" %>
<html>
	<head></head>
	<body style="font-size:30px;">
		今天是:
		<%
			Date date = new Date();
			SimpleDateFormat sdf = 
					new SimpleDateFormat("yyyy-MM-dd");
		%>
		<%=sdf.format(date)%>
	</body>
</html>

empList1.jsp

<%@ page pageEncoding="utf-8" 
contentType="text/html;charset=utf-8" %>
<%@ page import="entity.*,dao.*,java.util.*" %>
<html>
	<head>
		<style>
			.row1{
				background-color:#fff8dc;
			}
			.row2{
				background-color:#f0f0f0;
			}
		</style>
	</head>
	<body style="font-size:30px;">
		<table width="60%" border="1" 
			cellpadding="0" cellspacing="0">
			<tr>
				<td>ID</td><td>姓名</td>
				<td>薪水</td><td>年齡</td>
			</tr>
			<%
				EmployeeDAO dao = new EmployeeDAO();
				List<Employee> employees = 
						dao.findAll();
				for(int i = 0; i < employees.size(); i ++){
					Employee e = employees.get(i);
					%>
					<tr class="row<%=(i % 2 + 1)%>">
						<td><%=e.getId()%></td>
						<td><%=e.getEname()%></td>
						<td><%=e.getSalary()%></td>
						<td><%=e.getAge()%></td>
					</tr>
					<%
				}
			%>
		</table>
	</body>
</html>

empList2.jsp

<%@ page pageEncoding="utf-8" 
contentType="text/html; charset=utf-8" %>
<%@ page import="java.util.*,java.text.*,dao.*,entity.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title>員工管理</title>
		<link rel="stylesheet" 
		type="text/css" href="css/style.css" />
	</head>
	<body>
		<div id="wrap">
			<div id="top_content"> 
				<div id="header">
					<div id="rightheader">
						<p>
							<%
								Date date = new Date();
								SimpleDateFormat sdf = 
									new SimpleDateFormat("yyyy-MM-dd");
							%>
							<%=sdf.format(date)%>
							<br />
						</p>
					</div>
					<div id="topheader">
						<h1 id="title">
							<a href="#">main</a>
						</h1>
					</div>
					<div id="navigation">
					</div>
				</div>
				<div id="content">
					<p id="whereami">
					</p>
					<h1>
						員工列表
					</h1>
					<table class="table">
						<tr class="table_header">
							<td>
								ID
							</td>
							<td>
								姓名
							</td>
							<td>
								薪水
							</td>
							<td>
								年齡
							</td>
							<td>
								操作
							</td>
						</tr>
						<%
							EmployeeDAO dao = 
								new EmployeeDAO();
							List<Employee> employees = 
								dao.findAll();
							for(int i = 0; i < employees.size(); i ++){
								Employee e = employees.get(i);
								%>
						<tr class="row<%=(i % 2 + 1)%>">
							<td>
								<%=e.getId()%>
							</td>
							<td>
								<%=e.getEname()%>
							</td>
							<td>
								<%=e.getSalary()%>
							</td>
							<td>
								<%=e.getAge()%>
							</td>
							<td>
								<a href="emplist.html">刪除</a>&nbsp;
								<a href="updateEmp.html">修改</a>
							</td>
						</tr>
								<%
							}
						%>
					</table>
					<p>
						<input type="button" class="button" 
						value="新增員工" onclick="location='addEmp.html'"/>
					</p>
				</div>
			</div>
			<div id="footer">
				<div id="footer_bg">
				[email protected]
				</div>
			</div>
		</div>
	</body>
</html>

empList3.jsp

<%@ page pageEncoding="utf-8" 
contentType="text/html; charset=utf-8" %>
<%@ page import="java.util.*,java.text.*,entity.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title>員工管理</title>
		<link rel="stylesheet" 
		type="text/css" href="css/style.css" />
	</head>
	<body>
		<div id="wrap">
			<div id="top_content"> 
				<div id="header">
					<div id="rightheader">
						<p>
							<%
								Date date = new Date();
								SimpleDateFormat sdf = 
									new SimpleDateFormat("yyyy-MM-dd");
							%>
							<%=sdf.format(date)%>
							<br />
						</p>
					</div>
					<div id="topheader">
						<h1 id="title">
							<a href="#">main</a>
						</h1>
					</div>
					<div id="navigation">
					</div>
				</div>
				<div id="content">
					<p id="whereami">
					</p>
					<h1>
						員工列表
					</h1>
					<table class="table">
						<tr class="table_header">
							<td>
								ID
							</td>
							<td>
								姓名
							</td>
							<td>
								薪水
							</td>
							<td>
								年齡
							</td>
							<td>
								操作
							</td>
						</tr>
						<%
							
							List<Employee> employees = 
								(List<Employee>)request.getAttribute(
										"employees");
							for(int i = 0; i < employees.size(); i ++){
								Employee e = employees.get(i);
								%>
						<tr class="row<%=(i % 2 + 1)%>">
							<td>
								<%=e.getId()%>
							</td>
							<td>
								<%=e.getEname()%>
							</td>
							<td>
								<%=e.getSalary()%>
							</td>
							<td>
								<%=e.getAge()%>
							</td>
							<td>
								<a href="emplist.html">刪除</a>&nbsp;
								<a href="updateEmp.html">修改</a>
							</td>
						</tr>
								<%
							}
						%>
					</table>
					<p>
						<input type="button" class="button" 
						value="新增員工" onclick="location='addEmp.html'"/>
					</p>
				</div>
			</div>
			<div id="footer">
				<div id="footer_bg">
				[email protected]
				</div>
			</div>
		</div>
	</body>
</html>