当前位置:Gxlcms > 数据库问题 > 基于JSP+Serlvet+JDBC的开发(5)-- 商品功能

基于JSP+Serlvet+JDBC的开发(5)-- 商品功能

时间:2021-07-01 10:21:17 帮助过:3人阅读

<html> 2 <head> 3 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 4 <%@ include file="top.jsp"%> 5 <title>商品展示</title> 6 </head> 7 <body> 8 <div class="main"> 9 <div> 10 <a href="${root}/send?url=goods-save.jsp">添加商品</a> 11 </div> 12 <table> 13 <tr> 14 <td>序号</td> 15 <td>商品名称</td> 16 <td>商品价格</td> 17 </tr> 18 <c:forEach items="${entities}" var="obj" varStatus="status"> 19 <tr> 20 <td>${status.index + 1 }</td> 21 <td>${obj.name}</td> 22 <td>${obj.price}</td> 23 </tr> 24 </c:forEach> 25 </table> 26 </div> 27 </body> 28 </html>

Controller层(Serlvet):

 1 package action;
 2 
 3 import java.io.IOException;
 4 import java.util.List;
 5 
 6 import javax.servlet.RequestDispatcher;
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 
12 import model.Goods;
13 import service.GoodsService;
14 import service.impl.GoodsServiceImpl;
15 
16 public class GoodsAction extends HttpServlet {
17     private static final long serialVersionUID = 1L;
18 
19     private static final String[] action = { "tid", "save", "delete", "update" };
20     private GoodsService goodsService = new GoodsServiceImpl();
21 
22     protected void doGet(HttpServletRequest request, HttpServletResponse response)
23             throws ServletException, IOException {
24         doPost(request, response);
25     }
26 
27     protected void doPost(HttpServletRequest request, HttpServletResponse response)
28             throws ServletException, IOException {
29         // 获取action
30         String actionName = request.getParameter("action") != null ? request.getParameter("action") : "";
31         int actionIndex = 0;
32         for (int i = 0; i < action.length; i++) {
33             if (action[i].equals(actionName)) {
34                 actionIndex = i;
35                 break;
36             }
37         }
38         // 保存action操作结果[d/r, url]
39         String[] r = null;
40         // 根据actionIndex调用对应的方法
41         switch (actionIndex) {
42         case 0:
43             r = tip(request, response);
44             break;
45         case 1:
46             r = save(request, response);
47         }
48 
49         // 根据action操作结果执行相应的操作
50         if ("d".equals(r[0])) {// 转发
51             RequestDispatcher rd = request.getRequestDispatcher(r[1]);
52             rd.forward(request, response);
53         } else {// 重定向
54             response.sendRedirect(r[1]);
55         }
56     }
57 
58     // 根据类似ID获取商品
59     private String[] tip(HttpServletRequest request, HttpServletResponse response) {
60         Long tid = Long.parseLong(request.getParameter("tid"));
61         List<Goods> gList = goodsService.findByTid(tid);
62         request.setAttribute("entities", gList);
63         return new String[] { "d", "WEB-INF/jsp/goods-index.jsp" };
64     }
65 
66     // 保存商品
67     private String[] save(HttpServletRequest request, HttpServletResponse response) {
68         String name = request.getParameter("name");
69         String price = request.getParameter("price");
70         boolean isNull = false;
71         if (name == null || "".equals(name)) {
72             request.setAttribute("msg-name", "商品名称不能为空");
73             isNull = true;
74         }
75         if (price == null || "".equals(price)) {
76             request.setAttribute("msg-price", "商品价格不能为空");
77             isNull = true;
78         }
79         try {
80             Double.parseDouble(price);
81         } catch (Exception e) {
82             request.setAttribute("msg-price", "商品价格不能为字符");
83             isNull = true;
84         }
85         
86         if (isNull) {
87             return new String[] { "d", "WEB-INF/jsp/goods-save.jsp" };
88         }
89         // 保存实体
90         Goods g = new Goods();
91         g.setName(name);
92         g.setPrice(Double.parseDouble(price));
93         g.setTid(Long.parseLong(request.getParameter("tid")));
94         goodsService.save(g);
95         String root = request.getContextPath();
96         return new String[] { "r", root + "/type" };
97     }
98 
99 }

Service层(这里GoodsService除了基本的增删查改外,还有自己的一个业务,就是根据商品类型ID获取所有该类型的商品):

1 public interface GoodsService extends BaseServcice<Long, Goods>{
2 
3     // 根据类型ID查询所有商品
4     List<Goods> findByTid(Long tid);
5 }

Service的实现(直接调用DAO层)

 1 public class GoodsServiceImpl extends BaseServiceImpl<Long, Goods> implements GoodsService{
 2 
 3     private GoodsDAO goodsDAO = new GoodsDAOImpl();
 4     
 5     @Override
 6     protected BaseDAO<Long, Goods> getBaseDAO() {
 7         return goodsDAO;
 8     }
 9 
10     @Override
11     public List<Goods> findByTid(Long tid) {
12         return goodsDAO.findByTid(tid);
13     }
14 }

DAO层:

