JavaWeb:servlet+MyBatis+ajax (商品管理系统)

文章目录

        • 1、开发环境
        • 2、环境准备
        • 3、功能实现
          • 3.1、查询所有
          • 3.2、增加数据

1、开发环境
  • IDEA
  • mysql8.0
  • ajax
  • servlet
2、环境准备

1、创建数据库

CREATE DATABASE ajax_test;
USE ajax_test;

-- 删除tb_brand表
DROP TABLE IF EXISTS tb_brand;
-- 创建tb_brand表
CREATE TABLE tb_brand
(
    -- id 主键
    id           INT PRIMARY KEY AUTO_INCREMENT,
    -- 品牌名称
    brand_name   VARCHAR(20),
    -- 企业名称
    company_name VARCHAR(20),
    -- 排序字段
    ordered      INT,
    -- 描述信息
    description  VARCHAR(100),
    -- 状态:0:禁用  1:启用
    STATUS       INT
);
-- 添加数据
INSERT INTO tb_brand (brand_name, company_name, ordered, description, STATUS)
VALUES ('三只松鼠', '三只松鼠股份有限公司', 5, '好吃不上火', 0),
       ('华为', '华为技术有限公司', 100, '华为致力于把数字世界带入每个人、每个家庭、每个组织,构建万物互联的智能世界', 1),
       ('小米', '小米科技有限公司', 50, 'are you ok', 1);


SELECT * FROM tb_brand;

SELECT id, brand_name AS brandName, company_name AS companyName FROM tb_brand;

2、创建web项目

3、pom.xml文件导入依赖

<dependencies>
    
    <dependency>
        <groupId>org.mybatisgroupId>
        <artifactId>mybatisartifactId>
        <version>3.5.5version>
    dependency>

    
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.46version>
    dependency>

    
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>javax.servlet-apiartifactId>
        <version>3.1.0version>
        <scope>providedscope>
    dependency>

    
    <dependency>
        <groupId>javax.servlet.jspgroupId>
        <artifactId>jsp-apiartifactId>
        <version>2.2version>
        <scope>providedscope>
    dependency>

    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>fastjsonartifactId>
        <version>1.2.58version>
    dependency>
dependencies>

4、编写mybatis配置文件

<?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>
    <settings>
        <!--在控制台显示SQL语句-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!--起别名-->
    <typeAliases>
        <package name="com.demo.pojo"/>
    </typeAliases>

    <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:///ajax_test?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--扫描mapper-->
        <package name="com.demo.mapper"/>
    </mappers>
</configuration>

5、创建项目结构导入js

JavaWeb:servlet+MyBatis+ajax (商品管理系统)_第1张图片

6、编写Mybatis工具类

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    // 我们只需要一个SqlSessionFactory,在静态代码块中创建SqlSessionFactory
    static {
        try {
            // 编写代码让MyBatis跑起来,执行SQL语句
            String resource = "mybatis-config.xml";
            // 加载核心配置文件
            InputStream inputStream = Resources.getResourceAsStream(resource);
            // 得到SqlSession工厂,赋值给成员变量
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 返回SqlSessionFactory
    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }

    // 返回SqlSession
    public static SqlSession openSession() {
        return sqlSessionFactory.openSession();
    }

    public static SqlSession openSession(boolean autoCommit) {
        return sqlSessionFactory.openSession(autoCommit);
    }
}

7、编写实体类

public class Brand {
    // id 主键
    private Integer id;
    // 品牌名称
    private String brandName;
    // 企业名称
    private String companyName;
    // 排序字段
    private Integer ordered;
    // 描述信息
    private String description;
    // 状态:0:禁用  1:启用
    private Integer status;
    ....省略方法
}
3、功能实现
3.1、查询所有

JavaWeb:servlet+MyBatis+ajax (商品管理系统)_第2张图片

代码实现

1、在mapper包下编写BrandMapper接口,编写查询所有方法

public interface BrandMapper {
    @Select("select * from tb_brand;")
    List<Brand> selectAllBrand();
}

