基于Ajax的商品搜索的展示

JavaWeb学习大纲传送门

本章学习目录

一,流程图解释

在这里插入图片描述

二,servlet层的数据处理
  • 从界面得到的数据常见的几种处理方法:
    Double.parseDouble(对象)
    new SimpleDateFormat("yyyy-MM-dd").parse(对象)
  • 从数据库中返回的数据的处理
  1. 传统的将集合对象处理成JSON格式的方式:
           PrintWriter out = response.getWriter();
           StringBuffer stringBuffer = new StringBuffer("[");
           for (Goods goods:goodsList){
               stringBuffer.append("{");
               stringBuffer
                       .append("'g_id':")
                       .append(goods.getG_id())
                       .append(",")
                       .append("'g_name':'")
                       .append(goods.getG_name())
                       .append("',")
                       .append("'g_price':")
                       .append(goods.getG_price())
                       .append(",")
                       .append("'g_date':'")
                       .append(goods.getG_date()).append("'");
               stringBuffer.append("}").append(",");
           }
           stringBuffer.deleteCharAt(stringBuffer.length()-1);
           stringBuffer.append("]");
           //将goods对象输出到客户端
           out.print(stringBuffer.toString());
  1. 运用maven提供的依赖管理中的fastjson中的方法:

maven坐标(放入xml下的<dependencies></dependencies>中):

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.76</version>
    </dependency>

servlet中的操作

            PrintWriter out = response.getWriter();
            out.print(JSONArray.toJSON(goodsList));
三,html界面的接收和处理
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <title>展示商品</title>
    <style>
        table{
            border: 1px solid orange;
            width: 600px;
            border-collapse: collapse;
        }
        th,td{
            border: 1px solid orange;
            height: 50px;
            line-height: 50px;
            text-align: center;
        }
    </style>
</head>
<body>
<form name="searchFrom">
    商品名称:<input type="text" name="g_name" id="g_name"/>
    单价:<input type="text" name="g_price1" placeholder="起始单价" id="g_price1"/>-<input type="text" name="g_price2" placeholder="结束单价" id="g_price2"/>
    上架时间:<input type="date" name="g_date1" placeholder="起始时间" id="g_date1"/>-<input type="date" name="g_date2" placeholder="结束时间" id="g_date2"/>
    <button type="button" onclick="getGoods()">搜索</button>
</form>
<table>
    <thead>
    <tr>
        <th>商品编号</th>
        <th>商品名称</th>
        <th>商品单价</th>
        <th>上架时间</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>

    </tbody>
</table>
<script>
getGoods();//加载时调用
/**
 * 获得商品数据
 */
