在使用Servlet進行Java Web的開發(fā)時, 如果每個業(yè)務都去重新寫一個Servlet來處理, 那么重復的代碼就很多!
這里, 我們引入BaseServlet的概念, 讓每個新寫的Servlet去繼承這個BaseServlet, 把公用的操作方法都寫到這個類里.
BaseServlet的用法
我們新建一個JSP頁面 addCustomer.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>增加</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/CustomerServlet" method="post">
<!-- 提交時默認帶上, 區(qū)分具體做什么操作 -->
<input type="hidden" name="method" value="addCustomer">
<input type="submit" value="添加">
</form>
</body>
</html>
然后新建一個Servlet: BaseServlet.java
注意, 這里不需要在web.xml中配置, 因為已經通過注解的方式配置了Servlet.
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 java.io.IOException;
import java.lang.reflect.Method;
/**
* Created by menglanyingfei on 2018/1/14.
*/
@WebServlet(name = "BaseServlet")
public class BaseServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 獲取請求方法, 在請求參數中, 附帶一個額外的參數, 該參數是一個方法名
String methodName = req.getParameter("method");
/*
如果不通過反射來操作, 增加一個邏輯, 就需要修改代碼!
if ("addCustomer".equals(methodName)) {
addCustomer(req, resp);
} else if ("editCustomer".equals(methodName)) {
editCustomer(req, resp);
} else if ("findCustomer".equals(methodName)) {
findCustomer(req, resp);
} else if ("deleteCustomer".equals(methodName)) {
deleteCustomer(req, resp);
}
*/
// 通過反射來實現(推薦)
/*
1. 獲取方法名
2. 獲取當前類Class對象 this.getClass();
3. 獲取與該方法名對應的Method對象 getMethod(String name, Class<?>... parameterTypes)
方法名 方法的參數類型
4. 通過Method對象來調用invoke(this, req, resp), 就相當于調用了methodName()
假設獲取的methodName為addCustomer
*/
Class cl = this.getClass();
Method method = null;
try {
method = cl.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
} catch (Exception e) {
throw new RuntimeException("不能獲取" + methodName + "Method對象");
}
String path = null;
try {
// 采用反射調用, 執(zhí)行this.methodName(req, resp)的返回值
path = (String) method.invoke(this, req, resp);
} catch (Exception e) {
throw new RuntimeException("調用" + methodName + "出錯!");
}
if (path == null) {
System.out.println("什么也不做!!!");
return;
}
// 在此處轉發(fā)或重定向
String[] arr = path.split(":");
if ("redirect".equals(arr[0])) {
resp.sendRedirect(req.getContextPath() + arr[1]);
} else if ("forward".equals(arr[0])) {
req.getRequestDispatcher(arr[1]).forward(req, resp);
} else {
throw new RuntimeException("操作有誤,只能轉發(fā)或者重定向枉昏,或者什么也不做");
}
}
}
這里注釋已經寫的很清楚了, 所以可以直接新建一個自己的Servlet去繼承這個BaseServlet了.(CustomerServlet.java)
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by menglanyingfei on 2018/1/14.
*/
@WebServlet(name = "CustomerServlet", value = "/CustomerServlet")
public class CustomerServlet extends BaseServlet {
public void deleteCustomer(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("刪除用戶P至选Q粼濉!P饶唷!");
}
public String addCustomer(HttpServletRequest req, HttpServletResponse resp) throws Exception {
// resp.sendRedirect(req.getContextPath() + "/index.jsp");
// req.getRequestDispatcher("/index.jsp").forward(req, resp);
System.out.println("添加用戶");
// 在這里返回一個路徑
// return "redirect:/index.jsp";
return "forward:/index.jsp";
// return null;
}
public void editCustomer(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("修改用戶G恪!裆悄!");
}
public void findCustomer(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("查詢用戶1哿!");
}
}
DBUtils的使用
QueryRunner
構造方法
QueryRunner();
使用該構造方法創(chuàng)建對象在執(zhí)行update操作和query操作時需要帶Connection對象
qr.update(Connection conn, String sql , Object[] objs);
QueryRunner(DataSource ds);
該構造方法創(chuàng)建的對象在執(zhí)行update操作和query操作時不需要帶Connection對象
qr.update(String sql, Object[] objs);
為了方便, 我們就使用第二種構造方法:
private QueryRunner qr = new QueryRunner(JDBCUtils.getDateSource());
JDBCUtils.java:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class JDBCUtils {
private static ComboPooledDataSource ds = new ComboPooledDataSource();
// 獲取數據源
public static DataSource getDateSource() {
return ds;
}
public static Connection getConnection() {
try {
Connection conn = ds.getConnection();
return conn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void close(Connection conn, Statement stmt, ResultSet rs) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
兩個核心方法
update(String sql ,Object[] objs) // 執(zhí)行增 刪 改
數據操作語言 -- DML, 我們就舉一例:
@Test
public void test() throws Exception {
// 使用UUID生成一個客戶的id
for (int i = 0; i < 50; i++) {
UUID uuid = UUID.randomUUID();
String cid = uuid.toString();
cid = cid.replace("-", "");
String sql = "insert into `customer` values(?,?,?,?,?,?,?)";
Customer c = new Customer(cid, "小陽", "男", new Date(), "111", "111", "777");
Object[] obj = {c.getCid(), c.getCname(), c.getGender(), DateUtil.dateToStr(c.getBirthday()),
c.getCellPhone(), c.getEmail(), c.getDescription()};
qr.update(sql, obj);
}
}
query(String sql, ResultSetHandler handler, Object[] objs) // 查詢操作
ResultSetHandler:這個接口是對查詢結果集進行處理,返回我們想要的數據類型.
實現類:
[BeanHandler]:將查詢結果集 直接轉換成javabean對象 結果只有一行
[BeanListHandler]:對應多行結果集腻贰,將結果集轉換成多個javabean對象保存到list集合中
[MapHandler]:對應一行扒秸,將字段名作為key冀瓦,將字段作為value 將一行結果封裝一個map對象
[MapListHandler]:將字段名作為key,將字段作為value 將多行結果封裝多個map對象翼闽,將Map保存到List中
[ScalarHandler]:對應一個值的情況感局,一般用于聚合函數的查詢
示例代碼:
String sql = "select * from customer where cid = ?";
Object[] obj = {cid};
Customer c = qr.query(sql, new BeanHandler<Customer>(Customer.class), obj);
// =================
String sql = "select * from customer limit ?, ?";
Object[] obj = {(pageBean.getCp() - 1) * pageBean.getPr(), pageBean.getPr()};
List<Customer> list = qr.query(sql, new BeanListHandler<Customer>(Customer.class), obj);
// =================
String sql = "select * from customer where cid = ?";
Object[] obj = {"05cf0a8291794060af41b971954f7d06"};
Map<String, Object> map = qr.query(sql, new MapHandler(), obj);
System.out.println(map);
// =================
String sql = "select * from customer";
List<Map<String,Object>> list = qr.query(sql, new MapListHandler());
System.out.println(list);
// =================
// 查詢總記錄數
sql = "select count(*) from customer";
Number n = (Number) qr.query(sql, new ScalarHandler());
Integer tr = n.intValue();
完整代碼地址
BaseServlet:
https://github.com/menglanyingfei/Java/tree/master/JavaWebTrain/day_1_14
DBUtils:
https://github.com/menglanyingfei/Java/tree/master/JavaWebTrain/day_1_15/customer