SSM整合之增刪改查


一:SSM整合介紹

SpringMVC+Spring+Mybatis 俗稱SSM 

  在下面的整合案例中我將帶大家完成整合和簡單的CRUD操作,前端頁面我將使用Vue和Element-UI來完成簡單的布局,下面我將為大家展示全部代碼,如果有對SSM部分不了解的也可以參考我的博客(詳細)

1:環境介紹

JDK:1.9 tomcat:9.0.12 MySQL:5.5 maven:3.5.2 編譯器:Intellij IDEA 2020.2.3 x64

2:項目頁面

3:項目結構

二:代碼實現

1:基本配置文件SQL語句

<packaging>war</packaging>

    <!--設置maven的代碼編譯環境 我設置JDK1.9-->
    <properties>
        <maven.compiler.source>1.9</maven.compiler.source>
        <maven.compiler.target>1.9</maven.compiler.target>
        <maven.compiler.compilerVersion>1.9</maven.compiler.compilerVersion>
    </properties>
    
    <dependencies>
        <!-- ##########  Spring家族坐標  ########## -->
        <!--Spring-context主要坐標 核心容器-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <!--spring的jdbc操作數據庫的jar包,包含spring自帶數據源,jdbcTemplate-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <!--Spring對mybatis的支持-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
        <!--Spring-test測試坐標-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <!--Spring對Aop支持-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <!--支持解析切入點表達式等等-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>
        <!--支持AOP相關注解等等-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.5</version>
        </dependency>
        <!--事務管理器jar包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.2.6.RELEASE</version>
        </dependency>
        <!--springmvc的核心包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>

        <!-- ##########  mybatis核心坐標 注解sql語句需要  ########## -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <!-- ##########  日志相關坐標  ########## -->
        <!--引入日志的jar包 門面模式-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>
        <!-- 日志工具包 -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.10.0</version>
        </dependency>
        <!--日志核心包-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.10.0</version>
        </dependency>
        <!--web相關的功能包-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <version>2.9.1</version>
        </dependency>
        <!--為java做簡單的日志記錄-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>
        <!--slf4j的log4j實現類-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>2.9.1</version>
        </dependency>
        <!--程序運行的時候檢測用了哪種日志實現類-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-jcl</artifactId>
            <version>2.9.1</version>
        </dependency>

        <!-- ##########  jackson之JSON處理相關坐標  ########## -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.0</version>
        </dependency>

        <!-- ##########  JSTL相關坐標 循環標簽啥的  ########## -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>

        <!-- ##########  Servlet/Jsp坐標  ########## -->
        <!--servlet-api :引入servlet的功能-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <!--jsp-api: jsp頁面的功能包 -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
            <scope>provided</scope>
        </dependency>

        <!-- ##########  其它補充坐標  ########## -->
        <!--JDK9廢棄了一些注解,使用此坐標導入-->
        <dependency>
            <groupId>javax.annotation</groupId>
            <artifactId>javax.annotation-api</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!--mysql驅動坐標-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <!--c3p0連接池坐標-->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <!--junit單元測試坐標-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <!--用來為實體類生成get/set啥的方法-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>
    </dependencies>
pom.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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">

    <!--開啟注解掃描 放入Spring容器-->
    <context:component-scan base-package="cn.xw">
        <!--不掃描Controller和Repository注解的類 Repository下面集成Mybatis掃描了 Controller在Springmvc.xml掃描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>

    <!--數據庫連接基本信息properties文件引入-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--配置C3P0連接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--設置Mybatis工廠類bean對象-->
    <bean id="factoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--設置mybatis數據源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置別名-->
        <property name="typeAliasesPackage" value="cn.xw.pojo"/>
        <!--配置mybatis配置文件,如果有別的配置文件可以使用此標簽導入-->
        <!--<property name="configuration" value="classpath:SqlMapConfig.xml"/>-->
    </bean>

    <!--配置mapper掃描映射類 一旦設置這個  說明dao包下的類都被掃描到Spring容器了-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.xw.dao"/>
    </bean>

    <!--配置Spring自帶的事務管理器  此時我使用的是Mybatis,所以要使用DataSourceTransactionManager實現類-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!--配置事務通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*" propagation="REQUIRED" read-only="false"/>
            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <!--配置AOP切入點表達式-->
    <aop:config>
        <aop:pointcut id="pt1" expression="execution(* cn.xw.service.impl.*.*(..))"/>
        <!--我們使用Spring提供的事務通知的話就不用再配置<aop:aspect>來指定啥前/后/環繞啥的通知了-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
    </aop:config>