1 public interface GoodsDAO extends BaseDAO<Long, Goods>{
2 
3     // 根据商品类型查询所有商品
4     List<Goods> findByTid(Long tid);
5 }

DAO的实现(由于DAO继承了BaseDAOImpl,所有普通的增删查改就不用实现了,只要实现自己的就可以了。)

 1 public class GoodsDAOImpl extends BaseDAOImpl<Long, Goods> implements GoodsDAO{
 2 
 3     @Override
 4     public List<Goods> findByTid(Long tid) {
 5         String findSQL = "select * from tb_goods where tid = ?";
 6         List<Goods> gList = new ArrayList<Goods>();
 7         try {
 8             conn = DBUtil.getConn();
 9             pstmt = conn.prepareStatement(findSQL);
10             pstmt.setLong(1, tid);
11             rs = pstmt.executeQuery();
12             
13             Goods g = null;
14             while (rs.next()) {
15                 g = new Goods();
16                 g.setName(rs.getString("name"));
17                 g.setPrice(rs.getDouble("price"));
18                 gList.add(g);
19             }
20         } catch (Exception e) {
21             LogUtil.log(e.getMessage());
22             throw new RuntimeException(e);
23         }
24         return gList;
25     }
26 }

这里除了展示商品外依然提供了添加商品的连接:

 1 <html>
 2 <head>
 3 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 4 <%@ include file="top.jsp"%>
 5 <title>添加商品</title>
 6 </head>
 7 <body>
 8     <form action="${root}/goods?action=save" method="post">
 9         <table>
10             <caption>添加商品</caption>
11             <tr>
12                 <td>商品名称:</td>
13                 <td><input type="text" name="name"/></td>
14                 <td>${msg}</td>
15             </tr>
16             <tr>
17                 <td>商品价格:</td>
18                 <td><input type="text" name="price"/></td>
19                 <td>${msg}</td>
20             </tr>
21             <tr>
22                 <td>商品类型:</td>
23                 <td id="type-select">
24                 </td>
25                 <td>${msg}</td>
26             </tr>
27             <tr>
28                 <td colspan="3"><input type="submit" value="添加"/></td>
29             </tr>
30         </table>
31     </form>
32     
33     <script type="text/javascript" src="${root}/resources/js/jquery-1.11.1.js"></script>
34     <script type="text/javascript" src="${root}/resources/js/goods-save.js"></script>
35 </body>
36 </html>

技术分享

需要注意的是,这里的下拉框是在页面加载完后,异步向后台查询并添加的。这里使用了jQuery发送异步请求。

$(function() {
    $.ajax({
        url : "type?action=ajax-type",
        dataType : "json",
        success : function(r) {
            // "<select><option value>"
            var html = "<select name=‘tid‘>";
            for (var i = 0; i < r.total; i++) {
                html += "<option value=‘" + r.data[i].id + "‘>"
                        + r.data[i].name + "</option>";
            }
            html += "<select>";
            $("#type-select").html(html);
        }
    })
});

后台实现type这个Serlvet中的ajaxType方法负责这个请求并拼凑返回JSON数据:

 1 // 异步拉取type数据
 2     private String[] ajaxType(HttpServletRequest request, HttpServletResponse response) {
 3         List<Type> tList = typeService.find();
 4         StringBuffer json = new StringBuffer("{ \"total\" : ").append(tList.size()).append(", \"data\" : [");
 5         if (!tList.isEmpty()) {
 6             for (int i = 0, size = tList.size(); i < size - 1; i++) {
 7                 json = json.append("{\"id\" : ").append(tList.get(i).getId()).append(", \"name\" : \"")
 8                         .append(tList.get(i).getName()).append("\"},");
 9             }
10             json = json.append("{\"id\" : ").append(tList.get(tList.size() - 1).getId()).append(", \"name\" : \"")
11                     .append(tList.get(tList.size() - 1).getName()).append("\"}");
12         }
13         json = json.append("]}");
14 
15         return new String[] { "", json.toString() };
16     }

这里的返回数组的第一个对象是“”,不是“r”,也不是“d”,所以第二个对象json.toString()会被直接输出都客户端,相关代码如下:

 1     // 根据action操作结果执行相应的操作
 2         if ("d".equals(r[0])) {// 转发
 3             RequestDispatcher rd = request.getRequestDispatcher(r[1]);
 4             rd.forward(request, response);
 5         } else if ("r".equals(r[0])) {// 重定向
 6             response.sendRedirect(r[1]);
 7         } else {// 直接输出r[1]的内容
 8             PrintWriter out = response.getWriter();
 9             out.println(r[1]);
10             out.flush();
11             out.close();
12         }

这样基本的功能都实现了,接下来的改善地方就是利用Filter统一解决乱码问题,利用Listener项目启动就加载类型并放在application中(这样项目就不会每个人访问的都去数据库查一次类型了,毕竟类型改变的几率很少,即使改变了,重新加载一次就可以了。)还有一点改善的地方就是自定义注解解决表名的约定。

昨天忙了一晚上还落枕了,脖子一天都不舒服,坑爹。好了周末又过了。

基于JSP+Serlvet+JDBC的开发(5)-- 商品功能

标签:

人气教程排行