2022/10/15 作业实现前端和后端的数据交换的作业(查询和增加功能)

1、 创建模块webDemo7

  1. 使用maven里面的 骨架构建,并补全相关的目录。
    如图所示

2 、
打开 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>webDemo7</artifactId>
  <version>1.0-SNAPSHOT</version>

  <packaging>war</packaging>

  <dependencies>

<!--    配置 json -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.28</version>
    </dependency>

<!-- 配置 测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>

    <!--  配置servlet -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- 导入 mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.9</version>
    </dependency>

    <!-- 导入 Mysql 驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.48</version>
    </dependency>

  </dependencies>

  <build>
    <plugins>
      <!--Tomcat插件 -->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>

          <port>8080</port><!--访问端口号 -->
          <!--项目访问路径
              未配置访问路径: http://localhost:80/tomcat-demo2/a.html
              配置/后访问路径: http://localhost:80/a.html
              如果配置成 /hello,访问路径会变成什么?
                  答案: http://localhost:80/hello/a.html
          -->
          <path></path>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


3、
在 resources 目录下 建立 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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!-- 自己数据库的地址 端口号 和 要操作的数据库名字-->
                <property name="url" value="jdbc:mysql://localhost:3306/awork"/> 
                <!-- value 自己数据库的名字-->
                <property name="username" value="root"/>
                 <!-- value 自己数据库的密码 (这里没有写,是因为我自己的数据库没有密码)-->
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>

    <!-- 配置包扫描 根据自己的mapper文件目录设置-->
<!--    <mappers>
       <package name=""/>
    </mappers>-->
    <mappers>
        <package name="com.mapper"/>
    </mappers>


</configuration>

4、
在java包下建立 以下 6个目录(下面会详细讲解每个目录的用途)

在这里插入图片描述

5、
在 resources 目录建立与 上面 java目录下相对应mapper目录 在这里插入图片描述

6、
在上面创建的 pojo目录下 建立 Brand 实体类
(实体类的成员类型 需要与需要操作的数据的字段类型对应)
这个是我要操作的数据库的字段及类型
在这里插入图片描述
这个是我根据操作数据库字段的类型创建的私有成员,和标准的JavaBean

package com.pojo;

public class Brand {
    private Integer id;
    private String brandName;
    private String companyName;
    private Integer ordered;
    private String description;
    private Integer status;


    public Brand() {
    }

    public Brand(Integer id, String brandName, String companyName, Integer ordered, String description, Integer status) {
        this.id = id;
        this.brandName = brandName;
        this.companyName = companyName;
        this.ordered = ordered;
        this.description = description;
        this.status = status;
    }

    /**
     * 获取
     * @return id
     */
    public Integer getId() {
        return id;
    }

    /**
     * 设置
     * @param id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 获取
     * @return brandName
     */
    public String getBrandName() {
        return brandName;
    }

    /**
     * 设置
     * @param brandName
     */
    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    /**
     * 获取
     * @return companyName
     */
    public String getCompanyName() {
        return companyName;
    }

    /**
     * 设置
     * @param companyName
     */
    public void setCompanyName(String companyName) {
        this.companyName = companyName;
    }

    /**
     * 获取
     * @return ordered
     */
    public Integer getOrdered() {
        return ordered;
    }

    /**
     * 设置
     * @param ordered
     */
    public void setOrdered(Integer ordered) {
        this.ordered = ordered;
    }

    /**
     * 获取
     * @return description
     */
    public String getDescription() {
        return description;
    }

    /**
     * 设置
     * @param description
     */
    public void setDescription(String description) {
        this.description = description;
    }

    /**
     * 获取
     * @return status
     */
    public Integer getStatus() {
        return status;
    }

    /**
     * 设置
     * @param status
     */
    public void setStatus(Integer status) {
        this.status = status;
    }

    public String toString() {
        return "Brand{id = " + id + ", brandName = " + brandName + ", companyName = " + companyName + ", ordered = " + ordered + ", description = " + description + ", status = " + status + "}";
    }
}