</beans>
applicationContext.xml   Spring配置  聲明注解掃描、事務等
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/demo_school
jdbc.username=root
jdbc.password=123
jdbc.properties  連接數據庫基本信息
<?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 
       http://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">

    <!--注解掃描 加入Spring容器-->
    <context:component-scan base-package="cn.xw.controller">
        <!--設置只掃描Controller注解-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--視圖解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--配置放行靜態資源 Spring3.0以后發布  如果配置*.do在前端控制器就不要釋放靜態資源了-->
    <!--<mvc:default-servlet-handler/>-->
    <!--配置放行靜態資源 Spring3.0之前 2選一-->
    <!--<mvc:resources mapping="/plugins/" location="/js/**"/>
    <mvc:resources mapping="/css/" location="/css/**"/>
    <mvc:resources mapping="/img/" location="/img/**"/>-->

    <!--開啟MVC注解-->
    <mvc:annotation-driven/>
</beans>
springmvc.xml  SpringMVC配置 聲明視圖解析器
<?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_4_0.xsd"
         version="4.0">

    <!--監聽ServletContext對象創建-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--配置Spring配置文件加載 當tomcat啟動會為每個WEB創建一個ServletContext對象,ServletContext初始化會執行-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationConfig.xml</param-value>
    </context-param>

    <!--配置前端控制器-->
    <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:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!--配置post請求字符亂碼攔截器-->
    <filter>
        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
web.xml  web項目的主要配置文件

2:一些實體類及業務

/**
 * @author: xiaofeng
 * @date: Create in $DATE
 * @description: 此結果類用來和前端交互
 * @version: v1.0.0
 */
@Data   //使用data一定要下載lombok插件
public class Result {
    private Boolean flag;       //記錄此處操作是否成功
    private String Message;     //返回的信息提示
    private List data;       //返回的數據
    public Result(Boolean flag, String message, List data) {
        this.flag = flag;
        Message = message;
        this.data = data;
    }
    public Result(Boolean flag, String message) {
        this.flag = flag;
        Message = message;
    }
}

//+++++++++++++++++++++++++++++++++++++

/**
 * @author: xiaofeng
 * @date: Create in 2020/12/8
 * @description: 學生實體類
 * @version: v1.0.0
 */
@Data
public class Student {
    private int id;            //主鍵id
    private String name;       //姓名
    private String sex;        //性別
    private int age;           //年齡
    private double credit;     //學分
    private double money;      //零花錢
    private String address;    //住址
    private String enrol;      //入學時間
    //因為簡單的單表CRUD就不涉及到外鍵
    //private int fid;            //外鍵 連接家庭表信息學生對家庭,一對一
    //private int tid;            //外鍵 連接老師信息 學生對老師,一對一
    //創建構造器/get/set/toString就不展示了
}
cn.xw.entity.Result  及  cn.xw.pojo.Student 實體類
/**
 * @author: xiaofeng 
 * @date: Create in $DATE
 * @description: 學生Controller
 * @version: v1.0.0
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    //自動注入StudentService實現類
    @Autowired
    private StudentService studentService;
    
    //查詢全部
    @RequestMapping("/findAll")
    public Result findAll() {
        try {
            List<Student> studentList = studentService.findAll();
            return new Result(true, "數據查詢完成", studentList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "數據查詢失敗");
        }
    }

    //根據ID查詢數據
    @RequestMapping("/findById")
    public Result findById(@RequestParam("id") Integer stuId) {
        try {
            Student student = studentService.findById(stuId);
            //查詢的數據封裝到List對象
            ArrayList<Student> arrayList = new ArrayList<>();
            arrayList.add(student);
            return new Result(true, "數據查詢完成", arrayList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "數據查詢失敗");
        }
    }

    //更新學生
    @RequestMapping("/update")
    public Result updateStudent(@RequestBody Student student) {
        try {
            Boolean boo = studentService.update(student);
            if (boo) {
                return new Result(true, "更新成功");
            } else {
                return new Result(false, "未更新成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "更新出錯");
        }
    }

    //添加
    @RequestMapping("/save.do")
    public Result saveStudent(@RequestBody Student student) {

        System.out.println(student);
        try {
            Boolean boo = studentService.save(student);
            if (boo) {
                return new Result(true, "添加成功");
            } else {
                return new Result(false, "添加失敗");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "添加出錯");
        }
    }

    //刪除
    @RequestMapping("/delete.do")
    public Result deleteStudent(Integer id) {
        try {
            Boolean boo = studentService.deleteById(id);
            if (boo) {
                return new Result(true, "刪除成功");
            } else {
                return new Result(false, "刪除失敗");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "刪除出錯");
        }
    }
}
cn.xw.controller.StudentController  學生請求處理Controller
/**
 * @author: xiaofeng
 * @date: Create in $DATE
 * @description: 學生dao接口
 * @version: v1.0.0
 */
