JavaWeb小项目(四)- 基于Axios + JSON完成品牌列表的增查

JavaWeb小项目(四)- 基于 Axios + JSON 完成品牌列表的增查

查询所有

在这里插入图片描述

  • 实现 Dao 层:通过 select * from tb_brand 查询品牌数据表中的所有数据

    public interface BrandMapper {
    
       /**
        * 查询所有
        * @return
        */
       @Select("select * from tb_brand")
       @ResultMap("brandResultMap")
       List<Brand> selectAll();
    }
    
  • 实现 Service 层:调用 Dao 层的查询函数,将查询到的数据以列表的形式返回

    public class BrandService {
    
        SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();
    
        /**
         * 查询所有
         * @return
         */
        public List<Brand> selectAll(){
            //调用BrandMapper.selectAll()
    
            //1.获取SqlSession
            SqlSession sqlSession = factory.openSession();
    
            //2.获取BrandMapper
            BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    
            //3.调用方法
            List<Brand> brands = mapper.selectAll();
            sqlSession.close();
            return brands;
        }
    }
    
  • 实现 web 层之实现 SelectAllServlet:

    @WebServlet("/selectAllServlet")
    public class SelectAllServlet extends HttpServlet {
    
        private BrandService brandService = new BrandService();
    
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            //1.调用Service查询
            List<Brand> brands = brandService.selectAll();
    
            //2.将集合转换成JSON数据 (序列化)
            String jsonString = JSON.toJSONString(brands);
    
            //3.响应数据
            response.setContentType("text/json;charset=utf-8");
            response.getWriter().write(jsonString);
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request,response);
        }
    }
    
  • 实现 web 层之实现在brand.html添加页面交互的脚本:

    <script src="js/axios-0.18.0.js"></script>
    <script>
        //1.当页面加载完成后,发送ajax请求
        window.onload = function () {
           //2.发送ajax请求
           axios({
               method:"get",
               url:"http://localhost:8080/brand-demo/selectAllServlet"
           }).then(function (response) {
                //获取数据
                let brands = response.data;
                let tableData = "<tr>\n" +
                    "        <th>序号</th>\n" +
                    "        <th>品牌名称</th>\n" +
                    "        <th>企业名称</th>\n" +
                    "        <th>排序</th>\n" +
                    "        <th>品牌介绍</th>\n" +
                    "        <th>状态</th>\n" +
                    "        <th>操作</th>\n" +
                    "    </tr>";
    
                for (let i=0;i<brands.length;i++){
                    let brand = brands[i];
    
                    tableData += "\n" +
                        "     <tr align=\"center\">\n" +
                        "        <td>"+(i+1)+"</td>\n" +
                        "        <td>"+brand.brandName+"</td>\n" +
                        "        <td>"+brand.companyName+"</td>\n" +
                        "        <td>"+brand.ordered+"</td>\n" +
                        "        <td>"+brand.description+"</td>\n" +
                        "        <td>"+brand.status+"</td>\n" +
                        "\n" +
                        "        <td><a href=\"#\">修改</a> <a href=\"#\">删除</a></td>\n" +
                        "       </tr>";
                }
    
                //设置表格数据,注意一定要在<table>标签中设置id
               document.getElementById("brandTable").innerHTML = tableData;
           })
        }
    </script>
    

新增品牌

在这里插入图片描述

  • 实现 Dao 层:通过 insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status}) 添加品牌数据到品牌数据列表中
    public interface BrandMapper {
    
        /**
         * 添加数据
         * @param brand
         */
        @Insert("insert into tb_brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
        void add(Brand brand);
    }
    
  • 实现 web 层之实现 AddAllServlet:
    @WebServlet("addServlet")
    public class AddServlet extends HttpServlet {
    
        private BrandService brandService = new BrandService();
    
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
            //1.接收请求体数据
            BufferedReader br = request.getReader();
            String params = br.readLine();
    
            //将JSON字符串转为Java对象
            Brand brand = JSON.parseObject(params, Brand.class);
    
            //2.调用Service 添加
            brandService.add(brand);
    
            //3.响应完成标识
            response.getWriter().write("success");
        }
    
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request,response);
        }
    }
    
  • 实现 web 层之实现在 brand.html 添加页面交互的脚本:
    <script src="js/axios-0.18.0.js"></script>
    <script>
        //1.按钮绑定单击事件
        document.getElementById("btn").onclick = function () {
    
            //将表单数据转换成json
            var formData = {
                brandName:"",
                companyName:"",
                ordered:"",
                description:"",
                status:"",
            };
            //获取表单数据
            let brandName = document.getElementById("brandName").value;
            formData.brandName = brandName;
    
            let companyName = document.getElementById("companyName").value;
            formData.companyName = companyName;
    
            let ordered = document.getElementById("ordered").value;
            formData.ordered = ordered;
    
            let description = document.getElementById("description").value;
            formData.description = description;
    
    
            let status = document.getElementByName("status");
            for(let i=0;i<status.length;i++){
                if(status[i].checked){
                    //选中
                    formData.status = status[i].value;
                }
            }
    
            console.log(formData);
    
            //2.发送ajax请求
            axios({
                method:"post",
                url:"http://localhost:8080/brand-demo/addServlet",
                data:formData
            }).then(function (response) {
                //判断响应数据是否 success
                if(response.data == "success"){
                    location_href = "http://localhost:8080/brand-demo/brand.html";
                }
            })
        }
    
    </script>
    

修改品牌(自主练习)

回显数据

  • 实现 Dao 层:通过选中数据的id在数据库查询出对应的数据,再将其数据回显出来;
    public interface BrandMapper {
        
        /**
         * 根据id查询
         * @param id
         * @return
         */
        @Select("select * from tb_brand where id=#{id}")
        @ResultMap("brandResultMap")
        Brand selectById(int id);
    }
    
  • 实现 Service 层:调用 Dao 层的查询函数,返回该对象
    public class BrandService {
      	
      	/**
         * 根据id查询
         * @param id
         * @return
         */
        public Brand selectById(int id){
            //调用BrandMapper.selectById(id)
    
            //1.获取SqlSession
            SqlSession sqlSession = factory.openSession();
    
            //2.获取BrandMapper
            BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    
            //3.调用方法
            Brand brand = mapper.selectById(id);
            sqlSession.close();
            return brand;
        }
    }
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值