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

news2024/11/30 1:05:13

一、什么是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.注册成功返回主界面

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

NLP信息抽取大总结:三大任务(带Prompt模板)

信息抽取大总结 1.NLP的信息抽取的本质&#xff1f;2.信息抽取三大任务&#xff1f;3.开放域VS限定域4.信息抽取三大范式&#xff1f;范式一&#xff1a;基于自定义规则抽取&#xff08;2018年前&#xff09;范式二&#xff1a;基于Bert下游任务建模抽取&#xff08;2018年后&a…

【JavaEE初阶 — 网络编程】TCP流套接字编程

TCP流套接字编程 1. TCP &#xff06; UDP 的区别 TCP 的核心特点是面向字节流&#xff0c;读写数据的基本单位是字节 byte 2 API介绍 2.1 ServerSocket 定义 ServerSocket 是创建 TCP 服务端 Socket 的API。 构造方法 方法签名 方法说明 ServerS…

记录一次 k8s 节点内存不足的排查过程

背景&#xff1a;前端服务一直报404&#xff0c;查看k8s日志&#xff0c;没发现报错&#xff0c;但是发现pods多次重启。 排查过程&#xff1a; 查看pods日志&#xff0c;发现日志进不去。 kubectrl logs -f -n weave pod-name --tail 100查看pod describe kubectl describ…

Java文件遍历那些事

文章目录 一、简要概述二、文件遍历几种实现1. java实现2. Apache common-io3. Spring 三、最终结论 一、简要概述 文件遍历基本上是每个编程语言具备的基本功能&#xff0c;Java语言也不例外。下面我们以java原生实现&#xff0c;Apache common-io、spring框架实现为例来比较…

硬件基础22 反馈放大电路

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

【JS】React与Vue的异步编程对比:深度解析与实战案例全面指南

文章目录 前言更多实用工具React与Vue概述ReactVue 异步编程基础回调函数PromiseAsync/Await React中的异步编程使用Axios进行数据请求异步操作与组件生命周期React Hooks中的异步处理 Vue中的异步编程使用Axios进行数据请求异步操作与Vue生命周期Vue Composition API中的异步处…

【iOS】知乎日报总结

文章目录 前言首页网络请求轮播图上滑加载图片请求 文章详情页WKWebView的使用点赞、收藏持久化——FMDB的使用 其他问题沙盒问题单元格点击其他 总结 前言 在系统学习了OC语言和UI控件后&#xff0c;知乎日报是第一个比较大的项目&#xff0c;耗时一个多月时间&#xff0c;里面…

算法竞赛(Python)-链表

文章目录 一 链表简介1.1链表定义1.2 双向链表1.3 循环链表 二、链表的基本操作2.1 链表的结构定义2.2 建立一个线性链表2.3 求线性链表的长度2.4 查找元素2.5 插入元素2.5.1 链表头部插入元素2.5.2 链表尾部插入元素2.5.3 链表中间插入元素 2.6 改变元素2.7 删除元素2.7.1 链表…

Unity ShaderLab 实现网格爆炸

实现思路&#xff1a; 沿着3D物体每个面的法线&#xff0c;将面偏移一定的位置。 Shader Graph实现如下&#xff1a; Shader Lab 实现如下&#xff1a; Shader "Unlit/MeshExplode" {Properties{_MainTex ("Texture", 2D) "white" {}_Distan…

快速上手:如何开发一个实用的 Edge 插件

在日常浏览网页时&#xff0c;背景图片能够显著提升网页的视觉体验。如果你也想为自己的浏览器页面添加个性化背景图片&#xff0c;并希望背景图片设置能够持久保存&#xff0c;本文将介绍如何通过开发一个自定义Edge插件来实现这一功能。我们将涵盖保存背景设置到插件选项页&a…

【Maven】功能和核心概念

