20220720_JSON使用案例_数据库查询和新增

本例在已经有项目代码基础上扩展,
参考本贴的准备工作部分
完成后结构图
brand-demo模块
请添加图片描述
因为要用到JSON语句,所以要导入JSON的坐标,maven的pom.xml最后如下

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>brand-demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>


    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>

        <!--jstl-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <!--JSON-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.7</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
            </plugin>
        </plugins>
    </build>
    
</project>

mybatis-config.xml也给一个,数据库的数据自行准备

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--起别名-->
    <typeAliases>
        <package name="com.diy.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql:///mybatis?useSSL=false&amp;useServerPrepStmts=true"/>
                <property name="username" value="root"/>
                <property name="password" value="1234"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--扫描mapper-->
        <package name="com.diy.mapper"/>
    </mappers>
</configuration>

文章目录


查询功能
不安思路分步了,直接上完成态代码
写一个brand.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<a href="addBrand.html"><input type="button" value="新增"></a><br>
<hr>
<table id="brandTable" border="1" cellspacing="0" width="100%">
<!--    <tr>-->
<!--        <th>序号</th>-->
<!--        <th>品牌名称</th>-->
<!--        <th>企业名称</th>-->
<!--        <th>排序</th>-->
<!--        <th>品牌介绍</th>-->
<!--        <th>状态</th>-->
<!--        <th>操作</th>-->
<!--    </tr>-->
<!--    <tr align="center">-->
<!--        <td>1</td>-->
<!--        <td>三只松鼠</td>-->
<!--        <td>三只松鼠</td>-->
<!--        <td>100</td>-->
<!--        <td>三只松鼠,好吃不上火</td>-->
<!--        <td>启用</td>-->
<!--        <td><a href="#">修改</a> <a href="#">删除</a></td>-->
<!--    </tr>-->

<!--    <tr align="center">-->
<!--        <td>2</td>-->
<!--        <td>优衣库</td>-->
<!--        <td>优衣库</td>-->
<!--        <td>10</td>-->
<!--        <td>优衣库,服适人生</td>-->
<!--        <td>禁用</td>-->

<!--        <td><a href="#">修改</a> <a href="#">删除</a></td>-->
<!--    </tr>-->

<!--    <tr align="center">-->
<!--        <td>3</td>-->
<!--        <td>小米</td>-->
<!--        <td>小米科技有限公司</td>-->
<!--        <td>1000</td>-->
<!--        <td>为发烧而生</td>-->
<!--        <td>启用</td>-->

<!--        <td><a href="#">修改</a> <a href="#">删除</a></td>-->
<!--    </tr>-->
</table>

<script src="js/axios-0.18.0.js"></script>

<script>
    //when whole window onload
    window.onload = function (){
        //send axios request
        axios({
            method:"get",
            url:"http://localhost:8080/brand-demo/queryAllServlet"
        }).then(function (resp){
            let brands = resp.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>"
            //json has convert list<brand> to a brand array, so we can use for i
            for (let i = 0; i < brands.length; i++) {
                let brand = brands[i]
                tableData += "<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" +
                    "        <td><a href=\"#\">Edit</a> <a href=\"#\">Delete</a></td>\n" +
                    "    </tr>"
            }
            document.getElementById("brandTable").innerHTML = tableData
        })
    }
</script>

</body>
</html>

写对应的查询servlet

package com.diy.web;

import com.alibaba.fastjson.JSON;
import com.diy.pojo.Brand;
import com.diy.service.BrandService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/queryAllServlet")
public class queryAllServlet extends HttpServlet {
    //get a service object
    private BrandService bsr = new BrandService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //query all brand info
        List<Brand> brands = bsr.selectAll();
        //convert it to json, serialization
        String jsonBrands = JSON.toJSONString(brands);
        //response to html
        resp.setContentType("text/json;charset=utf-8");
        resp.getWriter().write(jsonBrands);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

写好servlet如果访问http://localhost:8080/brand-demo/servlet可以看到
请添加图片描述
list数据经json传给网页后,输出是一个数组的格式
访问http

文章目录


添加功能
整个思路完成后的addBrand.html页面

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>添加品牌</title>
</head>
<body>
<h3>添加品牌</h3>
<form action="" method="post">
    品牌名称:<input id="brandName" name="brandName"><br>
    企业名称:<input id="companyName" name="companyName"><br>
    排序:<input id="ordered" name="ordered"><br>
    描述信息:<textarea rows="5" cols="20" id="description" name="description"></textarea><br>
    状态:
    <input type="radio" name="status" value="0">禁用
    <input type="radio" name="status" value="1">启用<br>

    <input type="button" id="btn"  value="提交">
    <!--here is a normal button, not a submit button, so it must be submitted by diy-->
    <!--and normal submit is sync type, diy here is async type by json data-->
</form>
<script src="js/axios-0.18.0.js"></script>
<script>

    document.getElementById("btn").onclick = function (){

        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.getElementById("status").value
        // formData.status = status
        /**
         * get the value of status, code like others instead by the way under
         */
        for (let stat of document.getElementsByName("status")) {
            if (stat.checked){
                formData.status = stat.value
            }
        }

        console.log(formData)

        axios({
            method:"post",
            url:"http://localhost:8080/brand-demo/addServlet",
            data:formData
            /*{} is json format*/
        }).then(function (resp){
            if (resp.data == "1"){
                location.href="http://localhost:8080/brand-demo/brand.html"
            }
        })
    }
</script>


</body>
</html>

对应的servlet

package com.diy.web;

import com.alibaba.fastjson2.JSON;
import com.diy.pojo.Brand;
import com.diy.service.BrandService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/addServlet")
public class addServlet extends HttpServlet {
    //get a service object
    private BrandService bsr = new BrandService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * we can't use this ways get data from json format, you print out a null
         * getParameter get data by split by & and =
         */
//        String brandName = req.getParameter("brandName");
//        System.out.println(brandName);

        //1.through right way receive data in post
        req.setCharacterEncoding("utf-8");

        BufferedReader reader = req.getReader();
        String data = reader.readLine();//no matter how long the data is ,it is one line

        //2.convert to brand ob
        Brand brand = JSON.parseObject(data, Brand.class);
        System.out.println(brand);

        //3.insert into database
        bsr.add(brand);
        //4.if no exception
        resp.getWriter().write("1");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

访问添加功能的网址
请添加图片描述
提交后idea的控制台根据代码输出
请添加图片描述
有乱码,是我的系统环境原因,无法解决,但提交后的网页正常,因为代码里对应乱码有代码请添加图片描述
数据库里也是正常的请添加图片描述
直接在数据库改了一下内容

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值