(动力节点项目)SSM整合:SSM+VUE

目录:

  • 一、效果图:
  • 二、实现步骤:
    • 1.后端:
    • 2.前端:
  • 三、后端SSM:
    • 1.项目结构:
    • 2. 实现思路:
      • (1)创建数据库表:
      • (2)pom.xml文件添加依赖:
      • (3)添加properties属性配置文件:
      • (4)SqlMapConfig.xml(Mybatis核心配置文件):
      • (5)applicationContext_mapper.xml文件(数据访问层的核心配置文件):
      • (6)applicationContext_service.xml文件(业务逻辑层的核心配置文件):
      • (7)spirngmvc.xml文件(Springmvc核心配置文件):
      • (8) web.xml文件设置中文编码,注册spirngmvc框架、Spring框架:
      • (9)新建实体类user:
      • (10)新建UserMapper.java接口:
      • (11)新建UserMapper.xml实现接口中所有功能:
      • (12)新建service接口:
      • (13)新建service实现类实现接口中所有功能:
      • (14)新建测试类,完成所有功能的测试:
      • (15)新建控制器,完成所有功能:
  • 四、前端VUE:
    • 1.项目结构:
    • 2.UserHome.vue解析:
  • 五、附件:后端接口文档:

一、效果图:

(动力节点项目)SSM整合:SSM+VUE_第1张图片
(动力节点项目)SSM整合:SSM+VUE_第2张图片
(动力节点项目)SSM整合:SSM+VUE_第3张图片

二、实现步骤:

1.后端:

  1. 创建数据库。
  2. 新建Maven项目,选择webapp模板。
  3. 补全webapp缺失目录。
  4. 修改pom.xml文件,添加依赖。
  5. 添加jdbc.properties属性配置文件。
  6. 添加SqlMapConfig.xml(Mybatis核心配置文件)。
  7. 添加applicationContext_mapper.xml文件(数据访问层的核心配置文件)。
  8. 添加applicationContext_service.xml文件(业务逻辑层的核心配置文件)。
  9. 添加spirngmvc.xml文件(Springmvc核心配置文件)。
  10. web.xml文件设置中文编码,并注册spirngmvc框架,并注册Spring框架。
  11. 新建实体类user。
  12. 新建UserMapper.java接口。
  13. 新建UserMapper.xml实现增删查所有功能。
  14. 新建service接口和实现类。
  15. 新建测试类,完成所有功能的测试。
  16. 新建控制器,完成所有功能。
  17. 浏览器测试功能。

2.前端:

  1. 使用前端交付的VUE项目。
  2. cd E:\idea_workspace\ssm-vue01 进入到当前项目的目录下
  3. npm i element -ui -S 下载elementUI的框架
  4. npm install 打包项目
  5. npm install --save vue-axios 下载跨域访问组件axios
  6. 在IDEA中启动VUE项目,使用npm的配置方式部署项目。
  7. 配合后端项目进行测试。

三、后端SSM:

1.项目结构:

(动力节点项目)SSM整合:SSM+VUE_第4张图片

2. 实现思路:

(1)创建数据库表:

(动力节点项目)SSM整合:SSM+VUE_第5张图片

