使用servlet的时候如果每个方法都创建一个servlet的话,会使系统非常的庞大,会在web.xml中创建很多的映射,为了简化操作,我们通过反射来根据调用的方法名动态的去执行指定的方法.

创建基类BaseServlet让其继承HttpServlet

public class BaseServlet extends HttpServlet {

@SuppressWarnings({ "unchecked", "null" })
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取继承自该url传递过来的method参数
String methodName = request.getParameter("method");

if (methodName != null || "".equals(methodName.trim())) {
try {
//组装参数类型,所有的方法参数都是request和response
Class[] parameterTypes = { HttpServletRequest.class, HttpServletResponse.class };
//通过反射获取在该类中的方法(指定方法名和方法参数)
Method method = this.getClass().getMethod(methodName,parameterTypes);
//执行通过反射获取到的方法
method.invoke(this, request,response);
} catch (Exception e) {
throw new RuntimeException(e);
}
} else {
throw new RuntimeException("请不要恶意攻击");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

创建的操作类继承BaseServlet


public class EmployeeServlet extends BaseServlet {
/**
* 添加员工
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void add(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String username = request.getParameter("username");
String spsw = request.getParameter("psw");
String psw = "";
if (spsw != null && !"".equals(spsw)) {
psw = MD5Utils.md5encrypt(spsw);
}
String realname = request.getParameter("realname");
String sex = request.getParameter("sex");
String sbirthday = request.getParameter("birthday");
String edu = request.getParameter("edu");
String major = request.getParameter("major");
String des = request.getParameter("des");
String shiredate = request.getParameter("hiredate");
String role = request.getParameter("role");

Employees emp = new Employees();
emp.setUsername(username);
emp.setPsw(psw);
emp.setRealname(realname);
emp.setSex(sex);

Date birthday = null;
if (sbirthday != null && "" != sbirthday.trim()) {
birthday = java.sql.Date.valueOf(sbirthday.trim());
}
emp.setBirthday(birthday);

emp.setEdu(edu);
emp.setMajor(major);
emp.setDes(des);
Date hiredate = null;
if (shiredate != null && "" != shiredate.trim()) {
hiredate = java.sql.Date.valueOf(shiredate);
}
emp.setHiredate(hiredate);
emp.setRole(role);

EmployeeImpl empimpl = new EmployeeImpl();
empimpl.addEmp(emp);

request.getRequestDispatcher("/employeeServlet?method=findAll")
.forward(request, response);

}

/**
* 列表显示
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void findAll(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

EmployeeImpl empimpl = new EmployeeImpl();
List<Employees> lists = empimpl.findAll();

request.setAttribute("lists", lists);
request.getRequestDispatcher("/employees/list.jsp").forward(request,
response);

}

/**
* 跳转到编辑页面
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void findOne(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
EmployeeImpl empimpl = new EmployeeImpl();
Employees emp = new Employees();
String id = request.getParameter("id");

if (id != null && !"".equals(id)) {
emp = empimpl.findOne(id);
}
request.setAttribute("emp", emp);
request.getRequestDispatcher("/employees/edit.jsp").forward(request,
response);
}

/**
* 查看
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void look(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
EmployeeImpl empimpl = new EmployeeImpl();
Employees emp = new Employees();
String id = request.getParameter("id");

if (id != null && !"".equals(id)) {
emp = empimpl.findOne(id);
}
request.setAttribute("emp", emp);
request.getRequestDispatcher("/employees/oneList.jsp").forward(request,
response);

}

/**
* 更新
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void update(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String id = request.getParameter("id");
String username = request.getParameter("username");
String spsw = request.getParameter("psw");
String psw = "";
if (spsw != null && !"".equals(spsw)) {
psw = MD5Utils.md5encrypt(spsw);
}
String realname = request.getParameter("realname");
String sex = request.getParameter("sex");
String sbirthday = request.getParameter("birthday");
String edu = request.getParameter("edu");
String major = request.getParameter("major");
String des = request.getParameter("des");
String shiredate = request.getParameter("hiredate");
String role = request.getParameter("role");

Employees emp = new Employees();
emp.setId(Integer.parseInt(id));
emp.setUsername(username);
emp.setPsw(psw);
emp.setRealname(realname);
emp.setSex(sex);

Date birthday = null;
if (sbirthday != null && "" != sbirthday.trim()) {
birthday = java.sql.Date.valueOf(sbirthday.trim());
}
emp.setBirthday(birthday);

emp.setEdu(edu);
emp.setMajor(major);
emp.setDes(des);
Date hiredate = null;
if (shiredate != null && "" != shiredate.trim()) {
hiredate = java.sql.Date.valueOf(shiredate);
}
emp.setHiredate(hiredate);
emp.setRole(role);

EmployeeImpl empimpl = new EmployeeImpl();
empimpl.update(emp);

request.getRequestDispatcher("/employeeServlet?method=findAll")
.forward(request, response);

}

/**
* 删除
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void delete(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String id = request.getParameter("id");
EmployeeImpl empimpl = new EmployeeImpl();
empimpl.delele(id);

request.getRequestDispatcher("/employeeServlet?method=findAll")
.forward(request, response);
}
/**
*
* @author ducc

* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void toSearch(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/employees/listCondition.jsp").forward(
request, response);
}
/**
* 条件查询
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
public void search(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String username = request.getParameter("username");
String realname = request.getParameter("realname");
String sex = request.getParameter("sex");
String beginhiredate = request.getParameter("beginhiredate");
String endhiredate = request.getParameter("endhiredate");
String edu = request.getParameter("edu");

Employees emp = new Employees();
emp.setUsername(username.trim());
emp.setRealname(realname.trim());
emp.setSex(sex);
if (beginhiredate != null) {
emp.setBirthday(Date.valueOf(beginhiredate.trim()));
}
if (endhiredate != null) {
emp.setHiredate(Date.valueOf(endhiredate.trim()));
}
emp.setEdu(edu);

EmployeeImpl empimpl = new EmployeeImpl();
List<Employees> lists = empimpl.search(emp);

request.setAttribute("lists", lists);
request.getRequestDispatcher("/employees/listCondition.jsp").forward(
request, response);

}

}

dao层实现

public class EmployeeImpl {
/**
* 添加员工
*/
public void addEmp(Employees emp) {
Connection conn = null;
PreparedStatement pstmt = null;

try {
conn = JDBCUtils.getConn();
String sql = "INSERT INTO employees(username, psw, realname, sex, birthday, edu, major, des,"
+ " hiredate, role) values(?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(sql);

pstmt.setString(1, emp.getUsername());
pstmt.setString(2, emp.getPsw());
pstmt.setString(3, emp.getRealname());
pstmt.setString(4, emp.getSex());
pstmt.setDate(5, emp.getBirthday());
pstmt.setString(6, emp.getEdu());
pstmt.setString(7, emp.getMajor());
pstmt.setString(8, emp.getDes());
pstmt.setDate(9, emp.getHiredate());
pstmt.setString(10, emp.getRole());
pstmt.executeUpdate();
System.out.println(emp.getPsw().length());

} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.close(conn, pstmt, null);
}

}

/**
* 获取所有员工
*/
public List<Employees> findAll() {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Employees> lists =null;

try {
conn = JDBCUtils.getConn();
String sql = "select id, username, psw, realname, sex, birthday, edu, major, des, hiredate, role from employees";
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
Employees emp=null;
if (rs != null) {
lists= new ArrayList<Employees>();
while (rs.next()) {
emp= new Employees();
emp.setId(rs.getInt("id"));
emp.setUsername(rs.getString("username"));
emp.setPsw(rs.getString("psw"));
emp.setRealname(rs.getString("realname"));
emp.setSex(rs.getString("sex"));
emp.setBirthday(rs.getDate("birthday"));
emp.setEdu(rs.getString("edu"));
emp.setMajor(rs.getString("major"));
emp.setDes(rs.getString("des"));
emp.setHiredate(rs.getDate("hiredate"));
emp.setRole(rs.getString("role"));

lists.add(emp);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.close(conn, pstmt, null);
}
return lists;
}
/**
* 根据id获取员工
*/
public Employees findOne(String id) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Employees emp = null;
try {
conn = JDBCUtils.getConn();
String sql = "select id, username, psw, realname, sex, birthday, edu, major, des, hiredate, role from employees where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, Integer.parseInt(id));
rs = pstmt.executeQuery();
if (rs != null) {
while (rs.next()) {
emp = new Employees();
emp.setId(rs.getInt("id"));
emp.setUsername(rs.getString("username"));
emp.setPsw(rs.getString("psw"));
emp.setRealname(rs.getString("realname"));
emp.setSex(rs.getString("sex"));
emp.setBirthday(rs.getDate("birthday"));
emp.setEdu(rs.getString("edu"));
emp.setMajor(rs.getString("major"));
emp.setDes(rs.getString("des"));
emp.setHiredate(rs.getDate("hiredate"));
emp.setRole(rs.getString("role"));
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.close(conn, pstmt, null);
}
return emp;
}
/**
* 更新员工
*/
public void update(Employees emp) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = JDBCUtils.getConn();
if (emp.getPsw() != "") {
String sql = "UPDATE employees set username = ?, psw = ? , realname = ? , sex = ? , birthday =?, "
+ "edu =? , major = ? , des =? , hiredate = ? , role =? where id = ?;";

pstmt = conn.prepareStatement(sql);
pstmt.setString(1, emp.getUsername());
pstmt.setString(2, emp.getPsw());
pstmt.setString(3, emp.getRealname());
pstmt.setString(4, emp.getSex());
pstmt.setDate(5, emp.getBirthday());
pstmt.setString(6, emp.getEdu());
pstmt.setString(7, emp.getMajor());
pstmt.setString(8, emp.getDes());
pstmt.setDate(9, emp.getHiredate());
pstmt.setString(10, emp.getRole());
pstmt.setInt(11, emp.getId());

pstmt.executeUpdate();
} else {
String sql = "UPDATE employees set username = ? , realname = ? , sex = ? , birthday =?, "
+ "edu =? , major = ? , des =? , hiredate = ? , role =? where id = ?;";

pstmt = conn.prepareStatement(sql);
pstmt.setString(1, emp.getUsername());
pstmt.setString(2, emp.getRealname());
pstmt.setString(3, emp.getSex());
pstmt.setDate(4, emp.getBirthday());
pstmt.setString(5, emp.getEdu());
pstmt.setString(6, emp.getMajor());
pstmt.setString(7, emp.getDes());
pstmt.setDate(8, emp.getHiredate());
pstmt.setString(9, emp.getRole());
pstmt.setInt(10, emp.getId());

pstmt.executeUpdate();
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.close(conn, pstmt, null);
}

}
/**
* 删除
*/
public void delele(String id) {

Connection conn = null;
PreparedStatement pstmt = null;
if (id != null && !"".equals(id.trim())) {

try {
conn = JDBCUtils.getConn();
String sql = "delete from employees where id=?";
pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, Integer.parseInt(id));
pstmt.executeUpdate();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.close(conn, pstmt, null);
}
}
}
/**
* 条件查询
*/
public List<Employees> search(Employees emp) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

List<Employees> lists = new ArrayList<Employees>();

try {
conn = JDBCUtils.getConn();
stmt = conn.createStatement();
String sql = "select * from employees where 1=1";
StringBuffer strWhere = new StringBuffer();
if (emp.getUsername() != null && !"".equals(emp.getUsername())) {
strWhere.append(" and username='").append(emp.getUsername()).append("'");
}
if (emp.getRealname() != null && !"".equals(emp.getRealname())) {
strWhere.append(" and realname='").append(emp.getRealname()).append("'");
}
if (emp.getSex() != null && !"".equals(emp.getSex())) {
strWhere.append(" and sex='").append(emp.getSex()).append("'");
}
if (emp.getBirthday() != null) {
strWhere.append(" and birthday='").append(emp.getBirthday()).append("'");
}
if (emp.getHiredate() != null) {
strWhere.append(" and hiredate='").append(emp.getHiredate()).append("'");
}
if (emp.getEdu() != null && !"".equals(emp.getEdu())) {
strWhere.append(" and edu='").append(emp.getEdu()).append("'");
}
sql += strWhere.toString();
rs = stmt.executeQuery(sql);
Employees emp1=null;
if (rs != null) {
while (rs.next()) {
emp1 = new Employees();
emp1.setId(rs.getInt("id"));
emp1.setUsername(rs.getString("username"));
emp1.setPsw(rs.getString("psw"));
emp1.setRealname(rs.getString("realname"));
emp1.setSex(rs.getString("sex"));
emp1.setBirthday(rs.getDate("birthday"));
emp1.setEdu(rs.getString("edu"));
emp1.setMajor(rs.getString("major"));
emp1.setDes(rs.getString("des"));
emp1.setHiredate(rs.getDate("hiredate"));
emp1.setRole(rs.getString("role"));
lists.add(emp1);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
JDBCUtils.close(conn, stmt, rs);
}
return lists;

}

}

工具类JDBCUtils.java

public class JDBCUtils {
private static Properties dbConfig = new Properties();
private static String driverClass = null;
private static String url = null;
private static String user = null;
private static String password = null;

static {
try {
InputStream in = JDBCUtils.class.getClassLoader()
.getResourceAsStream("db.properties");
dbConfig.load(in);
driverClass = dbConfig.getProperty("driverClass");
url = dbConfig.getProperty("url");
user = dbConfig.getProperty("user");
password = dbConfig.getProperty("password");
} catch (Exception e) {
throw new RuntimeException("找不到配置文件");
}

}

/**
* 获取数据库连接对象
*
* @return
*/
public static Connection getConn() {

Connection conn = null;
try {
Class.forName(driverClass);
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
throw new RuntimeException(e);

}
if (conn == null) {
throw new RuntimeException("获取连接失败");
}
return conn;

}

/**
* 释放连接数据库占用的资源
*
* @param conn
* @param stmt
* @param rs
*/
public static void close(Connection conn, Statement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
rs = null;
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
stmt = null;
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
conn = null;
e.printStackTrace();
}
}
}
}
}
}
}

}