Top

JAVA SERVLETJSP DAY05

  1. 员工管理——使用转发、JSP实现完整的增删改查
  2. 员工管理——添加异常处理
  3. 路径的练习
  4. 员工管理——注册

1 员工管理——使用转发、JSP实现完整的增删改查

1.1 问题

将美工制作的页面转变成JSP页面,使用转发、重定向等技术实现完整的员工管理功能

1.2 方案

功能的完成顺序为查询(增加(删除(修改。在查询功能中,JSP页面负责展示,数据来源使用转发的技术从request对象中获取。请求的地址映射规则为后缀匹配模式,由一个ActionServlet处理分发请求。

1.3 步骤

步骤一:使用MyEclipse创建Servlet

在工程的src目录下,右键新建选择Servlet,通过向导进行Servlet的相关配置。如图-1

图– 1

填写Servlet所在的包为web,名称为ActionServlet。需要包含的方法只保留doGet的复选框。如图-2

图– 2

点击Next之后为配置路径的步骤。名字可以按需修改,Mapping填写“*.do”为后缀匹配模式,Display Name和Description可以不用填写。

图– 3

查看生成的文件中的代码,修改doGet的方法名称为service,保留前面两行用于设置输出的中文。其余的输出语句删除。如图-4

图 - 4

步骤二:将前面工程中的dao包和entity包拷贝到src中。

dao包下的DBUtil.java文件为获取连接关闭连接的工具类,EmployeeDAO.java文件为针对Employee的数据操作对象。ActionServlet.java文件为处理请求的控制类。如图-5所示为完整结构。

图 - 5

步骤三:完成员工信息显示功能

修改ActionServlet中的service方法,判断动作是否是list,查询数据后存入request中,并转发给listEmp.jsp页面。

修改service方法如图-6

图 - 6

WebRoot下面新建listEmp.jsp页面,复制静态代码至该页面,复制图片、css,修改page指令。项目结构如图-7,添加循环输出如图-8

图- 7

图 - 8

运行效果如图-9

图 - 9

步骤四:完成增加员工信息功能

新建addEmp.jsp,表单的action值为add.do。修改ActionServlet,添加对增加动作的处理。添加成功后,重定向到list.do,查看全部员工信息。

图 - 10

图– 11

运行结果

图 - 12

步骤五:完成删除员工信息功能

修改listEmp.jsp中删除操作的链接地址,修改ActionServler的判断分支。

图– 13

图– 14

图- 15

步骤六:完成修改员工信息功能

修改listEmp.jsp页面的修改功能的链接,修改ActionServlet.java的判断,添加update.jsp页面,能够成功加载某一个员工信息后,再修改update.jsp页面的action地址,修改ActionServlet的判断,完成修改保存后重定向到listEmp.jsp页面。

工程结果如图-16

图- 16

修改ActionServlet,添加加载的判断

图– 17

修改listEmp.jsp页面的修改链接的地址

图– 18

修改uploadEmp.jsp页面,读取绑定数据,将数据显示到表单中,如图-19

图– 19

运行,查看是否能够正确加载员工信息,如图-20

图 - 20

修改updateEmp.jsp页面的表单提交,修改ActionServlet,保存成功后重定向到list.do

图– 21

ActionServlet.java文件修改如图-22

图 - 22

1.4 完整代码

DBUtil.java和EmployeeDAO.java和Employee.java文件代码参考前面的练习。

ActionServlet.java代码如下:

	package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import dao.EmployeeDAO;
import dao.UserDAO;
import entity.Employee;
import entity.User;

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("/")+1,
									  uri.lastIndexOf("."));
		
		//创建员工管理操作类
		EmployeeDAO dao = new EmployeeDAO();
		
		//判断请求动作种类,分不同种类情况处理
		if(action.equals("list")){//员工信息列表
			try {
				List<Employee> emps = dao.findAll();
				request.setAttribute("emps", emps);
				request.getRequestDispatcher("listEmp.jsp").
									forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if(action.equals("add")){//增加员工
			String name = request.getParameter("name");
			double salary = Double.parseDouble(request.
					    getParameter("salary"));
			int age = Integer.parseInt(request.getParameter("age"));
			Employee emp = new Employee();
			emp.setName(name);
			emp.setSalary(salary);
			emp.setAge(age);
			try {
				dao.save(emp);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();	
			}
		}else if(action.equals("delete")){//删除员工
			int id = Integer.parseInt(request.getParameter("id"));
			try {
				dao.delete(id);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}else if(action.equals("load")){//加载某个员工
			int id = Integer.parseInt(request.getParameter("id"));			
			try {
				Employee emp = dao.findById(id);
				request.setAttribute("emp", emp);
				request.getRequestDispatcher("updateEmp.jsp").
				forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}else if(action.equals("update")){//更新员工
			int id = Integer.parseInt(request.getParameter("id"));
			String name = request.getParameter("name");
			double salary = Double.parseDouble(
					request.getParameter("salary"));
			int age = Integer.parseInt(request.getParameter("age"));
			Employee emp = new Employee();
			emp.setName(name);
			emp.setSalary(salary);
			emp.setAge(age);
			emp.setId(id);
			try {
				dao.modify(emp);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}

listEmp.jsp文件代码如下:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="entity.*,java.util.*"%>

<html>
<head>
<title>员工列表</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<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>
						2009/11/20 <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>编号</td>
						<td>姓名</td>
						<td>薪水</td>
						<td>年龄</td>
						<td>操作</td>
					</tr>
					<%
						List<Employee> emps = (List<Employee>) request.
						                             getAttribute("emps");
						for (int i = 0; i < emps.size(); i++) {
							Employee emp = emps.get(i);
					%>
					<tr class="row<%=i % 2 + 1%>">
						<td><%=emp.getId()%></td>
						<td><%=emp.getName()%></td>
						<td><%=emp.getSalary()%></td>
						<td><%=emp.getAge()%></td>
						<td>
				<a href="delete.do?id=<%=emp.getId()%>" 
				onclick="return confirm('是否确认删除<%=emp.getName()%>信息?');">删除</a>
				&nbsp;
				<a href="load.do?id=<%=emp.getId()%>">修改</a></td>
					</tr>
					<%
						}
					%>
				</table>
				<p>
					<input type="button" class="button" value="增加员工"
						onclick="location='addEmp.jsp'" />
				</p>
			</div>
		</div>
		<div id="footer">
			<div id="footer_bg">ABC@126.com</div>
		</div>
	</div>
</body>
</html>

addEmp.jsp文件代码如下:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>增加员工</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<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>
						2009/11/20 <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>
				<form action="add.do" method="post">
					<table cellpadding="0" cellspacing="0" border="0"
						class="form_table">
						<tr>
							<td valign="middle" align="right">姓名:</td>
							<td valign="middle" align="left"><input type="text"
								class="inputgri" name="name" /></td>
						</tr>
						<tr>
							<td valign="middle" align="right">薪水:</td>
							<td valign="middle" align="left"><input type="text"
								class="inputgri" name="salary" /></td>
						</tr>
						<tr>
							<td valign="middle" align="right">年龄:</td>
							<td valign="middle" align="left"><input type="text"
								class="inputgri" name="age" /></td>
						</tr>
					</table>
					<p>
						<input type="submit" class="button" value="增加" />
					</p>
				</form>
			</div>
		</div>
		<div id="footer">
			<div id="footer_bg">ABC@126.com</div>
		</div>
	</div>
</body>
</html>

updateEmp.jsp文件代码如下:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="entity.*" %>
<html>
	<head>
		<title>修改员工信息</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<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>
								2009/11/20
								<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>
					<%
						Employee emp = (Employee)request.getAttribute("emp");					
					%>
					<form action="update.do?id=<%=emp.getId()%>" method="post">
						<table cellpadding="0" cellspacing="0" border="0"
							class="form_table">
							<tr>
								<td valign="middle" align="right">
									编号:
								</td>
								<td valign="middle" align="left">
									<%=emp.getId()%>
								</td>
							</tr>
							<tr>
								<td valign="middle" align="right">
									姓名:
								</td>
								<td valign="middle" align="left">
									<input type="text" class="inputgri" name="name" value="<%=emp.getName()%>"/>
								</td>
							</tr>
							<tr>
								<td valign="middle" align="right">
									薪水:
								</td>
								<td valign="middle" align="left">
									<input type="text" class="inputgri" name="salary" value="<%=emp.getSalary()%>"/>
								</td>
							</tr>
							<tr>
								<td valign="middle" align="right">
									年龄:
								</td>
								<td valign="middle" align="left">
									<input type="text" class="inputgri" name="age" value="<%=emp.getAge()%>"/>
								</td>
							</tr>
						</table>
						<p>
							<input type="submit" class="button" value="修改" />
						</p>
					</form>
				</div>
			</div>
			<div id="footer">
				<div id="footer_bg">
					ABC@126.com
				</div>
			</div>
		</div>
	</body>
</html>

2 员工管理——添加异常处理

2.1 问题

解决系统在出现异常时的不友好提示,避免客户端看到有关错误的任何说明。

2.2 方案

两种解决方法,一种是编程式处理,即在捕获到异常时,绑定错误提示信息,转发到指定的错误页面。一种是声明式处理,即在捕获到异常时,将其封装成ServletException后抛给容器,在web.xml中添加配置,在捕获到异常后由容器控制着跳转到指定的错误页面。

2.3 步骤

步骤一:添加编程式处理的判断

图 - 23

步骤二:新建error.jsp页面,读取绑定的错误信息

图 - 24

步骤三:添加声明式处理的代码

图 - 25

步骤四:配置web.xml文件

图 - 26

2.4 完整代码

ActionServlet.java文件代码:

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import dao.EmployeeDAO;
import dao.UserDAO;
import entity.Employee;
import entity.User;

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("/")+1,
									  uri.lastIndexOf("."));
		
		//创建员工管理操作类
		EmployeeDAO dao = new EmployeeDAO();
		
		//判断请求动作种类,分不同种类情况处理
		if(action.equals("list")){//员工信息列表
			try {
				List<Employee> emps = dao.findAll();
				request.setAttribute("emps", emps);
				request.getRequestDispatcher("listEmp.jsp").
									forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
				//编程式的处理异常
				request.setAttribute("err_msg", "系统出错,请重试");
				request.getRequestDispatcher("error.jsp").
									forward(request, response);
			}
		}else if(action.equals("add")){//增加员工
			String name = request.getParameter("name");
			double salary = Double.parseDouble(request.
					    getParameter("salary"));
			int age = Integer.parseInt(request.getParameter("age"));
			Employee emp = new Employee();
			emp.setName(name);
			emp.setSalary(salary);
			emp.setAge(age);
			try {
				dao.save(emp);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
				//将异常抛给容器,在web.xml中添加声明,变成声明式的处理异常
				throw new ServletException(e);
			}
		}else if(action.equals("delete")){//删除员工
			int id = Integer.parseInt(request.getParameter("id"));
			try {
				dao.delete(id);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}else if(action.equals("load")){//加载某个员工
			int id = Integer.parseInt(request.getParameter("id"));			
			try {
				Employee emp = dao.findById(id);
				request.setAttribute("emp", emp);
				request.getRequestDispatcher("updateEmp.jsp").
				forward(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}else if(action.equals("update")){//更新员工
			int id = Integer.parseInt(request.getParameter("id"));
			String name = request.getParameter("name");
			double salary = Double.parseDouble(
					request.getParameter("salary"));
			int age = Integer.parseInt(request.getParameter("age"));
			Employee emp = new Employee();
			emp.setName(name);
			emp.setSalary(salary);
			emp.setAge(age);
			emp.setId(id);
			try {
				dao.modify(emp);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}

web.xml文件代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="/java.sun.com/xml/ns/javaee" 
	xmlns:xsi="/www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="/java.sun.com/xml/ns/javaee 
	/java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name></display-name>
<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>
	
<error-page>
	<exception-type>javax.servlet.ServletException</exception-type>
	<location>/error.jsp</location>
</error-page>
</web-app>

error.jsp文件代码:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
	<head>	
		<title>错误提醒</title>
	</head>
	<body style="font-size:24px">
	
	<%=request.getAttribute("err_msg")==null
	   ?"":request.getAttribute("err_msg")%><Br>
	
	系统异常	<a href="list.do">返回</a>
	</body>
</html>

3 路径的练习

3.1 问题

绝对路径和相对路径的练习。

3.2 方案

在工程中添加biz01和biz02两个文件夹,分别包含a1.jsp和a2.jsp两个文件,并且使用相对路径和绝对路径两种方式完成a1和a2之间的链接跳转。再增加一个SomeServlet,实现form.jsp表单数据提交时到Servlet的链接写法。

3.3 步骤

步骤一:新建a1.jsp和a2.jsp文件

分别创建biz01/a1.jsp 和 biz02/a2.jsp 两个文件,工程结构如图-27

图 - 27

步骤二:为a1.jsp和a2.jsp添加跳转链接

a1.jsp文件中的链接写法如下:

图 - 28

a2.jsp文件中的链接写法如下:

图- 29

步骤三:添加SomeServlet

图 - 30

步骤四:添加form.jsp文件

图– 31

form.jsp文件内容

图 - 32

3.4 完整代码

a1.jsp文件代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body style="font-size:24px;">
	a1.jsp's content<br/>
	相对路径的写法:
	<a href="../biz02/a2.jsp">a2.jsp</a>
	绝对路径的写法:
	<a href="/day05/biz02/a2.jsp">a2.jsp</a>
	变量路径的写法:
	<a href="<%=request.getContextPath()%>/biz02/a2.jsp">a2.jsp</a>
</body>
</html>

a2.jsp文件代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body style="font-size:24px;">
	a2.jsp's content<br/>
	相对路径的写法:
	<a href="../biz01/a1.jsp">a1.jsp</a>
	绝对路径的写法:
	<a href="/day05/biz01/a1.jsp">a1.jsp</a>
	变量路径的写法:
	<a href="<%=request.getContextPath()%>/biz01/a1.jsp">a2.jsp</a>
</body>
</html>

SomeServlet.java文件代码

package path;

import java.io.IOException;
import java.io.PrintWriter;

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

public class SomeServlet extends HttpServlet {

	
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		PrintWriter out = response.getWriter();
		System.out.println("SomeServlet's service is running...");
		//重定向到biz01/a1.jsp
		request.getRequestDispatcher("/biz01/a1.jsp").forward(request, response);
	}

}

form.jsp文件代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<!-- <form action="../some" method="post"> -->
	<form action="<%=request.getContextPath()%>/some" method="post">
		<input type="text" name="name" /><br>
		<input type="submit" value="提交"/>
	</form>
</body>
</html>

4 员工管理——注册

4.1 问题

为员工管理系统添加注册和登陆功能,注册时需要进行用户名是否存在的判断,如果存在则出现提示。

4.2 方案

创建t_user表,编写User实体和UserDAO操作类。编写注册页面,提交到服务器以后,判断用户名是否存在,存在则绑定提示信息后转发回注册页面,页面输出绑定的提示信息,如果不存在则添加用户信息后重定向到登陆页面。登陆页面功能相同。

4.3 步骤

步骤一:创建t_user表

图 - 33

步骤二:创建entity.User类

图 - 34

步骤三:创建dao.UserDAO类

dao.DBUtil.java的内容同前面的练习一致

图- 35

步骤四:创建regist.jsp页面

将美工制作的注册页面内容复制到regist.jsp页面中

图- 36

步骤五:修改ActionServlet类

图– 37

修改regist.jsp页面,读取绑定的信息,非空则显示在文本框的后面。然后运行程序,查看效果

图– 38

图- 39

步骤六:创建login.jsp页面

图- 40

步骤七:修改ActionServlet页面

图– 41

修改login.jsp页面,读取绑定信息,非空则显示在文本框的后面

图- 42

运行查看结果。

4.4 完整代码

User.java文件代码:

package entity;

/**
 * 实体类:用于描述用户,与数据库中的t_user表中的字段一一对应
 */
public class User {
	private int id;
	private String userName;
	private String pwd;
	private String name;
	private String gender;

	@Override
	public String toString() {
		return id + "  " + userName + "  " +
				pwd + "  " + name + "  " + gender;
	}

	public int getId() {
		return id;
	}

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

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getName() {
		return name;
	}

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

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

}

UserDAO.java文件的代码

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import entity.User;
/**
 *  用户的数据操作类
 */
public class UserDAO {
	/**
	 * 根据用户名称查找用户对象
	 * @param userName 用户名称
	 * @return	用户实体
	 */
	public User findByUserName(String userName) throws Exception {

		User user = null;
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;

		try {
			con = DBUtil.getConnection();
			stmt = con.prepareStatement("select * from t_user where username=?");
			stmt.setString(1, userName);
			rs = stmt.executeQuery();
			if (rs.next()) {
				user = new User();
				user.setId(rs.getInt("id"));
				user.setUserName(rs.getString("username"));
				user.setName(rs.getString("name"));
				user.setPwd(rs.getString("pwd"));
				user.setGender(rs.getString("gender"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			DBUtil.close(con);
		}

		return user;
	}
	
	/**
	 * 保存实体信息到数据库
	 */
	public void save(User user) throws Exception {

		Connection con = null;
		PreparedStatement stmt = null;

		try {
			con = DBUtil.getConnection();
			stmt = con.prepareStatement("insert into t_user values(user_id_seq.nextval,?,?,?,?)");
			stmt.setString(1, user.getUserName());
			stmt.setString(2, user.getPwd());
			stmt.setString(3, user.getName());
			stmt.setString(4, user.getGender());
			stmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			DBUtil.close(con);
		}
	}
}

ActionServlet.java文件代码

package web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import dao.EmployeeDAO;
import dao.UserDAO;
import entity.Employee;
import entity.User;

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("/") + 1,
				uri.lastIndexOf("."));

		// 创建员工管理操作类
		EmployeeDAO dao = new EmployeeDAO();

		// 判断请求动作种类,分不同种类情况处理
		if (action.equals("list")) {// 员工信息列表
			try {
				List<Employee> emps = dao.findAll();
				request.setAttribute("emps", emps);
				request.getRequestDispatcher("listEmp.jsp").forward(request,
						response);
			} catch (Exception e) {
				e.printStackTrace();
				// 编程式的处理异常
				request.setAttribute("err_msg", "系统出错,请重试");
				request.getRequestDispatcher("error.jsp").forward(request,
						response);
			}
		} else if (action.equals("add")) {// 增加员工
			String name = request.getParameter("name");
			try {
				double salary = Double.parseDouble(request
						.getParameter("salary"));
				int age = Integer.parseInt(request.getParameter("age"));
				Employee emp = new Employee();
				emp.setName(name);
				emp.setSalary(salary);
				emp.setAge(age);

				dao.save(emp);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
				// 将异常抛给容器,在web.xml中添加声明,变成声明式的处理异常
				throw new ServletException(e);
			}
		} else if (action.equals("delete")) {// 删除员工
			int id = Integer.parseInt(request.getParameter("id"));
			try {
				dao.delete(id);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (action.equals("load")) {// 加载某个员工
			int id = Integer.parseInt(request.getParameter("id"));
			try {
				Employee emp = dao.findById(id);
				request.setAttribute("emp", emp);
				request.getRequestDispatcher("updateEmp.jsp").forward(request,
						response);
			} catch (Exception e) {
				e.printStackTrace();
			}

		} else if (action.equals("update")) {// 更新员工
			int id = Integer.parseInt(request.getParameter("id"));
			String name = request.getParameter("name");
			double salary = Double.parseDouble(request.getParameter("salary"));
			int age = Integer.parseInt(request.getParameter("age"));
			Employee emp = new Employee();
			emp.setName(name);
			emp.setSalary(salary);
			emp.setAge(age);
			emp.setId(id);
			try {
				dao.modify(emp);
				response.sendRedirect("list.do");
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if (action.equals("regist")) {//注册
			UserDAO userDAO = new UserDAO();
			String userName = request.getParameter("username");
			String name = request.getParameter("name");
			String pwd = request.getParameter("pwd");
			String gender = request.getParameter("sex");
			try {
				User u = userDAO.findByUserName(userName);
				if (u != null) {
					request.setAttribute("regis_err", "用户名已经存在");
					request.getRequestDispatcher("regist.jsp").forward(
							request, response);
				} else {
					u = new User();
					u.setUserName(userName);
					u.setName(name);
					u.setPwd(pwd);
					u.setGender(gender);
					userDAO.save(u);
					response.sendRedirect("login.jsp");
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServletException(e);
			}
		} else if (action.equals("login")) {//登陆

			String userName = request.getParameter("name");
			String pwd = request.getParameter("pwd");
			UserDAO userDAO = new UserDAO();
			try {
				User u = userDAO.findByUserName(userName);
				if (u == null || !u.getPwd().equals(pwd)) {
					request.setAttribute("login_err", "用户名或密码错误");
					request.getRequestDispatcher("login.jsp").forward(
							request, response);
				} else {
					response.sendRedirect("list.do");
				}
			} catch (Exception e) {
				e.printStackTrace();
				throw new ServletException(e);
			}

		}
	}
}

regist.jsp文件代码

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

<html>
	<head>
		<title>注册</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<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>
								2009/11/20
								<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>
					<form action="regist.do" method="post">
						<table cellpadding="0" cellspacing="0" border="0"
							class="form_table">
							<tr>
								<td valign="middle" align="right">
									用户名:
								</td>
								<td valign="middle" align="left">
									<input type="text" class="inputgri" name="username" />
									<%
										String errorMsg = (String)request.getAttribute("regis_err");
									%><span style="color:red;"><%=errorMsg==null?"":errorMsg%></span>
								</td>
							</tr>
							<tr>
								<td valign="middle" align="right">
									真实姓名:
								</td>
								<td valign="middle" align="left">
									<input type="text" class="inputgri" name="name" />
								</td>
							</tr>
							<tr>
								<td valign="middle" align="right">
									密码:
								</td>
								<td valign="middle" align="left">
									<input type="password" class="inputgri" name="pwd" />
								</td>
							</tr>
							<tr>
								<td valign="middle" align="right">
									性别:
								</td>
								<td valign="middle" align="left">
									男
									<input type="radio" class="inputgri" name="sex" value="m" checked="checked"/>
									女
									<input type="radio" class="inputgri" name="sex" value="f"/>
								</td>
							</tr>
							
							<tr>
								<td valign="middle" align="right">
									验证码:
									<img id="num" src="image" />
									<a href="javascript:;" onclick="document.getElementById('num').src = 'image?'+(new Date()).getTime()">换一张</a>
								</td>
								<td valign="middle" align="left">
									<input type="text" class="inputgri" name="number" />
								</td>
							</tr>
						</table>
						<p>
							<input type="submit" class="button" value="Submit &raquo;" />
						</p>
					</form>
				</div>
			</div>
			<div id="footer">
				<div id="footer_bg">
				ABC@126.com
				</div>
			</div>
		</div>
	</body>
</html>

login.jsp文件代码

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

<html>
<head>
<title>login</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<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>
						2009/11/20 <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>login</h1>
				<form action="login.do" method="post">
					<table cellpadding="0" cellspacing="0" border="0"
						class="form_table">
						<tr>
							<td valign="middle" align="right">用户名:</td>
							<td valign="middle" align="left">
							<input type="text"	class="inputgri" name="name" />
								<%
								String errorMsg = (String)request.getAttribute("login_err");
								%><span style="color:red;"><%=errorMsg==null?"":errorMsg%></span>
							</td>
						</tr>
						<tr>
							<td valign="middle" align="right">密码:</td>
							<td valign="middle" align="left"><input type="password"
								class="inputgri" name="pwd" />
							</td>
						</tr>
					</table>
					<p>
						<input type="submit" class="button" value="Submit &raquo;" />
					</p>
				</form>
			</div>
		</div>
		<div id="footer">
			<div id="footer_bg">ABC@126.com</div>
		</div>
	</div>
</body>
</html>