(2)pom.xml文件添加依赖:



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>org.examplegroupId>
  <artifactId>ssmartifactId>
  <version>1.0version>
  <packaging>warpackaging>



  
  <properties>
    
    <junit.version>4.12junit.version>
    
    <spring.version>5.2.5.RELEASEspring.version>
    
    <mybatis.version>3.5.1mybatis.version>
    
    <mybatis.spring.version>1.3.1mybatis.spring.version>
    
    <mybatis.paginator.version>1.2.15mybatis.paginator.version>
    
    <mysql.version>8.0.26mysql.version>
    
    <slf4j.version>1.6.4slf4j.version>
    
    <druid.version>1.1.12druid.version>
    
    <pagehelper.version>5.1.2pagehelper.version>
    
    <jstl.version>1.2jstl.version>
    
    <servlet-api.version>3.0.1servlet-api.version>
    
    <jsp-api.version>2.0jsp-api.version>
    
    <jackson.version>2.9.6jackson.version>
  properties>


  <dependencies>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-beansartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aspectsartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jmsartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-context-supportartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>${mybatis.spring.version}version>
    dependency>
    <dependency>
      <groupId>com.github.miemiedevgroupId>
      <artifactId>mybatis-paginatorartifactId>
      <version>${mybatis.paginator.version}version>
    dependency>
    <dependency>
      <groupId>com.github.pagehelpergroupId>
      <artifactId>pagehelperartifactId>
      <version>${pagehelper.version}version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>
    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>${druid.version}version>
    dependency>
    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>${junit.version}version>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>${jstl.version}version>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.0.1version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>jsp-apiartifactId>
      <scope>providedscope>
      <version>${jsp-api.version}version>
    dependency>
    
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>${jackson.version}version>
    dependency>
    <dependency>
      <groupId>org.jsongroupId>
      <artifactId>jsonartifactId>
      <version>20140107version>
    dependency>
    
    <dependency>
      <groupId>commons-iogroupId>
      <artifactId>commons-ioartifactId>
      <version>2.4version>
    dependency>
    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.3.1version>
    dependency>
    
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>2.0.3version>
    dependency>
    
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-simpleartifactId>
      <version>2.0.3version>
      <scope>testscope>
    dependency>

  dependencies>


  
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.pluginsgroupId>
        <artifactId>maven-compiler-pluginartifactId>
        <configuration>
          
          
          <source>1.8source>
          <target>1.8target>
          <encoding>UTF-8encoding>
        configuration>
      plugin>
    plugins>
    
    <resources>
      <resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.propertiesinclude>
          <include>**/*.xmlinclude>
        includes>
        <filtering>falsefiltering>
      resource>
      <resource>
        <directory>src/main/resourcesdirectory>
        <includes>
          <include>**/*.propertiesinclude>
          <include>**/*.xmlinclude>
        includes>
        <filtering>falsefiltering>
      resource>
    resources>
  build>

project>

(3)添加properties属性配置文件:

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/123
jdbc.username=账号
jdbc.password=密码

(4)SqlMapConfig.xml(Mybatis核心配置文件):


DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    settings>
    
configuration>

(5)applicationContext_mapper.xml文件(数据访问层的核心配置文件):


<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 https://www.springframework.org/schema/context/spring-context.xsd">
    
    <context:component-scan base-package="com.user.mapper"/>
    
    <context:property-placeholder location="classpath:jdbc.properties"/>
    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    bean>
    
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="configLocation" value="classpath:SqlMapConfig.xml"/>
        
        <property name="typeAliasesPackage" value="com.user.pojo"/>
    bean>
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.user.mapper"/>
    bean>
beans>

(6)applicationContext_service.xml文件(业务逻辑层的核心配置文件):


<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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <context:component-scan base-package="com.user.service"/>
    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        
        <property name="dataSource" ref="dataSource"/>
    bean>
    
    <tx:advice id="myadvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*select*" read-only="true"/>
            <tx:method name="*find*" read-only="true"/>
            <tx:method name="*search*" read-only="true"/>
            <tx:method name="*get*" read-only="true"/>
            <tx:method name="*insert*" propagation="REQUIRED"/>
            <tx:method name="*add*" propagation="REQUIRED"/>
            <tx:method name="*save*" propagation="REQUIRED"/>
            <tx:method name="*set*" propagation="REQUIRED"/>
            <tx:method name="*update*" propagation="REQUIRED"/>
            <tx:method name="*change*" propagation="REQUIRED"/>
            <tx:method name="*modify*" propagation="REQUIRED"/>
            <tx:method name="*delete*" propagation="REQUIRED"/>
            <tx:method name="*drop*" propagation="REQUIRED"/>
            <tx:method name="*remove*" propagation="REQUIRED"/>
            <tx:method name="*clear*" propagation="REQUIRED"/>
            <tx:method name="*" propagation="SUPPORTS"/>
        tx:attributes>
    tx:advice>
    
    <aop:config>
        <aop:pointcut id="mycut" expression="execution(* com.user.service.Impl.*.*(..))"/>
        <aop:advisor advice-ref="myadvice" pointcut-ref="mycut"/>
    aop:config>
beans>

(7)spirngmvc.xml文件(Springmvc核心配置文件):


<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">
    
    <context:component-scan base-package="com.user.controller"/>
    
    <mvc:annotation-driven/>
beans>

(8) web.xml文件设置中文编码,注册spirngmvc框架、Spring框架:


<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">
    
    <filter>
        <filter-name>encodefilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
        <init-param>
            <param-name>forceRequestEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
        <init-param>
            <param-name>forceResponseEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodefilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
    
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc.xmlparam-value>
        init-param>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext_*.xmlparam-value>
    context-param>
web-app>

(9)新建实体类user:

package com.user.pojo;

public class User {
    private String userId;
    private String cardType;
    private String cardNo;
    private String userName;
    private String userSex;
    private String userAge;
    private String userRole;

    @Override
    public String toString() {
        return "User{" +
                "userId='" + userId + '\'' +
                ", cardType='" + cardType + '\'' +
                ", cardNo='" + cardNo + '\'' +
                ", userName='" + userName + '\'' +
                ", userSex='" + userSex + '\'' +
                ", userAge='" + userAge + '\'' +
                ", userRole='" + userRole + '\'' +
                '}';
    }

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getCardType() {
        return cardType;
    }

    public void setCardType(String cardType) {
        this.cardType = cardType;
    }

    public String getCardNo() {
        return cardNo;
    }

    public void setCardNo(String cardNo) {
        this.cardNo = cardNo;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

    public String getUserAge() {
        return userAge;
    }

    public void setUserAge(String userAge) {
        this.userAge = userAge;
    }

    public String getUserRole() {
        return userRole;
    }

    public void setUserRole(String userRole) {
        this.userRole = userRole;
    }

    public User() {
    }

    public User(String userId, String cardType, String cardNo, String userName, String userSex, String userAge, String userRole) {
        this.userId = userId;
        this.cardType = cardType;
        this.cardNo = cardNo;
        this.userName = userName;
        this.userSex = userSex;
        this.userAge = userAge;
        this.userRole = userRole;
    }
}

(10)新建UserMapper.java接口:

package com.user.mapper;

import com.user.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserMapper {

    /**
     * 根据条件分页获取分页数据:
     * url:
     * /user/selectUserPage?userName=z&userSex=男&page=null
     * 参数:
     * userName:表单中用户名称
     * userSex:表单中用户性别
     * page:提交的页码(第一次访问为null)
     * 结果:
     * 有数据时:
     * [{
     * "userId":"15968954638794962",
     * "cardType":"身份证",
     * "cardNo":"343343554654",
     * "userName":"撒撒旦",
     * "userSex":"女",
     * "userAge":"29",
     * "userRole":"生产、运输设备操作人员及有关人员"},
     * {...}
     * ]
     * 无数据时:
     * []
     */
    List<User> selectUserPage(
            @Param("userName")
            String userName,
            @Param("userSex")
            String UserSex,
            @Param("startRow")
            int startRow);

    /**
     * 增加用户:
     * url:
     * /user/createUser(参数见下面)
     * 参数:
     * cardType: this.ruleForm.cardType,//证件类型
     * cardNo: this.ruleForm.cardNo,//证件号码
     * userName: this.ruleForm.userName,//用户姓名
     * userSex: this.ruleForm.userSex,//用户性别
     * userAge: this.ruleForm.userAge,//用户年龄
     * userRole: this.ruleForm.userRole,//用户角色
     * 结果:
     * 增加成功时:
     * 1
     * 增加失败时:
     * 0
     */
    int createUser(User user);

    /**
     * 根据用户ID删除用户:
     * url:
     * /user/ deleteUserById?userId= 15968162087363060
     * 参数:
     * userId:删除用户的id
     * 结果:
     * 删除成功时:
     * 1
     * 删除失败时:
     * 0
     */
    int deleteUserById(String userId);

    /**
     * 获取总行数:
     * url:
     * /user/getRowCount?userName=z&userSex=男
     * 参数:
     * userName:表单中用户名称
     * userSex:表单中用户性别
     * 结果:
     * 有数据时:
     * 12
     * 无数据时:
     * 0
     */
    int getRowCount(
            @Param("userName")
            String userName,
            @Param("userSex")
            String userSex);

    /**
     * 更新用户:
     * url:
     * /user/updateUserById(参数见以下)
     * 参数:
     * userId: this.ruleForm.userId,//用户 Id
     * cardType: this.ruleForm.cardType,//证件类型
     * cardNo: this.ruleForm.cardNo,//证件号码
     * userName: this.ruleForm.userName,//用户姓名
     * userSex: this.ruleForm.userSex,//用户性别
     * userAge: this.ruleForm.userAge,//用户年龄
     * userRole: this.ruleForm.userRole,//用户角色
     * 结果:
     * 成功时:
     * 1
     * 出错时:
     * 0
     */
    int updateUserById(User user);
}

