首页 前端知识 基于javaweb jquery axios前后端分离实现增删改查

基于javaweb jquery axios前后端分离实现增删改查

2024-04-01 10:04:50 前端知识 前端哥 786 442 我要收藏

新建javaweb项目,在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>javaweb</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.24</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-core</artifactId>
            <version>9.0.37</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
    </dependencies>
</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.sjm.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://localhost:3306/gk2022?useUnicode=true&amp;allowPublicKeyRetrieval=true&amp;characterEncoding=utf-8&amp;serverTimezone=GMT&amp;useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers> <!--加载sql映射文件-->
        <!--        <mapper resource="com/zr/mapper/UserMapper.xml"/>-->
        <!--        包扫描-->
        <package name="com.sjm.mapper"/>
    </mappers>
</configuration>


因为使用代理的原因下面的路径要一致,否则会报错
在这里插入图片描述
BrandMapper.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">
<mapper namespace="com.sjm.mapper.BrandMapper">

    <select id="selectAll" resultType="com.sjm.pojo.Brand">
    select * from brand
    </select>
</mapper>

com.sjm.mapper下新建接口BrandMapper

package com.sjm.mapper;

import com.sjm.pojo.Brand;
import com.sjm.pojo.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface BrandMapper {
    //查询所有

    List<Brand> selectAll();

    //添加
    @Insert("insert into brand values(null,#{brandName},#{companyName},#{ordered},#{description},#{status})")
    int add(Brand brand);

    //根据id查询
    @Select("select * from brand where id=#{id}")
    Brand selectById(int id);

    //修改
    @Update("update brand set brandName=#{brandName},companyName=#{companyName},ordered=#{ordered},description=#{description},status=#{status} where id=#{id}")
    int update(Brand brand);

//    删除
    @Delete("delete from brand where id=#{id}")
    int deleteById(int id);
}

工具类

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;
    }
}

BrandService类

package com.sjm.service;

import com.sjm.mapper.BrandMapper;
import com.sjm.pojo.Brand;
import com.sjm.pojo.User;
import com.sjm.utils.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /*** 查询所有 * @return */
    public List<Brand> selectAll() {
//        调用   BrandMapper.selectAll()
//         2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
//         3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
//         4. 调用方法
        List<Brand> usersList = mapper.selectAll();
        sqlSession.close();
        return usersList;
    }

    //添加
    public int add(Brand brand) {
// 2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
// 3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
// 4. 调用方法
        int i = mapper.add(brand);
// 提交事务
        sqlSession.commit();
// 释放资源
        sqlSession.close();
        return i;
    }


    //根据id查询
    public Brand selectById(int id) {
        // 调用BrandMapper.selectAll()
        // 2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        // 3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        // 4. 调用方法
        Brand brand = mapper.selectById(id);
        sqlSession.close();
        return brand;
    }

    //修改
    public int update(Brand brand) {
        // 2. 获取SqlSession
        SqlSession sqlSession = factory.openSession();
        // 3. 获取BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        // 4. 调用方法
        int update = mapper.update(brand);
        // 提交事务
        sqlSession.commit();
        // 释放资源
        sqlSession.close();
        return update;
    }

//    删除
public int delete(int id) {
    // 2. 获取SqlSession
    SqlSession sqlSession = factory.openSession();
    // 3. 获取BrandMapper
    BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
    // 4. 调用方法
    int i = mapper.deleteById(id);
    // 提交事务
    sqlSession.commit();
    // 释放资源
    sqlSession.close();

    return i;
}

}

实体类

@Data
public class Brand {
    private Integer id;
//     品牌名称
    private String brandName;
     // 企业名称

    private String companyName;
//     排序字段
    private Integer ordered;
//     描述信息
    private String description;
     // 状态:0:禁用 1:启用
     private Integer status;
     public Brand(){

     }
}

配置过滤器

package com.sjm.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.io.IOException;
@WebFilter("/*")
public class FilterA implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        Object user_session = session.getAttribute("USER_SESSION");
        //判断访问资源路径是否和登录注册相关
        //1,在数组中存储登陆和注册相关的资源路径
        String[] urls =
                {"/login.jsp","/register.jsp","/imgs","/css/",
                        "/login","/register","/loginOut","/AjaxTest","/index.html","/allBrand","/addBrand","/delete","/selectById","/update"};
        String url= req.getRequestURI();
        for (String u:urls
             ) {
            if(url.contains(u)){
                //找到了,放行
                chain.doFilter(request, response);
//                break;
                return;
            }
        }
        if(user_session != null){
            //放行
            chain.doFilter(request,response);
        }else {
            req.getRequestDispatcher("/login.jsp").forward(req, response);
        }
    }

    @Override
    public void destroy() {

    }
}

处理跨域问题