1. 什么是Maven 1.1 Maven的概念 Maven 是 Apache 软件基金会组织维护的一款自动化构建工具&#xff0c;专注服务于 Java 平台的项目构建和依赖管理。 1.2 为什么要使用Maven&#xff1f; 在项目开发中&#xff0c;我们需要引用各种 jar 包&#xff0c;引用的 jar 包可能有…

神经网络归一化方法总结

在深度学习中&#xff0c;归一化 是提高训练效率和稳定性的关键技术。以下是几种常见的神经网络归一化方法的总结&#xff0c;包括其核心思想、适用场景及优缺点。 四种归一化 特性Batch NormalizationGroup NormalizationLayer NormalizationInstance Normalization计算维度…

视频汇聚平台Liveweb国标GB28181视频平台监控中心设计

在现代安防视频监控领域&#xff0c;Liveweb视频汇聚平台以其卓越的兼容性和灵活的拓展能力&#xff0c;为用户提供了一套全面的解决方案。该平台不仅能够实现视频的远程监控、录像、存储与回放等基础功能&#xff0c;还涵盖了视频转码、视频快照、告警、云台控制、语音对讲以及…

hubu新星杯实践能力赛模拟赛web/Misc-wp

ez_eval <?php highlight_file(__FILE__); error_reporting(0);$hubu $_GET[hubu];eval($hubu);?> 先进行代码审计&#xff0c;GET传参hubu&#xff0c;并执行命令&#xff0c;没有任何绕过&#xff0c;放开手脚去做 payload: ?hubusystem(cat /f*); #直接rcerc…

【前端】跨域问题与缓存

报错如下&#xff1a; 原因&#xff1a; 浏览器 缓存跨域&#xff0c;顾名思义是由于浏览器的缓存机制导致的一种跨域情况。这种跨域一般会出现在浏览器通过一些无视跨域的标签和css(如img、background-image)缓存了一些图片资源之后&#xff0c;当再次发起图片请求时&#xff…

抓包之OSI七层模型以及TCPIP四层模型

写在前面 本文看下OSI七层模型以及TCP/IP四层网络模型&#xff0c;并尝试使用wireshark进行验证。 1&#xff1a;OSI七层网络模型和TCP/IP四层模型 全称&#xff1a;open system interconnection。 需要注意OSI七层模型最终是没有落地的&#xff0c;最终落地的是与之类似的…

#渗透测试#红蓝攻防#HW#漏洞挖掘#漏洞复现02-永恒之蓝漏洞

免责声明 本教程仅为合法的教学目的而准备&#xff0c;严禁用于任何形式的违法犯罪活动及其他商业行为&#xff0c;在使用本教程前&#xff0c;您应确保该行为符合当地的法律法规&#xff0c;继续阅读即表示您需自行承担所有操作的后果&#xff0c;如有异议&#xff0c;请立即停…

MTK 展锐 高通 sensorhub架构

一、MTK平台 MTK框架可以分为两部分&#xff0c;AP和SCP。 AP是主芯片&#xff0c;SCP是协处理器&#xff0c;他们一起工作来处理sensor数据。 SCP 是用来处理sensor和audio相关功能和其他客制化需求的一个协处理理器&#xff0c;MTK SCP选择freeRTOS作为操作系统&#xff0c…

视觉语言模型(VLM)学习笔记

目录 应用场景举例 VLM 的总体架构包括&#xff1a; 深度解析&#xff1a;图像编码器的实现 图像编码器&#xff1a;视觉 Transformer 注意力机制 视觉-语言投影器 综合实现 训练及注意事项 总结 应用场景举例 基于文本的图像生成或编辑&#xff1a;你输入 “生成一张…

[AutoSar]BSW_Diagnostic_007 BootLoader 跳转及APP OR boot response 实现

目录 关键词平台说明背景一、Process Jump to Bootloader二、相关函数和配置2.1 Dcm_GetProgConditions()2.2 Dcm_SetProgConditions() 三、如何实现在APP 还是BOOT 中对10 02服务响应3.1 配置3.2 code 四、报文五、小结 关键词 嵌入式、C语言、autosar、OS、BSW、UDS、diagno…