我是最棒的!基础不牢,地动山摇!
步骤
前面的步骤1参考我前面的CRUD博客,主要是步骤2,步骤3和步骤4的增强。
抽取相同部分,成为一个模板方法,抽取增删改的模板相对简单。抽取查询的模板需要处理结果集,因为Domain是不定的,所以我们写一个专门处理结果集的接口ResultSetHandler,他需要一个结果集对象作为参数,然后返回一个list给查询方法作为返回值。处理User就写一个类去实现这个接口,重写方法。在模板方法中,传入这个相应的实现类处理结果集就OK了。最终实现如下
package cn.itsource.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import cn.itsource.domain.User;
public class JdbcTemplate {
/**
* 模板方法抽取dao,增删改
* @param sql
* @param objs
*/
public static void executeUpdate(String sql,Object...objs){
Connection conn= null;
PreparedStatement ps = null;
try {
//获取连接对象
conn = JDBCUtil.getConnection();
//获取预编译对象
ps = conn.prepareStatement(sql);
//设置属性
for (int i = 0; i < objs.length; i++) {
ps.setObject(i+1, objs[i]);
}
//执行
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.close(null, ps, conn);
}
}
/**
* 抽取模板方法查询全部
* @param sql
* @param objs
* @return
*/
public static <T> List<T> executeQuery(String sql,IResultSetHandler<T> handler,Object...objects){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtil.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < objects.length; i++) {
ps.setObject(i+1, objects[i]);
}
rs = ps.executeQuery();
//针对结果集进行处理
List<T> list = handler.handler(rs);
return list;
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.close(rs, ps, conn);
}
return null;
}
/**
* 抽取模板方法查询单个
* @param sql
* @param objs
* @return
*/
public static <T> T executeQueryOne(String sql,IResultSetHandler<T> handler,Object...objects){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtil.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < objects.length; i++) {
ps.setObject(i+1, objects[i]);
}
rs = ps.executeQuery();
//针对结果集进行处理
List<T> list = handler.handler(rs);
return list.get(0);
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.close(rs, ps, conn);
}
return null;
}
}
ResultHandler接口及其实现类
package cn.itsource.util;
import java.sql.ResultSet;
import java.util.List;
public interface IResultSetHandler <T>{
List<T> handler(ResultSet rs);
}
实现类
package cn.itsource.util;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import cn.itsource.domain.User;
/**
* 专门处理User的结果集
*/
public class UserResultHandler implements IResultSetHandler<User>{
@Override
public List<User> handler(ResultSet rs) {
List<User> users = new ArrayList<User>();
try {
while (rs.next()) {
User user = new User();
user.setId(rs.getLong("id"));
user.setName(rs.getString("name"));
user.setAge(rs.getInt("age"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
}
UserDaoImpl实现
package cn.itsource.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import cn.itsource.dao.IUserDao;
import cn.itsource.domain.User;
import cn.itsource.util.JDBCUtil;
import cn.itsource.util.JdbcTemplate;
import cn.itsource.util.UserResultHandler;
public class UserDaoImpl implements IUserDao{
/**新增用户方法*/
@Override
public void save(User user) {
JdbcTemplate.executeUpdate("insert into t_user (name,age) values (?,?)"
, user.getName(),user.getAge());
}
/**根据id删除用户*/
@Override
public void removeById(Long id) {
JdbcTemplate.executeUpdate("delete from t_user where id = ?", id);
}
/**修改用户信息*/
@Override
public void update(User user) {
JdbcTemplate.executeUpdate("update t_user set name = ? , age = ? where id = ?"
, user.getName(), user.getAge(), user.getId());
}
/**根据id查询用户*/
@Override
public User queryById(Long id) {
User user = JdbcTemplate.executeQueryOne("select * from t_user where id = ?", new UserResultHandler(),id);
return user;
}
/**查询所有用户信息*/
@Override
public List<User> queryAll() {
List<User> users = JdbcTemplate.executeQuery("select * from t_user", new UserResultHandler());
return users;
}
}
加强的Servlet全部放在一个Servlet里面,UserServlet如下。其实就是将所有的Servlet写在一起而已,没有什么太大的区别。
package cn.itsource.controller;
import java.io.IOException;
import java.util.List;
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 cn.itsource.dao.IUserDao;
import cn.itsource.dao.impl.UserDaoImpl;
import cn.itsource.domain.User;
@WebServlet(value="/user",loadOnStartup = 1)
public class UserServlet extends HttpServlet{
private IUserDao dao;
@Override
public void init() throws ServletException {
dao = new UserDaoImpl();
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置编码
req.setCharacterEncoding("UTF-8");
//通过cmd来统一所有业务处理在一个里面
String cmd = req.getParameter("cmd");
if("delete".equals(cmd)){
delete(req,resp);
}else if ("input".equals(cmd)) {
input(req,resp);
}else if("update".equals(cmd)){
update(req,resp);
}else {
show(req,resp);
}
}
/**
* 展示界面
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
private void show(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<User> users = dao.queryAll();
req.setAttribute("users", users);
req.getRequestDispatcher("/WEB-INF/jsp/show.jsp").forward(req, resp);
}
/**
* 修改和新增
* @param req
* @param resp
* @throws IOException
*/
private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String id = req.getParameter("id");
String name = req.getParameter("name");
String age = req.getParameter("age");
if(id != null && "".equals(id) == false){
User user = new User();
user.setId(Long.valueOf(id));
user.setName(name);
user.setAge(Integer.valueOf(age));
// System.out.println(user);
dao.update(user);
}else {
User user = new User();
user.setName(name);
user.setAge(Integer.valueOf(age));
dao.save(user);
}
resp.sendRedirect("/show");
}
/**
* 识别修改和新增
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
private void input(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
if(id != null && "".equals(id) == false){
User user = dao.queryById(Long.valueOf(id));
req.setAttribute("user", user);
}
req.getRequestDispatcher("/WEB-INF/jsp/input.jsp").forward(req, resp);
}
/**
* 删除
* @param req
* @param resp
* @throws IOException
*/
private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String id = req.getParameter("id");
dao.removeById(Long.valueOf(id));
resp.sendRedirect("/show");
}
}
UserServlet根据传入的cmd来完成对应的操作
主界面show.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 http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
table{
width:50%;
border:1px solid deepskyblue;
border-collapse:collapse;
text-align: center;
}
table th,table td{
border:1px solid deepskyblue;
}
</style>
</head>
<body>
<table>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>操作</th>
</tr>
<c:forEach items="${users}" var="u" varStatus="s">
<tr style="background: ${s.index%2==0 ? 'pink' : 'grey'}">
<td>${u.id}</td>
<td>${u.name}</td>
<td>${u.age}</td>
<td>
<a href="/user?cmd=input&id=${u.id}">修改</a>
<a href="/user?cmd=delete&id=${u.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<a href="/input" >新增</a>
</body>
</html>
增加和修改界面input.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://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="/user?cmd=update" method="post">
<input type="hidden" name="id" value=${user.id}>
姓名<input type="text" name="name" value=${user.name}><br/>
年龄<input type="text" name="age" value=${user.age}><br/>
<input type="submit" value="提交">
</form>
</body>
</html>
抽取总是美妙的,重复的代码在编程中实在是不太优雅。