function getGoods() {
    //获得表单提交的数据
    let g_name=document.searchFrom.g_name.value;
    let g_price1=document.searchFrom.g_price1.value;
    let g_price2=document.searchFrom.g_price2.value;
    let g_date1=document.searchFrom.g_date1.value;
    let g_date2=document.searchFrom.g_date2.value;
    console.log(g_name,g_price1,g_price2,g_date1,g_date2);
    let xmlHttpRequest=new XMLHttpRequest();
    xmlHttpRequest.open("GET","goods.do?operate=getGoods&g_name="+g_name+"&g_price1="+g_price1+"&g_price2="+g_price2+"&g_date1="+g_date1+"&g_date2="+g_date2);
    xmlHttpRequest.onreadystatechange=function () {
        if (xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){
            //接收数据
            let goodsArrstr=xmlHttpRequest.responseText;
            let tbodyObj=document.querySelectorAll("table tbody")[0];
            //清除tbody中的数据
            tbodyObj.innerHTML="";
            if (goodsArrstr==""||goodsArrstr.length==0){
                let trobj = document.createElement("tr");
                tbodyObj.appendChild(trobj);
                let tdobj = document.createElement("td");
                tbodyObj.appendChild(tdobj);
                tdobj.colSpan="5";
                tdobj.innerHTML="不好意思,没有该范围内的数据";
                trobj.appendChild(tdobj);
                return;
            }
            //将接受到的数据处理
            let goodsArr = eval("("+goodsArrstr+")");
            //获得表格对象
            //querySelectorAll通过选择器获得js对象

            //遍历goodsArr
            for (let goods of goodsArr){
                //创建tr对象
                let trObj=document.createElement("tr");
                //将tr对象添加到tbody对象中
                tbodyObj.appendChild(trObj);
                let tdObj0 = document.createElement("td");
                tdObj0.innerHTML=goods.g_id;
                //将td对象添加tr中
                trObj.appendChild(tdObj0);

                let tdObj1 = document.createElement("td");
                tdObj1.innerHTML=goods.g_name;
                //将td对象添加tr中
                trObj.appendChild(tdObj1);

                let tdObj2 = document.createElement("td");
                tdObj2.innerHTML=goods.g_price;
                //将td对象添加tr中
                trObj.appendChild(tdObj2);

                let tdObj3 = document.createElement("td");
                tdObj3.innerHTML=goods.g_date_str;
                //将td对象添加tr中
                trObj.appendChild(tdObj3);


                let tdOperate = document.createElement("td");
                //创建两个超链接对象
                let updateLink = document.createElement("a");
                updateLink.innerHTML = "修改";
                //添加超链接地址
                updateLink.href = "goods.do?operate=updateGoods";

                let delLink = document.createElement("a");
                delLink.innerHTML = "删除";
                delLink.href="goods.do?operate=delGoodsById";
                delLink.style.marginLeft="10px";
                //将超链接对象添加到tdOperate中
                tdOperate.appendChild(updateLink).appendChild(delLink);
                trObj.appendChild(tdOperate);
            }
            //创建添加按钮
            let inserttd = document.createElement("td");
            let insertLink=document.createElement("a");
            inserttd.colSpan="5";
            insertLink.innerHTML="添加商品";
            insertLink.style.marginLeft="100px";
            //超链接地址
            insertLink.href="goods.do?operate=insertGoods";
            //将该超链接对象添加到tr中
            inserttd.appendChild(insertLink);
            tbodyObj.appendChild(inserttd);
        }
    }
    //发送请求
    xmlHttpRequest.send(null);
}
</script>
</body>
</html>
四,servlet层的方法
    protected void getGoods(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            System.out.println("getGoods被执行");
            GoodsView goodsView=new GoodsView();
            String g_name=request.getParameter("g_name");
            goodsView.setG_name(g_name==null||"".equals(g_name)?null:g_name);
            String g_price1= request.getParameter("g_price1");
            goodsView.setG_price1(g_name==null||"".equals(g_price1)?null:Double.parseDouble(g_price1));
            String g_price2= request.getParameter("g_price2");
            goodsView.setG_price2(g_name==null||"".equals(g_price2)?null:Double.parseDouble(g_price2));
            String g_date1= request.getParameter("g_date1");
            SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
            goodsView.setG_date1(g_name==null||"".equals(g_date1)?null:sim.parse(g_date1));
            String g_date2= request.getParameter("g_date2");
            goodsView.setG_date2(g_name==null||"".equals(g_date2)?null:sim.parse(g_date2));
            goodsView.setG_date2(g_name==null||"".equals(g_date2)?null:new SimpleDateFormat("yyyy-MM-dd").parse(g_date2));
            List<Goods> goodsList=goodsService.queryAll(goodsView);

            //设置response的内容类型
            response.setContentType("json/application;charset=utf-8");
            PrintWriter out = response.getWriter();

            //调用底层方法获得商品列表
            if (goodsList==null||goodsList.size()==0){
                out.print("");
                return;
            }
传统的将数据转换为json格式
//            StringBuffer stringBuffer = new StringBuffer("[");
//            for (Goods goods:goodsList){
//                stringBuffer.append("{");
//                stringBuffer
//                        .append("'g_id':")
//                        .append(goods.getG_id())
//                        .append(",")
//                        .append("'g_name':'")
//                        .append(goods.getG_name())
//                        .append("',")
//                        .append("'g_price':")
//                        .append(goods.getG_price())
//                        .append(",")
//                        .append("'g_date':'")
//                        .append(goods.getG_date()).append("'");
//                stringBuffer.append("}").append(",");
//            }
//            stringBuffer.deleteCharAt(stringBuffer.length()-1);
//            stringBuffer.append("]");
//            //将goods对象输出到客户端
//            out.print(stringBuffer.toString());
//使用了mavan坐标下的fastjjson中的方法
            System.out.println("使用fastjson进行转换");
            out.print(JSONArray.toJSON(goodsList));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值