public interface StudentDao {

    /**
     * 根據ID查詢學生
     * @param id
     * @return
     */
    @Select("select * from student where sid=#{sid}")
    @Results(id = "studentMapper", value = {
            @Result(id = true, column = "sid", property = "id"),
            @Result(column = "sname", property = "name"),
            @Result(column = "ssex", property = "sex"),
            @Result(column = "sage", property = "age"),
            @Result(column = "scredit", property = "credit"),
            @Result(column = "smoney", property = "money"),
            @Result(column = "saddress", property = "address"),
            @Result(column = "senrol", property = "enrol")
    })
    Student findById(@Param(value = "sid") Integer id);

    /**
     * 查詢全部學生
     * @return
     */
    @Select("select * from student limit 6")
    @ResultMap(value = {"studentMapper"})
    List<Student> findAll();

    /**
     * 添加學生
     * @param student
     * @return
     */
    @Insert("insert into student(sname,ssex,sage,scredit,smoney,saddress,senrol)" +
            " values (#{name},#{sex},#{age},#{credit},#{money},#{address},#{enrol})")
    Boolean save(Student student);

    /**
     * 更新學生
     * @param student
     * @return
     */
    @Update("update student set sname=#{name},ssex=#{sex},sage=#{age}," +
            "scredit=#{credit},smoney=#{money},senrol=#{enrol},saddress=#{address} where sid=#{id}")
    Boolean update(Student student);

    /**
     * 根據ID刪除學生
     * @param id
     * @return
     */
    @Delete("delete from student where sid = #{sid}")
    Boolean deleteById(@Param(value = "sid") Integer id);
    
}
cn.xw.dao.StudentDao  學生dao操作
/**
 * @author: xiaofeng
 * @date: Create in $DATE
 * @description: 學生業務接口
 * @version: v1.0.0
 */
public interface StudentService {

    List<Student> findAll();

    Boolean save(Student student);

    Boolean update(Student student);

    Boolean deleteById(Integer id);
    
    Student findById(Integer stuId);
}

//+++++++++++++++++++++++++++++++++++++

/**
 * @author: xiaofeng
 * @date: Create in $DATE
 * @description: 學生業務接口實現類
 * @version: v1.0.0
 */
@Service
public class StudentServiceImpl implements StudentService {

    //自動注入 提供構造方法 或者使用@Autowired也OK
    private final StudentDao studentDao;

    public StudentServiceImpl(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    /**
     * 查詢全部學生
     * @return
     */
    @Override
    public List<Student> findAll() {
        return studentDao.findAll();
    }


    /**
     * 根據ID查詢
     * @param stuId
     * @return
     */
    @Override
    public Student findById(Integer stuId) {
        return studentDao.findById(stuId);
    }

    /**
     * 添加學生
     * @return
     */
    @Override
    public Boolean save(Student student) {
        return studentDao.save(student);
    }

    /**
     * 更新學生
     * @param student
     * @return
     */
    @Override
    public Boolean update(Student student) {
        return studentDao.update(student);
    }

    /**
     * 刪除學生
     * @param id
     * @return
     */
    @Override
    public Boolean deleteById(Integer id) {
        System.out.println(id);
        return studentDao.deleteById(id);
    }
}
cn.xw.service.StudentService  及  cn.xw.service.impl.StudentServiceImpl  業務

3:測試代碼(有需求的可以在寫完這個測試)

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = "classpath:applicationConfig.xml")
public class MyTest {