2、在service包下创建BrandService类

public class BrandService {
    public List<Brand> selectAllBrand() {
        SqlSession sqlSession = MyBatisUtils.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        List<Brand> listBrand = mapper.selectAllBrand();
        return listBrand;
    }
}

3、在web包下编写SeleAllServlet

@WebServlet(value = "/selectAllServlet")
public class SelectAllServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1、调用查询
        BrandService brandService = new BrandService();
        List<Brand> brands = brandService.selectAllBrand();

        // 2、将集合转化为JSON数据
        String jsonString = JSON.toJSONString(brands);

        // 3、响应JSON数据
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(jsonString);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        doGet(request,response);
    }
}

4、编写前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>所有品牌</title>
    <script src="js/axios-0.18.0.js"></script>
</head>
<body>
<a href="addBrand.html"><input type="button" value="新增"></a>
<input type="button" value="获取所有品牌" onclick="ajaxGetAllBrand()"><br>
<hr>
<table id="brandTable" border="1" cellspacing="0" width="800">
    <thead>
        <tr>
            <th>序号</th>
            <th>品牌名称</th>
            <th>企业名称</th>
            <th>排序</th>
            <th>品牌介绍</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
    </thead>

    <tbody id="tableBody">
    </tbody>
</table>

<script>
    function ajaxGetAllBrand() {
        axios.get("selectAllServlet").then(
            resp=>{
                //获取响应
                let data = resp.data;
                let str = ""
                for (let datum of data) {
                    str+=`<tr align="center">
         <td>${datum.id}</td>
        <td>${datum.brandName}</td>
        <td>${datum.companyName}</td>
        <td>${datum.ordered}</td>
        <td>${datum.description}</td>
        <td>${datum.status}</td>
        <td><a href="#">修改</a> <a href="#">删除</a></td>
    </tr>`
                }
                
                document.getElementById("tableBody").innerHTML=str;
            }
        )
    }
</script>
</body>
</html>
3.2、增加数据

1、编写前端代码

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>添加品牌title>
    <script src="js/axios-0.18.0.js">script>
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" checked="checked">禁用
    <input type="radio" name="status" value="1" c>启用<br>

    <input id="btn" type="button" value="提交" onclick="ajaxPost()"><br/>
    <span id="msg" style="color: red">span>
form>

<script>
    function ajaxPost() {
        let brandJS = {
            brandName:"",
            companyName:"",
            ordered:0,
            description:"",
            status:0
        }

        brandJS.brandName = document.getElementById("brandName").value.trim();
        brandJS.companyName = document.getElementById("companyName").value.trim();
        brandJS.ordered = document.getElementById("ordered").value.trim();
        brandJS.description = document.getElementById("description").value.trim();

        let radioByName = document.getElementsByName("status");
        for (let rad of radioByName) {
            let checked = rad.checked;
            if (checked){
                brandJS.status = rad.value;
            }
        }
        console.log(brandJS)

        axios.post("addServlet",brandJS).then(
            resp=>{
                document.getElementById("msg").innerHTML = resp.data;
            }
        )
    }
script>

body>
html>

2、编写AddServlet

@WebServlet(value = "/addServlet")
public class AddServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、获取数据
        String brandJS = request.getReader().readLine();
        // 2、转化成java对象
        Brand brand = JSON.parseObject(brandJS, Brand.class);

        // 3、调用方法
        BrandService brandService = new BrandService();
        brandService.addBrand(brand);

        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write("添加数据成功");

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        doGet(request,response);
    }
}

3、编写BrandService添加方法

public void addBrand(Brand brand) {
    SqlSession sqlSession = MyBatisUtils.openSession();

    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

    mapper.addBrand(brand);

    sqlSession.commit();

    sqlSession.close();

}

4、接口添加方法

@Insert("insert into tb_brand values (null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
void addBrand(Brand brand);

你可能感兴趣的:(java,ajax,servlet,mybatis)