创建完成后,效果如下
在这里插入图片描述

7、
此时需要创建 是Brand 实体类对应的接口 BrandMapper
(其中 里面写了两个 抽象方法)

package com.mapper;

import com.pojo.Brand;

import java.util.List;

public interface BrandMapper {

    // 查询所有
    List<Brand> BrandSelectAll();

    // 添加数据
    int BrandInserts(Brand brand);

}

创建完成后,效果如下(自己使用了Mybatics 插件 会出现小鸟的图标,没有也没关系)
在这里插入图片描述

8、
在这之后 建立相对应的BrandMapper.xml文件
(注意这个文件名和目录路径一定要和上面Java目录下创建的mapper目录对应)
这里的xml文件,是为了实现上面接口文件的方法内容

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
        <!-- 这里的 namespace 是在Java目录里面建立的BrandMapper所在的目录-->
<mapper namespace="com.mapper.BrandMapper">

 <!-- 这里的 id 一定要与接口里面的方法名一致  type 指的是返回类型-->
    <resultMap id="brandResultMap" type="com.pojo.Brand">
        <result column="brand_name" property="brandName"/>
        <result column="company_name" property="companyName"/>
    </resultMap>

    <!-- 添加数据 -->
    <insert id="BrandInserts">
        insert into tb_brand
        values (null, #{brandName}, #{companyName}, #{ordered}, #{description}, #{status});

    </insert>

    <!-- 查询所有 -->
    <select id="BrandSelectAll" resultMap="brandResultMap">
        select *
        from tb_brand;

    </select>
</mapper>

效果如下
在这里插入图片描述

9、
完成上面的几个步骤后,最好在test里面进行测试,检测是否存在错误

在这个测试方法中,是为了检测查询数据的所有值,是否存在错误
如果能够查询出结果,那就说明,success。否则就得改bug

 @org.junit.Test
    public void BrandSelectAll() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
       List<Brand> brands = mapper.BrandSelectAll();
       System.out.println(brands);
    }

10、
为了简化SqlSessionFactory使用的麻烦,我们这里,在util包下
建立工具类 SqlSessionFactoryUtils
方便我们后续使用SqlSessionFactory

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionFactoryUtils {

    private static SqlSessionFactory sqlSessionFactory;
    static {

        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

效果如下

在这里插入图片描述

11、在service的目录下建立 BrandService 用于封装SqlSessionFactory
在这里插入图片描述
代码:

package com.service;

import com.mapper.BrandMapper;
import com.pojo.Brand;
import com.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {

    // 查询所有
    public static List<Brand> BrandSelectAll() {
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.BrandSelectAll();
        return brands;
    }

    // 添加数据
    public static int BrandAdd(Brand brand) {
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        int brandInserts = mapper.BrandInserts(brand);
        return brandInserts;
    }
}

12、
在这里之后,我们依然需要使用测试类,来检测,我们的工具类是否出现错误

这块测试类,是检测使用我们创建的工具类,去查询数据的的所有数据

@org.junit.Test
    public void BrandSelectAll1() throws IOException {
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> brands = mapper.BrandSelectAll();
        System.out.println(brands);
    }

这块测试类,是为了检测我们使用工具类来向数据库中添加数据是否出现错误

    @org.junit.Test
    public void BrandInsert() throws IOException {
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        Brand brand = new Brand();
        brand.setBrandName("dsfssd");
        int i = mapper.BrandInserts(brand);
        System.out.println(i);
        // 提交事务
        sqlSession.commit();

    }

13、
到这里,我们已经完成了数据库的查询和增加的功能。接下来,我们开始实现前端和后端的交互
首先在 webapp目录下建立js目录 ,为了后续的axios的使用。
向其中 添加axios-0.18.0.js 文件

这里是引用链接:axios-0.18.0.js 文件
https://pan.baidu.com/s/1ma2PymEhrj6y7fZWbwhz6A?pwd=1234
提取码:1234

效果如下
在这里插入图片描述
在使用 axios-0.18.0.js 之前,需要使用引入。

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

14、下面开始编写前端页面
在webapp目录下
建立html文件,brand.html
注意:不要建立到WEB-INF的目录下
页面样式
在这里插入图片描述
代码:

<!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>

    // 发送数据
    axios({
        method: "get",
        // 这里的URL 是发送的地址。在下面我们一会回来编写brandSelectAllServlet
       url:"http://localhost:8080/webDemo7/brandSelectAllServlet"
    }).then(function (resp) {
        // 获取数据
        let brands = resp.data;
        let tableDates =
            "<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];
            tableDates +=
                " <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>";
        }
        // 这里可以将获取到的数据,显示到html页面上
        document.getElementById("brandTable").innerHTML = tableDates;
    });

</script>

</body>
</html>

效果如下
在这里插入图片描述

15、在我们先前已经建好的web目录建立BrandSelectAllServlet类

package com.web;

import com.alibaba.fastjson.JSON;

import com.pojo.Brand;
import com.service.BrandService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
// 这里的注解,是与前面建立的bran.html的发送请求相互联系的
@WebServlet("/brandSelectAllServlet")
public class BrandSelectAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // 获取数据
        List<Brand> brands = BrandService.BrandSelectAll();

        // 解决json数据的中文乱码
        resp.setContentType("text/json;charset=utf-8");
        // 转换json
        String toJSONString = JSON.toJSONString(brands);
        // 响应数据
        resp.getWriter().write(toJSONString);
    }

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