    @Autowired
    private StudentService studentService;
    @Test
    public void testFindAll() {
        List<Student> students = studentService.findAll();
        for (Student student : students) {
            System.out.println(student);
        }
    }
    @Test
    public void testSave() {
        Student stu = new Student();
        stu.setName("許齡月");
        stu.setSex("女");
        stu.setAge(25);
        stu.setCredit(65);
        stu.setMoney(600.5);
        stu.setAddress("安徽六安");
        stu.setEnrol("2020-12-8");
        Boolean boo = studentService.save(stu);
        System.out.println("是否保存完成:" + boo);
    }
    @Test
    public void testUpdate() {
        Student stu = new Student();
        stu.setId(1);
        stu.setName("螞蟻小哥");
        stu.setSex("男");
        stu.setAge(25);
        stu.setCredit(65);
        stu.setMoney(600.5);
        stu.setAddress("安徽六安");
        stu.setEnrol("2020-12-8");
        Boolean boo = studentService.update(stu);
        System.out.println("是否更新完成:" + boo);
    }
    @Test
    public void testDelete() {
        //有主見存在,不能亂刪只能刪除最后添加的
        Boolean boo = studentService.deleteById(66);
        System.out.println("是否刪除完成:" + boo);
    }
}
測試

4:頁面代碼

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>SSM框架整合</title>
    <meta content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no" name="viewport">
    <!-- CDN引入樣式  這樣就不用下載了 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!--<link rel="stylesheet" href="../elementui/index.css">-->
</head>
<body class="hold-transition">
<!--組件開始-->
<div id="app">

    <div class="content-header">
        <h1><small>學生管理</small></h1>
    </div>

    <div class="app-container">
        <div class="box">
            <!--新建按鈕-->
            <div class="filter-container">
                <el-button type="primary" class="butT" @click="handleCreate()">新建</el-button>
            </div>
            <!--表單正文-->
            <el-table size="small" current-row-key="id" :data="dataList" stripe highlight-current-row>
                <el-table-column type="index" align="center" label="序號"></el-table-column>
                <el-table-column prop="name" align="center" label="姓名"></el-table-column>
                <el-table-column prop="sex" align="center" label="性別"></el-table-column>
                <el-table-column prop="age" align="center" label="年齡"></el-table-column>
                <el-table-column prop="credit" align="center" label="學分"></el-table-column>
                <el-table-column prop="money" align="center" label="零花錢"></el-table-column>
                <el-table-column prop="address" align="center" label="地址"></el-table-column>
                <el-table-column prop="enrol" align="center" label="入學時間"></el-table-column>

                <el-table-column fixed="right" width="150" label="操作" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">編輯</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)">刪除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 新增標簽彈層 -->
            <div class="add-form">
                <el-dialog title="新增賬戶" :visible.sync="dialogFormVisible">
                    <el-form ref="dataAddForm" :model="formData" label-position="right" label-width="100px">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="學生姓名">
                                    <el-input v-model="formData.name" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="性別">
                                    <el-input v-model="formData.sex" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="年齡">
                                    <el-input v-model="formData.age" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="學分">
                                    <el-input v-model="formData.credit" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="零花錢">
                                    <el-input v-model="formData.money" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="住址">
                                    <el-input v-model="formData.address" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col>
                                <el-form-item label="入學時間">
                                    <el-date-picker :span="24"
                                                    value-format="yyyy-MM-dd"
                                                    v-model="formData.enrol"
                                                    type="date"
                                                    placeholder="選擇日期">
                                    </el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取消</el-button>
                        <el-button type="primary" @click="handleAdd()">確定</el-button>
                    </div>
                </el-dialog>
            </div>
            <!-- 編輯標簽彈層 -->
            <div class="add-form">
                <el-dialog title="編輯賬戶" :visible.sync="dialogFormVisible4Edit">
                    <el-form ref="dataAddForm" :model="formData" label-position="right" label-width="100px">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="學生編號">
                                    <el-input v-model="formData.id" disabled></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="學生姓名">
                                    <el-input v-model="formData.name" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="性別">
                                    <el-input v-model="formData.sex" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="年齡">
                                    <el-input v-model="formData.age" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="學分">
                                    <el-input v-model="formData.credit" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="零花錢">
                                    <el-input v-model="formData.money" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="住址">
                                    <el-input v-model="formData.address" type="text"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="入學時間">
                                    <el-input v-model="formData.enrol" type="text" disabled type="date"></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <div slot="footer" class="dialog-footer">
                        <el-button @click="dialogFormVisible4Edit = false">取消</el-button>
                        <el-button type="primary" @click="handleEdit()">確定</el-button>
                    </div>
                </el-dialog>
            </div>
        </div>
    </div>