(11)新建UserMapper.xml实现接口中所有功能:


DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.user.mapper.UserMapper">

    
    <resultMap id="userMap" type="user">
        <id property="userId" column="user_id"/>
        <result property="cardType" column="card_type"/>
        <result property="cardNo" column="card_no"/>
        <result property="userName" column="user_name"/>
        <result property="userSex" column="user_sex"/>
        <result property="userAge" column="user_age"/>
        <result property="userRole" column="user_role"/>
    resultMap>

    
    <sql id="allColumns">user_id,card_type,card_no,user_name,user_sex,user_age,user_rolesql>
    
    <select id="selectUserPage" resultMap="userMap">
        select <include refid="allColumns"/>
        from user
        <where>
            <if test="userName != null and userName != ''">
                and user_name like concat('%',#{userName},'%')
            if>
            <if test="userSex != '' and userSex != null">
                and user_sex = #{userSex}
            if>
        where>
        limit #{startRow},5
    select>
    
    <insert id="createUser" parameterType="user">
        insert into user values (#{userId},#{cardType},#{cardNo},#{userName},#{userSex},#{userAge},#{userRole})
    insert>
    
    <delete id="deleteUserById" parameterType="String">
        delete from user where user_id = #{userId}
    delete>
    
    <select id="getRowCount" resultType="Integer">
        select count(*)
        from user
        <where>
            <if test="userName != null and userName != ''">
                and user_name like concat('%',#{userName},'%')
            if>
            <if test="userSex != '' and userSex != null">
                and user_sex = #{userSex}
            if>
        where>
    select>
    
    <update id="updateUserById" parameterType="user">
        update user
        set card_type = #{cardType},card_no = #{cardNo},user_name = #{userName},user_sex = #{userSex},user_age = #{userAge},user_role = #{userRole}
        where user_id = #{userId}
    update>
mapper>

(12)新建service接口:

package com.user.service;

import com.user.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface UserService {
    /**
     * 根据条件分页获取分页数据:
     * url:
     * /user/selectUserPage?userName=z&userSex=男&page=null
     * 参数:
     * userName:表单中用户名称
     * userSex:表单中用户性别
     * page:提交的页码(第一次访问为null)
     * 结果:
     * 有数据时:
     * [{
     * "userId":"15968954638794962",
     * "cardType":"身份证",
     * "cardNo":"343343554654",
     * "userName":"撒撒旦",
     * "userSex":"女",
     * "userAge":"29",
     * "userRole":"生产、运输设备操作人员及有关人员"},
     * {...}
     * ]
     * 无数据时:
     * []
     */
    List<User> selectUserPage(String userName ,String UserSex, int startRow);

    /**
     * 增加用户:
     * url:
     * /user/createUser(参数见下面)
     * 参数:
     * cardType: this.ruleForm.cardType,//证件类型
     * cardNo: this.ruleForm.cardNo,//证件号码
     * userName: this.ruleForm.userName,//用户姓名
     * userSex: this.ruleForm.userSex,//用户性别
     * userAge: this.ruleForm.userAge,//用户年龄
     * userRole: this.ruleForm.userRole,//用户角色
     * 结果:
     * 增加成功时:
     * 1
     * 增加失败时:
     * 0
     */
    int createUser(User user);

    /**
     * 根据用户ID删除用户:
     * url:
     * /user/ deleteUserById?userId= 15968162087363060
     * 参数:
     * userId:删除用户的id
     * 结果:
     * 删除成功时:
     * 1
     * 删除失败时:
     * 0
     */
    int deleteUserById(String userId);

    /**
     * 获取总行数:
     * url:
     * /user/getRowCount?userName=z&userSex=男
     * 参数:
     * userName:表单中用户名称
     * userSex:表单中用户性别
     * 结果:
     * 有数据时:
     * 12
     * 无数据时:
     * 0
     */
    int getRowCount(String userName, String userSex);

    /**
     * 更新用户:
     * url:
     * /user/updateUserById(参数见以下)
     * 参数:
     * userId: this.ruleForm.userId,//用户 Id
     * cardType: this.ruleForm.cardType,//证件类型
     * cardNo: this.ruleForm.cardNo,//证件号码
     * userName: this.ruleForm.userName,//用户姓名
     * userSex: this.ruleForm.userSex,//用户性别
     * userAge: this.ruleForm.userAge,//用户年龄
     * userRole: this.ruleForm.userRole,//用户角色
     * 结果:
     * 成功时:
     * 1
     * 出错时:
     * 0
     */
    int updateUserById(User user);
}

(13)新建service实现类实现接口中所有功能:

package com.user.service.Impl;

import com.user.mapper.UserMapper;
import com.user.pojo.User;
import com.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {
    @Autowired//IoC
    UserMapper userMapper;//数据访问层对象
    @Override
    public List<User> selectUserPage(String userName, String userSex, int startRow) {
        return userMapper.selectUserPage(userName,userSex,startRow);
    }

    @Override
    public int createUser(User user) {
        return userMapper.createUser(user);
    }

    @Override
    public int deleteUserById(String userId) {
        return userMapper.deleteUserById(userId);
    }

    @Override
    public int getRowCount(String userName, String userSex) {
        return userMapper.getRowCount(userName,userSex);
    }

    @Override
    public int updateUserById(User user) {
        return userMapper.updateUserById(user);
    }
}

(14)新建测试类,完成所有功能的测试:

package test;

import com.user.pojo.User;
import com.user.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext_mapper.xml","classpath:applicationContext_service.xml"})
public class MyTest {
    @Autowired
    UserService userService;
    @Test
    public void testSelectUserPage(){
        List<User> list = userService.selectUserPage(null,null,5);
        list.forEach(user -> {
            System.out.println(user);
        });
    }
    @Test
    public void testDeleteUserById(){
        int num = userService.deleteUserById("15968954638794962");
        System.out.println(num);
    }
    @Test
    public void testGetRowCount(){
        int num = userService.getRowCount(null,null);
        System.out.println(num);
    }
    @Test
    public void testCreatUser(){
        User user = new User("1234567891011","身份证","13354313545","彭十六","女","23","主播");
        int num = userService.createUser(user);
        System.out.println(num);
    }
    @Test
    public void testUpdateUserById(){
        User user = new User("12345678910","身份证","13354313545","彭十五","女","23","主播");
        int num = userService.updateUserById(user);
        System.out.println(num);
    }
}

(15)新建控制器,完成所有功能:

package com.user.controller;

import com.user.pojo.User;
import com.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
//@RestController如果本类中全部是ajax请求,则使用此注解,方法上的@ResponseBody可省略
@Controller
@CrossOrigin //设置服务器端支持跨域访问
@RequestMapping("/user")
public class UserController {
    @Autowired//IoC
    UserService userService;//业务逻辑层对象

    public static final int PAGE_SIZE = 5;

    // /user/selectUserPage?userName=z&userSex=男&page=null
    @RequestMapping("/selectUserPage")//访问路径
    @ResponseBody//该注解用于解析ajax请求
    public List<User> selectUserPage(String userName,String userSex,Integer page){//自动注入
        //根据页码计算起始行
        int startRow = 0;
        if (page != null) {
            startRow = (page-1)*PAGE_SIZE;
        }
        return userService.selectUserPage(userName,userSex,startRow);
    }

    // /user/getRowCount?userName=z&userSex=男
    @RequestMapping("/getRowCount")//访问路径
    @ResponseBody//该注解用于解析ajax请求
    public int getRowCount(String userName,String userSex){//自动注入
        return userService.getRowCount(userName,userSex);
    }

    // /user/ deleteUserById?userId=15968162087363060
    @RequestMapping("/deleteUserById")//访问路径
    @ResponseBody//该注解用于解析ajax请求
    public int deleteUserById(String userId){//自动注入
        return userService.deleteUserById(userId);
    }

    // /user/createUser?cardType=a&cardNo=b&userName=c&userSex=d&userAge=e&userRole=f
    @RequestMapping("/createUser")//访问路径
    @ResponseBody//该注解用于解析ajax请求
    public int createUser(User user){//自动注入
        String uid = System.currentTimeMillis()+"";//为插入行添加不重复的主键
        user.setUserId(uid);
        return userService.createUser(user);
    }

    // /user/updateUserById?userId=x&cardType=a&cardNo=b&userName=c&userSex=d&userAge=e&userRole=f
    @RequestMapping("/updateUserById")//访问路径
    @ResponseBody//该注解用于解析ajax请求
    public int updateUserById(User user){//自动注入
        return userService.updateUserById(user);
    }
}

四、前端VUE:

1.项目结构:

(动力节点项目)SSM整合:SSM+VUE_第6张图片

2.UserHome.vue解析:


<template>
  <div>
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item>
        <el-input v-model="formInline.search1" size="mini" placeholder="输入姓名查询" v-on:input="handleSearch()">
        el-input>
      el-form-item>
      <el-form-item>
        <el-select size="mini" v-model="formInline.search2" v-on:change="handleSearch()">
          <el-option label="请选择性别" value="">el-option>
          <el-option label="" value="">el-option>
          <el-option label="" value="">el-option>
        el-select>
      el-form-item>
       <el-form-item>
        <el-button icon="el-icon-circle-plus-outline" type="text" @click="search = true">查询el-button>
      el-form-item>
      <el-form-item>
        <el-button icon="el-icon-circle-plus-outline" type="text" @click="dialogAdd = true">添加el-button>
      el-form-item>
      <el-form-item>
        <el-button icon="el-icon-delete" type="text" @click="handleDeleteList()">删除el-button>
      el-form-item>
    el-form>
    
    <el-table
      ref="multipleTable"
      :data="tableData"
      border
      highlight-current-row
      style="width: 100%"
      @selection-change="handleSelectionDelete">
      <el-table-column type="selection" width="55">el-table-column>
      <el-table-column label="用户编号">
        <template slot-scope="scope">
          <span>{{ scope.row.userId }}span>
        template>
      el-table-column>
      <el-table-column label="证件类型" prop="cardType">el-table-column>
      <el-table-column label="证件号码" prop="cardNo">el-table-column>
      <el-table-column label="用户姓名">
        <template slot-scope="scope">
          <el-popover trigger="hover" placement="right">
            <p>证件类型: {{ scope.row.cardType }}p>
            <p>证件号码: {{ scope.row.cardNo }}p>
            <p>用户姓名:{{ scope.row.userName }}p>
            <p>用户性别: {{ scope.row.userSex }}p>
            <p>用户年龄: {{ scope.row.userAge }}p>
            <p>用户角色:{{ scope.row.userRole }}p>
            <div slot="reference" class="name-wrapper">
              <el-button type="text">{{ scope.row.userName }}el-button>
            div>
          el-popover>
        template>
      el-table-column>
      <el-table-column label="用户性别" prop="userSex">el-table-column>
      <el-table-column label="用户年龄" prop="userAge">el-table-column>
      <el-table-column label="用户角色" prop="userRole">el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑el-button>
          <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">删除el-button>
        template>
      el-table-column>
    el-table>
 <el-dialog title="添加" :append-to-body='true' :visible.sync="dialogAdd" :before-close="handleClose">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px" class="demo-ruleForm" size="medium">
        <el-form-item label="证件类型">
          <el-select v-model="ruleForm.cardType" placeholder="请选择证件类型" prop="cardType">
            <el-option label="身份证" value="身份证">el-option>
            <el-option label="军官证" value="军官证">el-option>
            <el-option label="护照" value="护照">el-option>
            <el-option label="港澳居民通行证" value="港澳居民通行证">el-option>
            <el-option label="台湾往来大陆通行证" value="台湾往来大陆通行证">el-option>
          el-select>
        el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="ruleForm.cardNo">el-input>
        el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="ruleForm.userName">el-input>
        el-form-item>
        <el-form-item label="用户性别">
          <el-radio-group v-model="ruleForm.userSex">
            <el-radio label="">el-radio>
            <el-radio label="">el-radio>
          el-radio-group>
        el-form-item>
        <el-form-item label="用户年龄">
          <el-slider v-model="ruleForm.userAge" show-input>el-slider>
        el-form-item>
        <el-form-item label="用户角色">
          <el-select v-model="ruleForm.userRole" placeholder="请选择用户角色" prop="userRole">
            <el-option label="国家机关、党群组织、企业、事业单位负责人" value="国家机关、党群组织、企业、事业单位负责人">el-option>
            <el-option label="专业技术人员" value="专业技术人员">el-option>
            <el-option label="办事人员和有关人员" value="办事人员和有关人员">el-option>
            <el-option label="商业、服务业人员" value="商业、服务业人员">el-option>
            <el-option label="农、林、牧、渔、水利业生产人员" value="农、林、牧、渔、水利业生产人员">el-option>
            <el-option label="生产、运输设备操作人员及有关人员" value="生产、运输设备操作人员及有关人员">el-option>
            <el-option label="军人" value="军人">el-option>
            <el-option label="不便分类的其他从业人员" value="不便分类的其他从业人员">el-option>
            <el-option label="未知" value="未知">el-option>
          el-select>
        el-form-item>
      el-form>
        <span slot="footer" class="dialog-footer">       <el-button @click="emptyUserData()" size="medium">取 消el-button>      <el-button @click="addUser('ruleForm')" type="primary" size="medium">确 定el-button>
span>
   el-dialog>

    <el-dialog title="编辑" :append-to-body='true' :visible.sync="dialogUpdate" :before-close="handleClose">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="70px" class="demo-ruleForm" size="medium">
        <el-form-item label="证件类型">
          <el-select v-model="ruleForm.cardType" placeholder="请选择证件类型" prop="cardType">
            <el-option label="身份证" value="身份证">el-option>
            <el-option label="军官证" value="军官证">el-option>
            <el-option label="护照" value="护照">el-option>
            <el-option label="港澳居民通行证" value="港澳居民通行证">el-option>
            <el-option label="台湾往来大陆通行证" value="台湾往来大陆通行证">el-option>
          el-select>
        el-form-item>
        <el-form-item label="证件号码">
          <el-input v-model="ruleForm.cardNo">el-input>
        el-form-item>
        <el-form-item label="用户姓名">
          <el-input v-model="ruleForm.userName">el-input>
        el-form-item>
        <el-form-item label="用户性别">
          <el-radio-group v-model="ruleForm.userSex">
            <el-radio label="">el-radio>
            <el-radio label="">el-radio>
          el-radio-group>
        el-form-item>
        <el-form-item label="用户年龄">
          <el-slider v-model="ruleForm.userAge" show-input>el-slider>
        el-form-item>
        <el-form-item label="用户角色">
          <el-select v-model="ruleForm.userRole" placeholder="请选择用户角色" prop="userRole">
            <el-option label="国家机关、党群组织、企业、事业单位负责人" value="国家机关、党群组织、企业、事业单位负责人">el-option>
            <el-option label="专业技术人员" value="专业技术人员">el-option>
            <el-option label="办事人员和有关人员" value="办事人员和有关人员">el-option>
            <el-option label="商业、服务业人员" value="商业、服务业人员">el-option>
            <el-option label="农、林、牧、渔、水利业生产人员" value="农、林、牧、渔、水利业生产人员">el-option>
            <el-option label="生产、运输设备操作人员及有关人员" value="生产、运输设备操作人员及有关人员">el-option>
            <el-option label="军人" value="军人">el-option>
            <el-option label="不便分类的其他从业人员" value="不便分类的其他从业人员">el-option>
            <el-option label="未知" value="未知">el-option>
          el-select>
        el-form-item>
      el-form>
        <span slot="footer" class="dialog-footer"><el-button @click="emptyUserData()" size="medium">取 消el-button>        <el-button @click="updateUser()" type="primary" size="medium">确 定el-button>
    span>
    el-dialog>

    <br>
    
    <el-pagination
      background
      :disabled="disablePage"
      :current-page.sync="currentPage"
      small
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      @current-change="handlePageChange">
    el-pagination>
  div>
template>

<script>
/* eslint-disable */
export default {
  name: 'UserHome',
  data() {
    return {
      ruleForm: {
        userId: null,//用户id
        cardType: null,//证件类型
        cardNo: null,//证件号码
        userName: null,//用户姓名
        userSex: null,//用户性别
        userAge: 25,//用户年龄
        userRole: null//用户角色
      },
      rules: {},
      tableData: [],
      formInline:{
        search1: '',
        search2: ''
      },
      dialogAdd: false,
      dialogUpdate: false,
      pageSize: 5,
      currentPage: 1,
      total: 0,
      disablePage: false,
      multipleSelection: []
    };
  },

  created() {
    this.handlePageChange();//分页
    this.getRowCount();//计算总行数
  },

  methods: {
    /**
     * 分页
     */
    handlePageChange() {
      let postData=this.qs.stringify({//构建json对象,属性为page、userName、userSex,用于封装要提交的数据
        page:this.currentPage,
        userName:this.formInline.search1,
        userSex:this.formInline.search2
      });
      this.$axios({//异步跨域ajax请求
        method:'post',//请求提交方式
        url:'/api/user/selectUserPage',//请求URL
        data:postData//携带的json数据:{"page":1,"userName":"","userSex":""}
      }).then(response=>{//成功后进入到这里,response是响应对象
        this.tableData=response.data;//数据绑定,返回的5个用户的json数据,将数据显示到表格上
      }).catch(error=>{
        console.log(error);//出错了进入到这里
      })
    },

    /**
     * 统计用户个数
     */
    getRowCount() {
      let postData=this.qs.stringify({
        userName:this.formInline.search1,
        userSex:this.formInline.search2
      });
      this.$axios({
        method:'post',
        url:'/api/user/getRowCount',
        data:postData//返回的总行数赋值给变量total
      }).then(response=>{
        this.total=response.data;
      }).catch(error=>{
        console.log(error);
      })
    },

    /**
     * 添加用户
     */
    addUser() {
      if (this.ruleForm.cardType == null || this.ruleForm.cardNo == null || this.ruleForm.userName == null || this.ruleForm.userSex == null || this.ruleForm.userRole == null) {
        this.$alert('用户信息不完整请检查', '温馨提示', {
          confirmButtonText: '确定'
        });
        return;
      }
      let postData = this.qs.stringify({
        cardType: this.ruleForm.cardType,//证件类型
        cardNo: this.ruleForm.cardNo,//证件号码
        userName: this.ruleForm.userName,//用户姓名
        userSex: this.ruleForm.userSex,//用户性别
        userAge: this.ruleForm.userAge,//用户年龄
        userRole: this.ruleForm.userRole,//用户角色
      });
      this.$axios({
        method:'post',
        url:'/api/user/createUser',
        data:postData
      }).then(response=>{
        this.handlePageChange();
        this.getRowCount();
        this.$message({
          type: 'success',
          message: '已添加!'
        });
        this.emptyUserData();
      }).catch(error=>{
        console.log(error);
      })
    },

    search(){
      this.handlePageChange();
      this.getRowCount();
    },

    handleSearch() {
      this.handlePageChange();
      this.getRowCount();
    },

    handleEdit(index, row) {
      this.dialogUpdate = true;
      row.userAge = Number(row.userAge);
      this.ruleForm = Object.assign({}, row, index); //点击更新按钮将用户数据回填到对话框,方便用户更新信息,关键!!!
    },

    handleClose(done) {
      this.$confirm('确认关闭?')
        .then(_ => {
          done();
          this.emptyUserData();
        })
        .catch(_ => {
        });
    },

    /**
     * 清空绑定数据
     */
    emptyUserData() {
      this.dialogAdd = false;
      this.dialogUpdate = false;
      this.ruleForm = {
        userId: null,//用户id
        cardType: null,//证件类型
        cardNo: null,//证件号码
        userName: null,//用户姓名
        userSex: null,//用户性别
        userAge: 25,//用户年龄
        userRole: null//用户角色
      };
    },

    /**
     * 根据 userId 删除用户
     * @param index
     * @param row
     */
    handleDelete(index, row) {//index是该行所在下标,row是行中所有数据
      //console.log(index, row);
      //弹出提示框,让用户确定是否删除
      this.$confirm('删除操作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'//黄色的警告图标
      }).then(() => {//用户点击确定后进入到这里
        let postData = this.qs.stringify({
          userId: row.userId,
        });
        this.$axios({//点击确定后发出跨域访问的请求,后端进行删除操作
          method: 'post',
          url: '/api/user/deleteUserById',
          data: postData
        }).then(response => {//跨域请求成功后进入这里,此时后端已删除成功
          this.getRowCount();//计算删除后的总行数,进行分页插件的页码变化
          if (this.total % 5 == 1 && this.currentPage >= 1) {
            if (this.total / 5 < this.currentPage) {
              this.currentPage = this.currentPage - 1;
            }
          }
          this.handlePageChange();//删除后重新分页

          this.$message({//删除成功后弹框
            type: 'success',
            message: '删除成功!'
          });
          //console.log(response);
        }).catch(error => {
          console.log(error);
        });

      }).catch(() => {
        this.$message({//用户点击取消后进入到这里
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    
    handleSelectionDelete(val) {
      this.multipleSelection = val;
    },

    /**
     * 根据 userId 批量删除用户
     */
    handleDeleteList() {
      let userIds = "";
      this.multipleSelection.forEach(item => {
        userIds += item.userId + ',';
      })
      console.log(userIds);
      // let userIds= this.multipleSelection.map(item => item.userId).join()

      this.$confirm('删除操作, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let postData = this.qs.stringify({
          userIdList: userIds
        });
        console.log(postData);
        this.$axios({
          method: 'post',
          url: '/api/user/deleteUserByIdList',
          data: postData
        }).then(response => {
          this.getRowCount();
          if (this.total % 5 == 1 && this.currentPage >= 1) {
            if (this.total / 5 < this.currentPage) {
              this.currentPage = this.currentPage - 1;
            }
          }
          this.handlePageChange();

          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          //console.log(response);
        }).catch(error => {
          console.log(error);
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


    updateUser() {
      if (this.ruleForm.cardType == null || this.ruleForm.cardNo == null || this.ruleForm.userName == null || this.ruleForm.userSex == null || this.ruleForm.userRole == null) {
        this.$alert('用户信息不完整请检查', '温馨提示', {
          confirmButtonText: '确定'
        });
        return;
      }
      let postData = this.qs.stringify({
        userId: this.ruleForm.userId,//用户 Id
        cardType: this.ruleForm.cardType,//证件类型
        cardNo: this.ruleForm.cardNo,//证件号码
        userName: this.ruleForm.userName,//用户姓名
        userSex: this.ruleForm.userSex,//用户性别
        userAge: this.ruleForm.userAge,//用户年龄
        userRole: this.ruleForm.userRole,//用户角色
      });
      this.$axios({
        method: 'post',
        url: '/api/user/updateUserById',
        data: postData
      }).then(response => {
        this.handlePageChange();
        this.getRowCount();
        this.$message({
          type: 'success',
          message: '已编辑!'
        });
        this.emptyUserData();
        console.log(response);
      }).catch(error => {
        console.log(error);
      });
    }
  },

}
/* eslint-disable */
script>
<style scoped>
style>

五、附件:后端接口文档:

(动力节点项目)SSM整合:SSM+VUE_第7张图片

你可能感兴趣的:(SpringMVC,mvc,spring,ssm,vue,mybatis)