(0基础保姆教程)-JavaEE开课啦!--11课程(初识Spring MVC + Vue2.0 + Mybatis)-实验9

一、什么是Spring MVC?

        Spring MVC 是一个基于 Java 的 Web 框架,遵循 MVC 设计模式,用于构建企业级应用程序。它通过控制器(Controller)处理用户请求,模型(Model)处理业务逻辑,视图(View)展示数据,实现了请求的分发、数据绑定、视图解析、异常处理等功能,并支持多种视图技术,以提高开发效率和代码的可维护性。

二、Spring MVC有哪些优点呢?

1. 无缝集成:与 Spring 生态系统紧密集成。
2. 灵活性:支持多种配置方式和视图技术。
3. 易于测试:控制器易于进行单元测试。
4. 数据绑定和验证:提供自动数据绑定和验证功能。
5. 拦截器和过滤器:支持拦截器和过滤器以扩展功能。
6. 国际化支持:简化多语言界面的开发。
7. 社区支持:拥有庞大的开发者社区和资源。
8. 可定制性:高度可定制以满足不同项目需求。

三、准备第一个Spring MVC项目

Example:

        编写客户信息(客户名称、客户单位、客户职位、客户生日、客户性别、客户联系方式)注册页面addcustom.jsp。要求:

        1.利用Mybatis框架将客户信息保存到数据库中;

        2.能够利用SpringMVC控制器将页面切换到该注册页面。

流程:

1.创建MySQL数据表customlist

2.创建SpringMvc项目,在pom文件引入相关依赖

3.创建spring-mvc.xml配置文件

4.创建web.xml配置文件

5.创建Entity-Custom客户实体类

6.创建db.properties/mybatis-config.xml配置文件

7.创建Mapper-CustomListMapper配置文件

8.创建applicationContext.xml配置文件

9.引入Vue2.0和Element-ui框架

10.创建Pages-customIndex.jsp和addcustom.jsp前端映射文件

11.创建controller-CustomController文件

12.配置tomcat服务器,运行项目

四、开始上操作

1.创建MySQL数据表customlist

SET NAMES utf8mb4;

SET FOREIGN_KEY_CHECKS = 0;



-- ----------------------------

-- Table structure for customlist

-- ----------------------------

DROP TABLE IF EXISTS `customlist`;