此时我们就完成了,数据的查询,相应到前端页面上。
效果如下:
在这里插入图片描述
此时运行项目后,回出现下面的效果

在这里插入图片描述
此时,可以说查询出数据库的内容,并响应给前端页面。

16、接下来,我们来实现点击新增跳转到新的页面去实现添加数据
在webapp目录下,建立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="提交">
</form>

<script src="js/axios-0.18.0.js"></script>
<script>
    // 1.给按钮添加一个点击事件
    document.getElementById("btn").onclick = function () {
        // 将表单数据转化为json数据
        let  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.getElementsByName("status")
        // 循环遍历
        for (let i = 0; i < status.length; i++) {
            if (status[i].checked) {
                formData.status = status[i].value;
            }
        }

        axios({
            method: "post",
            url: "http://localhost:8080/webDemo7/brandAddServlet",
            data:formData
        }).then(function (resp) {
            if (resp.data == "success") {
                // 跳转页面
                location.href = "http://localhost:8080/webDemo7/brand.html"

            }
        });
    };
</script>

</body>
</html>

效果:
在这里插入图片描述

17、下面,我们创建BrandAddServlet类,为addBrand.htm发送请求,进行处理
在这里插入图片描述
代码:

package com.web;

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

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/brandAddServlet")
public class BrandAddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 读取一行
        BufferedReader reader = req.getReader();
        String readLine = reader.readLine();
        System.out.println(readLine);

        // json转成java对象
        Brand brand = JSON.parseObject(readLine, Brand.class);
        System.out.println(brand);

        // 调用dao层
        int brandAdd = BrandService.BrandAdd(brand);
        if (brandAdd == 1) {
            resp.getWriter().write("success");
        }

    }

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

如果这一步也成功了,那么的加入数据也成功了
启动运行后,第一brand.html页面,成功查询出数据库里的所有内容
在这里插入图片描述
点击新增按钮
跳转页面,写入数据,提交
在这里插入图片描述

跳转到查询的页面,可以看到刚刚添加的数据
在这里插入图片描述

此时去数据库查看一下有没有这个数据,在这里,数据里也有相应的数据
在这里插入图片描述

最后的效果视频

2022/10/16作业实现前端和后端的数据交换的作业效果视频


.2

作业结束了。接下来,会实现,删除和修改的功能
😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄😄

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

偷偷不学习

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值