@WebFilter(filterName = "CorsFilter",value = "/*")
public class CorsFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletResponse response1= (HttpServletResponse) response;
        response1.setHeader("Access-Control-Allow-Origin", "*");
        response1.setHeader("Access-Control-Allow-Headers", "*");

        chain.doFilter(request, response);
    }
}

在web.xml中配置

<welcome-file-list>
    <welcome-file>/login.jsp</welcome-file>
</welcome-file-list>
    <!--跨域过滤器-->
    <filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.sjm.filter.CorsFilter</filter-class>
        <init-param>
            <param-name>cors.allowOrigin</param-name>
            <param-value>*</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedMethods</param-name>
            <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportedHeaders</param-name>
            <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
        </init-param>
        <init-param>
            <param-name>cors.exposedHeaders</param-name>
            <param-value>Set-Cookie</param-value>
        </init-param>
        <init-param>
            <param-name>cors.supportsCredentials</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

添加接口

@WebServlet("/addBrand")
public class addController extends HttpServlet {
    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 调用BrandService完成查询
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/json;charset=utf-8");
        BufferedReader reader = request.getReader();
        String brand_string = reader.readLine();
        System.out.println(brand_string);
        if (brand_string != null){
            // 将JSON字符串转为Java对象
            Brand brand = JSON.parseObject(brand_string, Brand.class);
//            System.out.println(brand);
            int add = service.add(brand);
            if (add > 0) {
                response.getWriter().write(JSON.toJSONString("success"));
            } else {
                response.getWriter().write(JSON.toJSONString("fail"));
            }
        }else {
            response.getWriter().write(JSON.toJSONString("fail"));
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request, response);
    }
}

删除接口


@WebServlet("/delete")
public class DeleteServlet extends HttpServlet {

    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException {
        //处理POST请求的乱码问题

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/json;charset=utf-8");
        // 1. 接收表单提交的数据,封装为一个Brand对象
        String id = request.getParameter("id");
        Map<String, Object> map = new HashMap<>();
//         2. 调用service 完成删除
        int delete = service.delete(Integer.parseInt(id));
        if (delete > 0) {
            map.put("status",200);
            map.put("msg", "delete success");
        } else {
            map.put("status",201);
            map.put("msg", "delete fail");
        }
        response.getWriter().write(JSON.toJSONString(map));
    }

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

查询所有接口

@WebServlet("/allBrand")
public class selectAllBrand extends HttpServlet {
    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 调用BrandService完成查询
        response.setContentType("text/html;charset=utf-8");
        List<Brand> brandList = service.selectAll();
        System.out.println(brandList);
        response.getWriter().write(JSON.toJSONString(brandList));

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request, response);
    }
}

根据Id查询


@WebServlet("/selectById")
public class SelectByIdServlet extends HttpServlet {
    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException {
        //1. 接收id
        String id = request.getParameter("id");
        response.setContentType("text/html;charset=utf-8");
        // 2. 调用service查询
        Brand brand = service.selectById(Integer.parseInt(id));
        response.getWriter().write(JSON.toJSONString(brand));
    }

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

更新记录接口


@WebServlet("/update")
public class updateServlet extends HttpServlet {
    private BrandService service = new BrandService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 调用BrandService完成查询
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/json;charset=utf-8");
        BufferedReader reader = request.getReader();
        String brand_string = reader.readLine();
        System.out.println(brand_string);
        if (brand_string != null){
            // 将JSON字符串转为Java对象
            Brand brand = JSON.parseObject(brand_string, Brand.class);

            int up = service.update(brand);
            if (up > 0) {
                response.getWriter().write(JSON.toJSONString("success"));
            } else {
                response.getWriter().write(JSON.toJSONString("fail"));
            }
        }else {
            response.getWriter().write(JSON.toJSONString("fail"));
        }


    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        this.doGet(request, response);
    }
}

前端页面使用了axios+jquery(自行下载)

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./axios-0.18.0.js"></script>
    <script src="./jquery.min.js"></script>
    <style>
        #addDiv {
            text-align: center;
            display: none;
            margin: 0 auto;
            width: 400px;
            height: 400px;
            background: rgb(34, 227, 179);
        }

        .updateDiv {
            text-align: center;
            display: none;
            margin: 0 auto;
            width: 400px;
            height: 400px;
            background: rgb(34, 227, 179);
        }
    </style>
</head>