CREATE TABLE `customlist`  (

  `id` int NOT NULL AUTO_INCREMENT,

  `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,

  `company` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,

  `role` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,

  `birthday` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,

  `gender` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,

  `tel` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,

  PRIMARY KEY (`id`) USING BTREE

) ENGINE = InnoDB AUTO_INCREMENT = 11 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

2.创建SpringMvc项目,在pom文件引入相关依赖

项目结构:

 打开IDEA,创建项目-Maven Archetype-名称-位置-JDK-Archetype-创建

点击创建后需要等待较长时间构建项目,完成加载和构建后,会显示以下界面:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.ljl</groupId>
  <artifactId>Spring_MVC_class9</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Spring_MVC_class9 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!--    Spring 基础配置-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.3.10</version>
    </dependency>
    <!--    SpringMVC工具插件-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.3.10</version>
    </dependency>
    <!--    servlet插件-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.1</version>
    </dependency>

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.32</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.11</version>
    </dependency>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>RELEASE</version>
      <scope>compile</scope>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.15.4</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.15.4</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>Spring_MVC_class9</finalName>
  </build>
</project>

3.创建spring-mvc.xml配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <mvc:annotation-driven/>
    <context:component-scan base-package="com.ljl.controller"/>
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
<!--    配置视图解释器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

4.创建web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

  <servlet>
    <servlet-name>DispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>DispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>


  <filter>
    <filter-name>chinese_encoder</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>chinese_encoder</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

5.创建Entity-Custom客户实体类

package com.ljl.Entity;

public class Custom {
    private int id;
    private String name;
    private String company;
    private String role;
    private String birthday;
    private String gender;
    private String tel;

    public Custom() {
    }

    public Custom(int id, String name, String company, String role, String birthday, String gender, String tel) {
        this.id = id;
        this.name = name;
        this.company = company;
        this.role = role;
        this.birthday = birthday;
        this.gender = gender;
        this.tel = tel;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    @Override
    public String toString() {
        return "Custom{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", company='" + company + '\'' +
                ", role='" + role + '\'' +
                ", birthday='" + birthday + '\'' +
                ", gender='" + gender + '\'' +
                ", tel='" + tel + '\'' +
                '}';
    }
}

6.创建db.properties/mybatis-config.xml配置文件

mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/class9_springmvc?serverTimezone=UTC&\characterEncoding=utf-8&useUnicode=true&useSSl=false
mysql.username=root
mysql.password=pjl2003
<?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>
    <properties resource="db.properties"/>
<!--    设置实体别名-->
    <typeAliases>
        <package name="com.ljl.Entity"/>
    </typeAliases>
    <!-- 和spring整合后 environments配置将废除-->
    <environments default="development">
        <environment id="development">
            <!-- 使用jdbc事务管理-->
            <transactionManager type="JDBC" />
            <!-- 数据库连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${mysql.driver}" />
                <property name="url" value="${mysql.url}" />
<!--                //数据库账号-->
                <property name="username" value="${mysql.username}" />
<!--                //数据库密码-->
                <property name="password" value="${mysql.password}" />
            </dataSource>
        </environment>
    </environments>
    <!--声明类对应的sql操作文件-->
    <mappers>
        <mapper class="com.ljl.Mapper.CustomListMapper"/>
    </mappers>
</configuration>


7.创建Mapper-CustomListMapper配置文件

package com.ljl.Mapper;


import com.ljl.Entity.Custom;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface CustomListMapper {

    //TODO 增加客户信息
    @Insert("INSERT INTO customlist (name, company, role, birthday, gender, tel) values (#{name}, #{company}, #{role}, #{birthday}, #{gender}, #{tel})")
    int insertCustom(Custom custom);

    //TODO 查询客户信息-全部
    @Select("SELECT * FROM customlist")
    List<Custom> getAllCustomList();

    //TODO 查询订单信息-根据客户名称模糊查询
    @Select("SELECT * FROM customlist WHERE name LIKE CONCAT('%', #{name}, '%')")
    List<Custom> getOrderListByLikeCustomName(String name);

    //TODO 查询订单信息-根据客户名称详细查询
    @Select("SELECT * FROM customlist WHERE name = #{name}")
    List<Custom> getOrderListByCustomName(String name);
}

8.创建applicationContext.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

<!--    自动装配Bean-->
    <context:component-scan base-package="com.ljl.controller"/>
</beans>

9.引入Vue2.0和Element-ui框架

<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">

<!-- import Vue before Element -->
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>

10.创建index.jsp \ Pages-customIndex.jsp和addcustom.jsp前端映射文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>CustomWelcome</title>
    <!-- import CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="index" class="big_box">
    <H1 class="tittle">欢迎使用{{ sys_name }}客户管理系统</H1>
    <el-row>
        <el-button type="primary" round style="width: 14%" @click="gosystem">开始使用</el-button>
    </el-row>
</div>

</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
    new Vue({
        el: '#index',
        data: function() {
            return {
                sys_name:"岚精灵"
            }

        },
        methods: {
            gosystem(){
                this.$message.success("欢迎使用岚精灵员工系统!");
                // 跳转到指定的URL
                // 设置延迟1秒后跳转
                setTimeout(() => {
                    window.location.href = 'http://localhost:8090/Spring_MVC_class9_war_exploded/customIndex';
                }, 1000); // 1000毫秒等于1秒
            }
        }
    })
</script>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    body {
        background-color: rebeccapurple;
    }
    .big_box{
        width: 100%;
        text-align: center;
        margin: 0 auto;
    }
    .tittle{
        margin-top: 250px;
        font-size: 55px;
        color: beige;
        margin-bottom: 170px;
    }
</style>
</html>
<%--
  Created by IntelliJ IDEA.
  User: 26520
  Date: 2024/11/21
  Time: 13:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>customSystem</title>
    <!-- import CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="cindex" class="cindex">
<%--    搜索框--%>
    <div style="margin-bottom: 40px;">
<%--        这里的键盘事件,由于使用了Element-ui,需要加上.native进行限制,因为在Element-ui中对active进行了封装,需要加上native进行限制--%>
        <el-input placeholder="请输入客户名称" v-model="search" class="input-with-select" @keyup.enter.native="search_ks">
            <el-select v-model="select" slot="prepend" placeholder="请选择">
                <el-option label="模糊查询" value="1"></el-option>
                <el-option label="准确查询" value="2"></el-option>
            </el-select>
            <el-button @click="search_ks" slot="append" icon="el-icon-search"  @keyup.enter.native="search_ks"></el-button>
        </el-input>
    </div>
<%--    内容展示框--%>
    <el-table height="550" :data="tableData" style="width: 100%; text-align: center" :row-class-name="tableRowClassName">
        <el-table-column
                prop="id"
                label="id">
        </el-table-column>
        <el-table-column
                prop="name"
                label="客户名称">
        </el-table-column>
        <el-table-column
                prop="company"
                label="客户单位">
        </el-table-column>
        <el-table-column
                prop="role"
                label="客户职位">
        </el-table-column>
        <el-table-column
                prop="birthday"
                label="客户生日">
        </el-table-column>
        <el-table-column
                prop="gender"
                label="客户性别">
        </el-table-column>
        <el-table-column
                prop="tel"
                label="联系方式">
        </el-table-column>
    </el-table>
    <div class="dibu_button">
        <el-row style="display: inline-block">
            <el-button type="primary" plain @click="addcustom">添加客户</el-button>
        </el-row>
        <el-row style="display: inline-block; margin-left: 30px">
            <el-button type="info" plain @click="go_out">退出系统</el-button>
        </el-row>
    </div>

</div>

</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
    new Vue({
        el: '#cindex',
        data: function() {
            return {
                search: '',
                // 这里默认情况下是模糊查询
                select: '1',
                tableData: []
            }

        },
        methods: {
            handleEdit(index, row) {
                console.log(index, row);
            },
            handleDelete(index, row) {
                console.log(index, row);
            },
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },
            addcustom(){
                this.$message.warning("加载中!");
                // 跳转到指定的URL
                setTimeout(() => {
                    window.location.href = 'http://localhost:8090/Spring_MVC_class9_war_exploded/goaddcustom';
                }, 300);
            },
            fetchData() {
                fetch('http://localhost:8090/Spring_MVC_class9_war_exploded/selectAllCustomList', {
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('Network response was not ok ' + response.statusText);
                        }
                        return response.json();
                    })
                    .then(data => {
                        this.tableData = data;
                    })
                    .catch(error => {
                        console.error('There has been a problem with your fetch operation:', error);
                    });
            },
            search_ks(){
                // 实现点击查询功能,先判断是模糊查询还是准确查询,查询出来的数据保存在tableData[]中
                //模糊查询
                if (this.search === ""){
                    this.$message.error("请输入需要查询的客户姓名!")
                }else {
                    if (this.select === "1"){
                        fetch('http://localhost:8090/Spring_MVC_class9_war_exploded/selectCustomLikeName?CustomName=' + this.search, {
                            method: 'POST', // 设置请求方法为 POST
                            headers: {
                                'Accept': 'application/json'
                            }
                        })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error('Network response was not ok ' + response.statusText);
                                }
                                return response.json();
                            })
                            .then(data => {
                                this.$message.success("查询成功!")
                                this.tableData = data;
                            })
                            .catch(error => {
                                console.error('There has been a problem with your fetch operation:', error);
                            });
                    }else if (this.select === "2") {
                        fetch('http://localhost:8090/Spring_MVC_class9_war_exploded/selectCustomByName?CustomName=' + this.search, {
                            method: 'POST', // 设置请求方法为 POST
                            headers: {
                                'Accept': 'application/json'
                            }
                        })
                            .then(response => {
                                if (!response.ok) {
                                    throw new Error('Network response was not ok ' + response.statusText);
                                }
                                return response.json();
                            })
                            .then(data => {
                                this.$message.success("查询成功!")
                                this.tableData = data;
                            })
                            .catch(error => {
                                console.error('There has been a problem with your fetch operation:', error);
                            });
                    }
                }
            },
            go_out(){
                this.$message.success("退出成功!")
                setTimeout(() => {
                    window.location.href = 'http://localhost:8090/Spring_MVC_class9_war_exploded/';
                }, 300);
            }
        },
        created() {
            this.fetchData(); // 当组件创建后调用 fetchData 方法
        },
    })
</script>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    body {
        background-color: #eaddf6;
    }
    .cindex{
        width: 70%;
        padding-top: 100px;
        text-align: center;
        margin: 0 auto;
    }
    .el-select .el-input {
        width: 130px;
    }
    .input-with-select .el-input-group__prepend {
        background-color: #fff;
    }
    .el-table .warning-row {
        background: oldlace;
    }

    .el-table .success-row {
        background: #f0f9eb;
    }
    .dibu_button{
        width: 100%;
        margin: 0 auto;
        margin-top: 30px;
        text-align: center;
    }
</style>
</html>
<%--
  Created by IntelliJ IDEA.
  User: 26520
  Date: 2024/11/21
  Time: 13:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>customSystem</title>
    <!-- import CSS -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
<div id="addcustom" class="big">
    <div class="from">
        <h1 style="text-align: center;color: #9438ec;font-size: 35px;margin-bottom: 40px;margin-top: 40px">添加客户</h1>
        <el-form ref="form" :model="form" :label-position="right" label-width="80px" action="">
            <el-form-item label="姓名">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="单位">
                <el-input v-model="form.company"></el-input>
            </el-form-item>
            <el-form-item label="职位">
                <el-input v-model="form.role"></el-input>
            </el-form-item>
            <el-form-item label="生日">
                <el-date-picker
                        v-model="form.birthday"
                        type="date"
                        style="width: 100%"
                        placeholder="选择日期">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="性别">
                <el-select style="width: 100%" v-model="form.gender" placeholder="请选择">
                    <el-option
                            v-for="item in genderchange"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="电话">
                <el-input v-model="form.tel"></el-input>
            </el-form-item>



            <el-button type="primary" @click="add">立即创建</el-button>
            <el-button type="danger" @click="back" style="margin-bottom: 40px">立即返回</el-button>
        </el-form>
    </div>

</div>

</body>
<!-- import Vue before Element -->
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
<!-- import JavaScript -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
    new Vue({
        el: '#addcustom',
        data: function() {
            return {
                form: {
                    name: '',
                    company:"",
                    role:"",
                    birthday:"",
                    gender:"",
                    tel:""
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                        },
                },
                genderchange: [{
                    value: '男',
                    label: '男'
                }, {
                    value: '女',
                    label: '女'
                }, {
                    value: '其他',
                    label: '其他'
                }],
            }

        },
        methods: {
            checkForm() {
                let allFilled = true;
                for (let key in this.form) {
                    if (!this.form[key] && this.form[key] !== 0) { // 假设0是一个有效的值
                        allFilled = false;
                        break;
                    }
                }
                return allFilled;
            },
            add(){
                if (!this.checkForm()) {
                    this.$message.error("请填写所有必填字段");
                    return;
                }
                // 格式化生日日期为 yyyy-mm-dd
                this.form.birthday = this.form.birthday ? this.form.birthday.toISOString().split('T')[0] : '';

                // 创建URLSearchParams对象并添加数据
                const params = new URLSearchParams();
                params.append('name', this.form.name);
                params.append('company', this.form.company);
                params.append('role', this.form.role);
                params.append('birthday', this.form.birthday);
                params.append('gender', this.form.gender);
                params.append('tel', this.form.tel);

                // 发送POST请求
                fetch('http://localhost:8090/Spring_MVC_class9_war_exploded/addcustom', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                    },
                    body: params // URLSearchParams对象会自动转换为URL编码的字符串
                })
                    .then(response => {
                        if (response.ok) {
                            return response.text(); // 或者 response.json() 如果响应是JSON格式
                        }
                        throw new Error('Network response was not ok.');
                    })
                    .then(data => {
                        console.log(data);
                        this.$message.success("数据添加成功!");
                        setTimeout(() => {
                            window.location.href = 'http://localhost:8090/Spring_MVC_class9_war_exploded/';
                        }, 300); // 1000毫秒等于1秒
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        this.$message.error("数据添加失败!");
                    });
            },
            back(){
                this.$message.warning("请稍等!");
                // 跳转到指定的URL
                // 设置延迟1秒后跳转
                setTimeout(() => {
                    window.location.href = 'http://localhost:8090/Spring_MVC_class9_war_exploded/customIndex';
                }, 300); // 1000毫秒等于1秒
            }
        }
    })
</script>
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .big{
        width: 70%;
        padding-top: 100px;
        text-align: center;
        margin: 0 auto;
    }
    .from{
        width: 40%;
        padding-right: 40px;
        text-align: center;
        margin: 0 auto;
        border: 1px solid grey;
        border-radius: 8px;
    }
</style>
</html>

11.创建controller-CustomController文件

package com.ljl.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.ljl.Entity.Custom;
import com.ljl.Mapper.CustomListMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Controller
@CrossOrigin(origins = "*")
public class CustomController {


    //主页
    @RequestMapping("/customIndex")
    public String customIndex() {
        return "customIndex";
    }
    //添加客户界面
    @RequestMapping("/goaddcustom")
    public String goaddcustom() {
        return "addcustom";
    }
    //添加客户到sql,再返回到主页
    @RequestMapping("/addcustom")
    public String addcustom(Custom custom) {
        if (custom.getName() != null) {
            SqlSessionFactory ssf = null;
            try {
                InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
                ssf = new SqlSessionFactoryBuilder().build(input);
            } catch (IOException e) {
                e.printStackTrace();
            }
            SqlSession sqlSession = ssf.openSession();
            CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
            int result_code = customListMapper.insertCustom(custom);
            sqlSession.commit();
            if (result_code == 1) {
                System.out.println("新增客户成功!");
            }else {
                System.out.println("新增客户失败!");
            }
        }
        return "customIndex";
    }

    //获取全部客户信息
    @GetMapping(value = "selectAllCustomList", produces = "application/json")
    @ResponseBody
    public List<Custom> selectAllCustomList() {
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
        List<Custom> custom = customListMapper.getAllCustomList();
        System.out.println("系统正在获取所有客户信息");
        return custom;
    }

    //模糊查询客户信息-根据name模糊查询
    @PostMapping(value = "selectCustomLikeName", produces = "application/json")
    @ResponseBody
    public List<Custom> selectCustomLikeName(HttpServletRequest request){
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
        List<Custom> custom = customListMapper.getOrderListByLikeCustomName(request.getParameter("CustomName"));
        System.out.println("用户正在进行模糊查询");
        return custom;
    }


    //准确查询客户信息-根据name准确查询
    @PostMapping(value = "selectCustomByName", produces = "application/json")
    @ResponseBody
    public List<Custom> selectCustomByName(HttpServletRequest request){
        SqlSessionFactory ssf = null;
        try {
            InputStream input = Resources.getResourceAsStream("mybatis-config.xml");
            ssf = new SqlSessionFactoryBuilder().build(input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSession sqlSession = ssf.openSession();
        CustomListMapper customListMapper = sqlSession.getMapper(CustomListMapper.class);
        List<Custom> custom = customListMapper.getOrderListByCustomName(request.getParameter("CustomName"));
        System.out.println("用户正在进行精确查询");
        return custom;
    }
}

12.配置tomcat服务器,运行项目

五、运行看效果

1.初始加载页面

2.进入系统主界面

3.模糊查询

4.精确查询

5.注册界面

6.注册成功返回主界面

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/925228.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

FCBP 认证考试要点摘要

理论知识 数据处理与分析&#xff1a;包括数据的收集、清洗、转换、存储等基础操作&#xff0c;以及数据分析方法&#xff0c;如描述性统计分析、相关性分析、数据挖掘算法等的理解和应用 。数据可视化&#xff1a;涉及图表类型的选择与应用&#xff0c;如柱状图、折线图、饼图…

「Qt Widget中文示例指南」如何为窗口实现流程布局?(二)

Qt 是目前最先进、最完整的跨平台C开发工具。它不仅完全实现了一次编写&#xff0c;所有平台无差别运行&#xff0c;更提供了几乎所有开发过程中需要用到的工具。如今&#xff0c;Qt已被运用于超过70个行业、数千家企业&#xff0c;支持数百万设备及应用。 本文将展示如何为不…

智能产品综合开发 - 手势识别

1 实训选题目的 本次实训选择的题目是“基于树莓派的手势识别系统”&#xff0c;旨在为人们提供一种便捷的交互方式&#xff0c;使用户能够通过手势控制智能设备&#xff0c;摆脱传统的物理按键操作。通过本项目&#xff0c;我们希望能实现快速、灵活的手势识别&#xff0c;提升…

Redis【1】- 如何阅读Redis 源码

1 Redis 的简介 Redis 实际上是简称&#xff0c;全称为 Remote Dictionary Server (远程字典服务器)&#xff0c;由 Salvatore Sanfilippo 写的高性能 key-value 存储系统&#xff0c;其完全开源免费&#xff0c;遵守 BSD 协议。Redis 与其他 key-value 缓存产品&#xff08;如…

git的使用(简洁版)

什么是 Git&#xff1f; Git 是一个分布式版本控制系统 (DVCS)&#xff0c;用于跟踪文件的更改并协调多人之间的工作。它由 Linus Torvalds 在 2005 年创建&#xff0c;最初是为了管理 Linux 内核的开发。Git 的主要目标是提供高效、易用的版本控制工具&#xff0c;使得开发者…

用于高吞吐量和低延迟的 JVM 性能调优

Java 虚拟机 &#xff08;JVM&#xff09; 调优是调整默认参数以满足我们的应用程序需求的过程。这包括通过选择合适的垃圾回收器来使用优化版本的 getter 来调整堆的大小等简单调整。 了解 Java 虚拟机 &#xff08;JVM&#xff09; 什么是 JVM&#xff1f; Java 虚拟机 &…

django authentication 登录注册

文章目录 前言一、django配置二、后端实现1.新建app2.编写view3.配置路由 三、前端编写1、index.html2、register.html3、 login.html 总结 前言 之前&#xff0c;写了django制作简易登录系统&#xff0c;这次利用django内置的authentication功能实现注册、登录 提示&#xff…

Python+Pytest+Yaml+Allure数据参数化(DDT)数据驱动(一)

我们在做数据之前要知道几个问题 1、在代码层面怎么来数据驱动 2、yaml文件是什么 3、怎么用yaml文件实现对应的数据驱动 我们用的是pytest框架所以相对来说是简单的&#xff0c;我们通过pytest框架来实现&#xff0c;而框架中要数据驱动用到我们装饰器就好啦pytest.mark.p…

WaveForms™ SDK 参考手册(翻译笔记与总结)

概述 WaveForms 提供了一个接口&#xff0c;允许用户与 Digilent Analog Design 硬件进行交互&#xff0c;例如 Analog DiscoveryTM、Analog Discovery 2TM、Analog Discovery ProTM、Digital DiscoveryTM、Discovery Power SupplyTM 和 Electronics ExplorerTM。虽然 WaveForm…

Python基础学习-12匿名函数lambda和map、filter

目录 1、匿名函数&#xff1a; lambda 2、Lambda的参数类型 3、map、 filter 4、本节总结 1、匿名函数&#xff1a; lambda 1&#xff09;语法&#xff1a; lambda arg1, arg2, …, argN : expression using arg 2&#xff09; lambda是一个表达式&#xff0c;而不是一个语…

pyqt5+yolo模型+多线程

界面开发 开发主窗口界面 from PyQt5 import QtWidgets from PyQt5 import QtCore,QtGui import sysclass MainWindow(QtWidgets.QMainWindow):def __init__(self):super().__init__()self.initUI()self.toolbar()# 创建菜单栏def initUI(self):menubar self.menuBar()file_m…

交通流量预测:基于交通流量数据建立模型

✅作者简介&#xff1a;2022年博客新星 第八。热爱国学的Java后端开发者&#xff0c;修心和技术同步精进。 &#x1f34e;个人主页&#xff1a;Java Fans的博客 &#x1f34a;个人信条&#xff1a;不迁怒&#xff0c;不贰过。小知识&#xff0c;大智慧。 &#x1f49e;当前专栏…

[Java]微服务配置管理

介绍 代码拆分为微服务后, 每个服务都有自己的配置文件, 而这些配置文件中有很多重复的配置, 并且配置变化后需要重启服务, 才能生效, 这样就会影响开发体验和效率 配置管理服务可以帮助我们集中管理公共的配置, 并且nacos就可以实现配置管理服务 配置共享 我们可以把微服务共…

【C++】入门【三】

本节目标 一、类的6个默认成员函数 二、 构造函数 三、析构函数 四、拷贝构造函数 五、赋值运算符重载 六、const成员函数 七、取地址及const取地址操作符重载 一、类的6个默认成员函数 如果类里一个成员都没有&#xff0c;简称空类空类中真的什么都没有吗&#xff1f;并不不是…

D78【 python 接口自动化学习】- python基础之HTTP

day78 pycharm创建项目并进行接口请求 学习日期&#xff1a;20241124 学习目标&#xff1a;http定义及实战 -- pycharm创建项目并进行接口请求 学习笔记&#xff1a; 安装requests 安装方式&#xff1a;pip/pip3 install requests 官网教程&#xff1a;Requests: HTTP fo…

UE5 实现组合键触发事件的方法

因为工作原因。 需要用大括号{和}来触发事件 但是在蓝图中搜了一下&#xff0c;发现键盘事件里根本就没有{}这两个键。 花费了一下午&#xff0c;终于找到解决的方法了&#xff0c;也就是增强输入的弦操作 首先创建一个项目 纯蓝图或者C都可行 进入到内容浏览器的默认页面 …

rabbitmq原理及命令

目录 一、RabbitMQ原理1、交换机&#xff08;Exchange&#xff09;fanoutdirecttopicheaders&#xff08;很少用到&#xff09; 2、队列Queue3、Virtual Hosts4、基础对象 二、RabbitMQ的一些基本操作:1、用户管理2、用户角色3、vhost4、开启web管理接口5、批量删除队列 一、Ra…

硬件基础22 反馈放大电路

目录 一、反馈的基本概念与分类 1、什么是反馈 2、直流反馈与交流反馈 3、正反馈与负反馈 4、串联反馈与并联反馈 5、电压反馈与电流反馈 二、负反馈四种组态 1、电压串联负反馈放大电路 2、电压并联负反馈放大电路 3、电流串联负反馈放大电路 4、电流并联负反馈放大…

新型大语言模型的预训练与后训练范式,苹果的AFM基础语言模型

前言&#xff1a;大型语言模型&#xff08;LLMs&#xff09;的发展历程可以说是非常长&#xff0c;从早期的GPT模型一路走到了今天这些复杂的、公开权重的大型语言模型。最初&#xff0c;LLM的训练过程只关注预训练&#xff0c;但后来逐步扩展到了包括预训练和后训练在内的完整…

网络知识1-TCP/IP模型

从用户端到服务端&#xff0c;tcp/ip模型可分为应用层、传输层、网络层、网络接口层 以下使用寄快递为例进行解释 应用层职责&#xff1a; 只关注与为用户提供应用功能&#xff0c;如HTTP、FTP、telnet、DNS、SMTP等 &#xff0c;应用层的职责就像我们寄快递时将快递给快递员…