在使用Servlet进行Java Web的开发时, 如果每个业务都去重新写一个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">
<!-- 提交时默认带上, 区分具体做什么操作 -->
<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 {
// 采用反射调用, 执行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;
}
// 在此处转发或重定向
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("操作有误,只能转发或者重定向,或者什么也不做");
}
}
}
这里注释已经写的很清楚了, 所以可以直接新建一个自己的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("删除用户!!!!!");
}
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("修改用户!!!");
}
public void findCustomer(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("查询用户!!");
}
}
DBUtils的使用
QueryRunner
构造方法
QueryRunner();
使用该构造方法创建对象在执行update操作和query操作时需要带Connection对象
qr.update(Connection conn, String sql , Object[] objs);
QueryRunner(DataSource ds);
该构造方法创建的对象在执行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) // 执行增 删 改
数据操作语言 -- 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
网友评论