</div>
</body>
<!-- CDN引入 這樣就不用下載了-->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<!--<script src="../js/vue.js"></script>-->
<!--<script src="../elementui/index.js"></script>-->
<!--<script src="../js/axios-0.18.0.js"></script>-->
<script>
    var vue = new Vue({
        el: '#app',
        data: {
            dataList: [
                {
                    id: 1,
                    name: "螞蟻小哥",
                    sex: "男",
                    age: 25,
                    credit: 65.0,
                    money: 600.5,
                    address: "安徽六安",
                    enrol: "2020-12-12"
                }
            ],//當前頁要展示的分頁列表數據
            formData: {},//表單數據
            dialogFormVisible: false,//增加表單是否可見
            dialogFormVisible4Edit: false//編輯表單是否可見
        },
        //鈎子函數,VUE對象初始化完成后自動執行
        created() {
            this.findPage();
        },
        methods: {
            //編輯
            handleEdit() {
                axios.post("http://localhost:8080/ssm/student/update.do",this.formData).then(response=>{
                    if(response.data.flag){
                       this.$message.success(response.data.message);
                        //再次更新一下表單
                        this.findPage();
                        //操作成功后改變修改表單到隱藏
                        this.dialogFormVisible4Edit=false;
                    }else{
                        this.$message.error(response.data.message)
                    }
                })
            },
            //添加
            handleAdd() {
                axios.post("http://localhost:8080/ssm/student/save.do",this.formData).then(response=>{
                    if(response.data.flag){
                        this.$message.success(response.data.message)
                        //再次更新一下表單
                        this.findPage();
                        //操作成功后改變修改表單到隱藏
                        this.dialogFormVisible=false;
                    }else{
                        this.$message.error(response.data.message)
                    }

                })

            },
            //查詢
            findPage() {
                //發送ajax請求獲取全部數據
                axios.get("http://localhost:8080/ssm/student/findAll.do").then(response => {
                    if(response.data.flag){
                        console.log(response.data);
                        this.dataList = response.data.data;
                    }else{
                        this.$message.error(response.data.message)
                    }
                })
            },
            // 新增彈窗
            handleCreate() {
                this.dialogFormVisible = true;
                this.formData = {};
            },
            //編輯彈框
            handleUpdate(row) {
                this.dialogFormVisible4Edit = true;
                //把原有的表單數據賦值給編輯頁面,但是不推薦,因為中途表單已經被更改了 所以先id查詢回顯
                //this.formData = row;
                axios.get("http://localhost:8080/ssm/student/findById.do?id="+row.id).then(response => {
                    if(response.data.flag){
                        this.formData = response.data.data[0];
                    }else{
                        this.$message.error(response.data.message)
                    }
                })
            },
            // 刪除
            handleDelete(row) {
                this.$confirm('此操作將永久刪除該文件, 是否繼續?', '提示', {
                    confirmButtonText: '確定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //ajax發送刪除
                    axios.get("http://localhost:8080/ssm/student/delete.do?id="+row.id).then(response=>{
                        if(response.data.flag){
                            this.$message.success(response.data.message)
                            //再次更新一下表單
                            this.findPage();
                        }else{
                            this.$message.error(response.data.message)
                        }
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消刪除'
                    });
                });
            }
        }
    })
</script>
</html>
pages/data.html  直接把這個頁面創建,其它資源如Vue什么都不用導入了使用CND

.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM