Servlet优化1 实现将各种请求由一个组件进行统一调度后响应
-
优化逻辑图
-
servlet组件
// 所有的html内post请求的action值和get请求中的href值,全部变更为customers.do @WebServlet("/customers.do") public class CustomersServlet extends ViewBaseServlet { // 属性 private ListIpm listIpm = new ListIpm(); // service方法,将所有的get/post请求统一拦截,然后调配至相应do方法 @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); // 将各html文件与js文件中请求标记的值赋给operate变量 String operate = req.getParameter("operate"); if (StringUtil.isEmpty(operate)) { operate = "index"; } // 使用反射,获取该对象对应的运行时类内的所有方法,使方法名与operate代表请求信息一一对应 Method[] methods = this.getClass().getDeclaredMethods(); for (Method m : methods) { String methodName = m.getName(); if (operate.equals(methodName)) { try { m.invoke(this, req, resp); break; } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } throw new RuntimeException("operate值非法"); } } // 下面的index、delete、edit、update、add方法,是各请求的具体实现方法 protected void index(HttpServletRequest req, HttpServletResponse resp) { Connection conn = null; try { // 1.连接数据库,实例化DAO中的实现类,得到session conn = JdbcUtils.getConnection(); ListIpm ipm = new ListIpm(); HttpSession session = req.getSession(); // 2.分页功能 // 2.1 给pageOn赋初始值,用于在js无返回页面值时,html可以明确显示哪个分页 int pageOn = 1; // 3.确认是否为查询按钮提交的数据 // 3.1 获取表单中隐藏域的关键字 String oper = req.getParameter("oper"); String key = null; // 3.2 判断获取的oper中的值,从而确定查询按钮被触发,显示的就是查询后的结果,页面调整到从首页显示 if (StringUtil.isNotEmpty(oper) && "search".equals(oper)) { pageOn = 1; // key是查询得到的关键字 key = req.getParameter("keyword"); if (StringUtil.isEmpty(key)) { key = ""; } // 如果查询输入栏中有值,那么就将这个值保存在作用域中,可以被组件或html调用 session.setAttribute("k",key); }else { // 2.3获取js文件中的page,如果html页面的控制页面按钮被触动,就将页面值赋给pageOn String pageStr = req.getParameter("page"); if (StringUtil.isNotEmpty(pageStr)) { pageOn = Integer.parseInt(pageStr); } // 如果是其它按钮被触发,那么key要从保存作用域中读值,这时可能时查询之后的翻页,key值还应该时查询时输入的值。 Object keyObj = session.getAttribute("k"); if (keyObj == null) { key = ""; }else { key = (String) keyObj; } } // 2.2 将pageOn保存到作用域中 session.setAttribute("pageOn",pageOn); List<Customers> custList = ipm.getList(conn,"%"+ key +"%",pageOn); session.setAttribute("cl",custList); // 4 获取客户个数,用于优化html中分页按钮功能 long count = 0L; count = ipm.getCount(conn,"%"+key+"%"); int max = (int) (count+2-1)/2; session.setAttribute("max",max); // 5.调用父类的模板处理方法 super.processTemplate("index",req,resp); } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtils.closeResource(conn,null); } } private void add(HttpServletRequest req, HttpServletResponse resp) { Connection conn = null; try { String name = req.getParameter("name"); String email = req.getParameter("email"); String birth = req.getParameter("birth"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = format.parse(birth); conn = JdbcUtils.getConnection(); listIpm.addCustomer(conn,name,email,date); resp.sendRedirect("customers.do"); } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtils.closeResource(conn,null); } } private void delete(HttpServletRequest req, HttpServletResponse resp) { String idStr = req.getParameter("sid"); if (StringUtil.isNotEmpty(idStr)) { Connection conn = null; try { int id = Integer.parseInt(idStr); conn = JdbcUtils.getConnection(); listIpm.delById(conn,id); resp.sendRedirect("customers.do"); } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtils.closeResource(conn,null); } } } private void edit(HttpServletRequest req, HttpServletResponse resp) { Connection conn = null; try { conn = JdbcUtils.getConnection(); // 1.去数据库中查询某一个库存记录,根据thymeleaf在html中的超链接标签中提供的id String idStr = req.getParameter("cid"); // 2.将判断idStr不是空字符串且不为null的语句写成一个工具类内的方法,可以方便后续频繁调用 if (StringUtil.isNotEmpty(idStr)) { int id = Integer.parseInt(idStr); System.out.println(id); Customers customer = listIpm.getCustomerById(conn, id); System.out.println(customer); // 3.将获取到的对象变量以键值对的形式保存到作用域中 req.setAttribute("cu" ,customer); // 4.调用模板处理方法,连接到edit.html文件中(如果该页面不存在,就创建一个) super.processTemplate("edit",req,resp); } } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtils.closeResource(conn,null); } } private void update(HttpServletRequest req, HttpServletResponse resp) { Connection conn = null; try { String idStr = req.getParameter("id"); int id = Integer.parseInt(idStr); String name = req.getParameter("name"); String email = req.getParameter("email"); String birth = req.getParameter("birth"); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = format.parse(birth); conn = JdbcUtils.getConnection(); listIpm.updateById(conn,name,email,date,id); resp.sendRedirect("customers.do"); } catch (Exception e) { e.printStackTrace(); } finally { JdbcUtils.closeResource(conn,null); } } }
-
html文件
index.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" th:href="@{CSS/index.css}"> <script language="JavaScript" th:src="@{js/index.js}" ></script> </head> <body> <div id="div_contain"> <div id="div_fruit_list"> <p class="center f32">欢迎使用客户后台管理系统</p> <!-- 查询层 --> <div style="float: left; margin-left: 20%;width: 60%" > <form th:action="@{/customers.do}" method="post"> <!-- 增加隐藏域,给operate赋值,对应index方法 --> <input type="hidden" name="operate" value="index"> <input type="hidden" name="oper" value="search"> 请输入查询关键字<input type="text" name="keyword"/> <input type="submit" value="查询" /> </form> </div> <!-- 添加层 --> <div style=" width:60% ; margin-left: 20%; float: right"> <a th:href="@{/add.html}" style=" margin-bottom: 10px"> 新添加客户 </a> </div> <!-- thymeleaf渲染表格 --> <table id="tbl_fruit"> <tr> <th>cust_id</th> <th>cust_name</th> <th>cust_email</th> <th>cust_birth</th> </tr> <tr th:if="${#lists.isEmpty(session.cl)}"> <td colspan="4">无客户名单!</td> </tr> <tr th:unless="${#lists.isEmpty(session.cl)}" th:each="cust:${session.cl}"> <td> <!-- get请求,给operate赋值,对应edit方法 --> <a th:text="${cust.id}" th:href="@{/customers.do(cid=${cust.id},operate='edit')}">1</a> </td> <td th:text="${cust.name}">太白金星</td> <td th:text="${cust.email}" th:onclick="|delCust(${cust.id})|">tbstart@163.com</td> <td th:text="${cust.birth}">1000-1-1</td> </tr> </table> <!-- 分页按钮层 --> <div style="width:60% ; margin-left: 20%"> <input th:type="button" th:value="首页" th:onclick="|pageControl(1)|" th:disabled="${session.pageOn==1}"/> <input th:type="button" th:value="上一页" th:onclick="|pageControl(${session.pageOn-1})|" th:disabled="${session.pageOn==1}"/> <input th:type="button" th:value="下一页" th:onclick="|pageControl(${session.pageOn+1})|" th:disabled="${session.pageOn==session.max}"/> <input th:type="button" th:value="尾页" th:onclick="|pageControl(${session.max})|" th:disabled="${session.pageOn==session.max}"/> </div> </div> </div> </body> </html>
add.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <base href="http://localhost:8080/optimization_1/" > <link rel="stylesheet" href="CSS/edit.css" > </head> <body> <div id="div_contain"> <div id="div_fruit_list"> <p class="center f32">修改/编辑库存信息</p> <form action="customers.do" method="post"> <!-- 增加隐藏域,给operate赋值,对应add方法 --> <input type="hidden" name="operate" value="add" /> <table id="tbl_fruit"> <tr> <th>cust_name</th> <td><input type="text" name="name" /></td> </tr> <tr> <th>cust_email</th> <td><input type="text" name="email" /></td> </tr> <tr> <th>cust_birth</th> <td><input type="text" name="birth" /></td> </tr> <tr> <th colspan="2"> <input type="submit" value="添加" /> </th> </tr> </table> </form> </div> </div> </body> </html>
edit.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <html> <head> <meta charset="UTF-8"> <link th:rel="stylesheet" th:href="@{CSS/index.css}"> </head> <body> <div id="div_contain"> <div id="div_fruit_list"> <p class="center f32">修改/编辑库存信息</p> <form th:action="@{/customers.do}" method="post"> <!-- 新增了隐藏域,为operate赋值,du --> <input type="hidden" name="operate" value="update"/> <table id="tbl_fruit" th:object="${cu}"> <tr> <th>cust_id</th> <td><input type="text" name="id" th:value="*{id}"/></td> </tr> <tr> <th>cust_name</th> <td><input type="text" name="name" th:value="*{name}"/></td> </tr> <tr> <th>cust_email</th> <td><input type="text" name="email" th:value="*{email}"/></td> </tr> <tr> <th>cust_birth</th> <td><input type="text" name="birth" th:value="*{birth}"/></td> </tr> <tr> <th colspan="2"> <input th:type="submit" th:value="提交" /> </th> </tr> </table> </form> </div> </div> </body> </html>
-
js文件
function delCust(s) { if (confirm('是否确认删除')) { <!-- 在url上添加operate的值,对应到delete方法 --> window.location.href = 'customers.do?sid=' + s +'&operate=delete'; } } function pageControl(page) { if (confirm("确认")) { <!-- 在url上添加operate的值,对应到index方法 --> window.location.href = 'customers.do?page=' + page +'&operate=index'; } }