<body>
    <input type="button" onclick="switchDiv(1)" value="新增">
    <br>
    <!-- 查询所有 -->
    <table id="brandTable" border="1" cellspacing="0" width="100%"></table>
    <div id="addDiv">
        <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" id="status">禁用
            <input type="radio" name="status" value="1" id="status">启用<br>
            <input type="button" id="addbtn" value="提交">
            <!-- <input type="button" onclick="switchDiv(0)"  value="取消"> -->
        </form>
    </div>
    <div class="updateDiv">
        <h3>修改品牌</h3>
        <form action="" id="updateForm" method="post">
            <input type="hidden" class="id" name="id">
            品牌名称:<input class="brandName" name="brandName"><br>
            企业名称:<input class="companyName" name="companyName"><br>
            排序:<input class="ordered" name="ordered"><br>
            描述信息:<textarea rows="5" cols="20" class="description" name="description"></textarea><br>
            状态:
            <input type="radio" name="status" value="0" class="status">禁用
            <input type="radio" name="status" value="1" class="status">启用<br>
            <input type="button" class="up" onclick="updateBrand()" value="提交">
            <input type="button" class="rem" id="rmupdate" value="取消">
        </form>
    </div>
    <script>
        const userList = () => {
            axios({
                method: "get",
                url: "http://localhost:8080/allBrand"
            }).then(function (msg) {
                //获取数据
                let brands = msg.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><button οnclick=" + 'selectById(' + brand.id + ')' + " >修改</button> <button  οnclick=" + 'deleteBrand(' + brand.id + ')' + ">删除</button></td>\n" +
                        " </tr>";

                }
                // 设置表格数据
                document.getElementById("brandTable").innerHTML = tableData;
            })
        }
        userList()



        // 添加
        $('#addbtn').click(function () {
            // 提交添加表单
            addBrands();
            $("#addDiv").hide();
            $("#btn").show();
            $("table").show();
            // switchDiv(2);
            userList();

        })
        const addBrands = () => {
            var formData = {};
            formData.brandName = $("#brandName").val();
            formData.companyName = $("#companyName").val();
            formData.ordered = $("#ordered").val();
            formData.description = $("#description").val();
            formData.status = $("#status:checked").val();
            axios({
                method: "post",
                url: "http://localhost:8080/addBrand",
                data: JSON.stringify(formData)
            }).then(function (res) {
                if (res.status == 200) {
                    alert(res.data);
                    userList();
                } else {
                    alert(res.data)
                }
            })
        }

        // 删除
        const deleteBrand = (id) => {

            axios({
                method: "get",
                url: "http://localhost:8080/delete?id=" + id
            }).then(function (res) {
                if (res.data.status == 200) {
                    alert(res.data.msg);
                    // switchDiv(2)
                    userList();
                } else if (res.data.status == 201) {
                    alert(res.data.msg);
                }
            })
        }
        $(".rem").click(function(){
            $(".updateDiv").hide();
                $("table").show();
        })
        // 修改
        const updateBrand = () => {
                $(".updateDiv").hide();
                $("table").show();
            // 获取表单的值
            let updateForm = {};
            updateForm.id = $(".id").val();
            updateForm.brandName = $(".brandName").val();
            updateForm.companyName = $(".companyName").val();
            updateForm.ordered = $(".ordered").val();
            updateForm.description = $(".description").val();
            updateForm.status = $(".status:checked").val();
            axios({
                method: "post",
                url: "http://localhost:8080/update",
                data: JSON.stringify(updateForm)
            }).then(function (res) {
                if (res.status == 200) {
                    alert(res.data);
                    userList();
                } else {
                    alert(res.data)
                }
            })
        }

// 根据ID查询
        const selectById = (id) => {
            switchDiv(3)
            axios({
                method: "get",
                url: "http://localhost:8080/selectById?id=" + id
            }).then(function (res) {
                //    表单赋值
                var brand = res.data
                $('#updateForm').find('input[name="id"]').val(brand.id);
                $('#updateForm').find('input[name="brandName"]').val(brand.brandName);
                $('#updateForm').find('input[name="companyName"]').val(brand.companyName);
                $('#updateForm').find('input[name="ordered"]').val(brand.ordered);
                $('#updateForm').find('textarea[name="description"]').val(brand.description);
                $('#updateForm').find('input[name="status"][value="' + brand.status + '"]').attr('checked', 'checked')
            })

        }

        //切换
        function switchDiv(part) {
            //隐藏内容
            $('#addDiv').css("display", "none")
            $('#brandTable').css("display", "none")
            $('#btn').css("display", "none")
            $('.updateDiv').css("display", "none")
            if (1 == part) {//添加页面
                $('#addDiv').css("display", "block")
            } else if (2 == part) {//列表页面
                $('#brandTable').css("display", "block")
            } else if (3 == part) {//编辑页面
                $('.updateDiv').css("display", "block")
            }
        }
    </script>
</body>

</html>

最终效果
在这里插入图片描述
添加
在这里插入图片描述
修改
在这里插入图片描述
删除
在这里插入图片描述

转载请注明出处或者链接地址:https://www.qianduange.cn//article/4390.html
标签
servlet
评论
发布的文章

前端vue实现甘特图

2024-04-19 21:04:35

HTML入门(详细)

2024-04-19 21:04:24

HTML 入门手册(一)

2024-04-19 21:04:58

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!