自学内容网 自学内容网

(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.注册成功返回主界面


原文地址:https://blog.csdn.net/pjlpjlpjl/article/details/143276091

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!