创建项目的目录结构

2.在pom.xml中导入依赖

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <maven.compiler.source>1.8</maven.compiler.source>
  <maven.compiler.target>1.8</maven.compiler.target>
  <spring.version>5.0.2.RELEASE</spring.version>
  <slf4j.version>1.6.6</slf4j.version>
  <log4j.version>1.2.12</log4j.version>
  <mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies> <!-- spring -->
  <dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.8</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${spring.version}</version>
  </dependency>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
  </dependency>
  <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
  </dependency> <!-- log start -->
  <dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>${log4j.version}</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j.version}</version>
  </dependency> <!-- log end -->
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>${mybatis.version}</version>
  </dependency>
  <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>1.3.0</version>
  </dependency>
  <dependency>
    <groupId>c3p0</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.1.2</version>
  </dependency>
  <dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
  </dependency>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.5</version>
  </dependency>
  <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>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
        <scope>compile</scope>
    </dependency>
</dependencies>

2.创建如下的数据库表结构

3.编写jdbc.properties

jdbc_driver=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/vuejsdemo
jdbc_user=root
jdbc_password=123

4.编写Spring的配置文件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"
       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
       http://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 http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--配置包扫描-->
    <context:component-scan base-package="com.bianyiit">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--引入外部properties-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
    <!--数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc_driver}"></property>
        <property name="jdbcUrl" value="${jdbc_url}"></property>
        <property name="user" value="${jdbc_user}"></property>
        <property name="password" value="${jdbc_password}"></property>
    </bean>
    <!--配置平台事务管理器-->
    <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务的通知-->
    <tx:advice transaction-manager="dataSourceTransactionManager" id="txAdvice">
        <tx:attributes>
            <tx:method name="findAll*" read-only="true" propagation="SUPPORTS"/>
            <tx:method name="*" read-only="false" propagation="REQUIRED"></tx:method>
        </tx:attributes>
    </tx:advice>
    <!--配置aop对于事务的支持-->
    <aop:config>
        <aop:pointcut id="pointCut1" expression="execution(* com.bianyiit.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointCut1"></aop:advisor>
    </aop:config>
    <!--spring整合mybatis-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置mapper的扫描器-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bianyiit.dao"></property>
    </bean>
</beans>

5.编写SpringMVC的配置文件springmvc.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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--配置包扫描-->
    <context:component-scan base-package="com.bianyiit">
        <!-- 制定扫包规则 ,只扫描使用@Controller注解的JAVA 类 -->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--处理静态资源-->
    <mvc:default-servlet-handler></mvc:default-servlet-handler>

    <!--开启注解对于web层的支持-->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>

6.编写webapp/WEB-INF目录结构下的web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--配置全局变量-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!--配置编码过滤器-->
  <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>
  <!--配置监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--配置前端控制器-->
  <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>
    <!--设置在服务器启动的时候加载springmvc配置文件-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!--配置前端过滤的静态资源-->
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

7.编写User实体类

package com.bianyiit.pojo;

import lombok.Data;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@Data
@Component
public class User implements Serializable {
    private static final long serialVersionUID = 439703552941380951L;
    private Integer id;
    private String username;
    private String password;
    private Integer age;
    private String sex;
    private String email;
}

8.编写后台UserController

package com.bianyiit.web;

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

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/findAll.do")
    public List<User> findAll(){
        return userService.findAll();
    }

    @RequestMapping("/findUserById.do")
    public User findUserById(Integer id){
        return userService.findUserById(id);
    }

    @RequestMapping("/updateUser.do")
    public void updateUser(@RequestBody User user){
        userService.updateUser(user);
    }
}

9.编写UserService接口和UserServiceImpl实现类

package com.bianyiit.service;

import com.bianyiit.pojo.User;

import java.util.List;

public interface UserService {
    /**
     * 查询所有用户信息
     * @return 包含所有User对象的list集合
     */
    List<User> findAll();

    /**
     * 根据id查询单个用户
     * @param id
     * @return User对象
     */
    User findUserById(Integer id);

    /**
     * 更新用户信息
     * @param user
     */
    void updateUser(User user);
}
package com.bianyiit.service.impl;

import com.bianyiit.dao.UserDao;
import com.bianyiit.pojo.User;
import com.bianyiit.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
    private UserDao userDao;

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }

    @Override
    public User findUserById(Integer id) {
        return userDao.findUserById(id);
    }

    @Override
    public void updateUser(User user) {
        userDao.updateUser(user);
    }
}

10.编写UserDao接口,使用Mybatis注解

package com.bianyiit.dao;

import com.bianyiit.pojo.User;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface UserDao {

    @Select("select * from user")
    List<User> findAll();

    @Select("select * from user where id=#{id}")
    User findUserById(Integer id);

    @Update("update user set username=#{username},password=#{password},age=#{age},sex=#{sex},email=#{email} where id=#{id}")
    void updateUser(User user);
}

11.在test包下创建UserControllerTest测试类,测试后台代码是否有误

package com.bianyiit.test;

import com.bianyiit.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;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class UserControllerTest {

    @Autowired
    private UserService userService;

    @Test
    public void testUser(){
        System.out.println(userService.findUserById(1));
    }
}

12.测试结果:后台代码编写无误

13.编写前台html代码

<script src="./js/vuejs-2.5.16.js"></script>
<script src="./js/axios-0.18.0.js"></script>
<script src="./js/user.js"></script>
<!--数据列表-->
<table id="dataList0" class="table table-bordered table-striped table-hover dataTable">
   <thead>
       <tr>
           <th class="">ID</th>
           <th class="">姓名</th>
           <th class="">密码</th>
           <th class="">年龄</th>
           <th class="">性别</th>
           <th class="">邮箱</th>
           <th class="text-center">操作</th>
       </tr>
   </thead>
   <tbody>
       <tr v-for="user in userList">
           <td>{{user.id}}</td>
           <td>{{user.username}}</td>
           <td>{{user.password}}</td>
           <td>{{user.age}}</td>
           <td>{{user.sex}}</td>
           <td>{{user.email}}</td>
           <td class="text-center">
               <button type="button" class="btn bg-olive btn-xs">详情</button>
               <button type="button" class="btn bg-olive btn-xs" @click="findUserById(user.id)">编辑</button>
           </td>
       </tr>
       <!--模态窗口-->
       <div class="tab-pane" id="tab-model">
           <div id="myModal" class="modal modal-primary" role="dialog">
               <div class="modal-dialog modal-lg">
                   <div class="modal-content">
                       <div class="modal-header">
                           <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                               <span aria-hidden="true">&times;</span></button>
                           <h4 class="modal-title">用户信息</h4>
                       </div>
                       <div class="modal-body">
                           <div class="box-body">
                               <div class="form-horizontal">
                                   <div class="form-group">
                                       <label class="col-sm-2 control-label">用户名:</label>
                                       <div class="col-sm-5">
                                           <input type="text" class="form-control" v-model="user.username">
                                       </div>
                                   </div>
                                   <div class="form-group">
                                       <label class="col-sm-2 control-label">密码:</label>
                                       <div class="col-sm-5">
                                           <input type="text" class="form-control" v-model="user.password">
                                       </div>
                                   </div>
                                   <div class="form-group">
                                       <label class="col-sm-2 control-label">性别:</label>
                                       <div class="col-sm-5">
                                           <input type="text" class="form-control" v-model="user.sex">
                                       </div>
                                   </div>
                                   <div class="form-group">
                                       <label class="col-sm-2 control-label">年龄:</label>
                                       <div class="col-sm-5">
                                           <input type="text" class="form-control" v-model="user.age">
                                       </div>
                                   </div>
                                   <div class="form-group">
                                       <label class="col-sm-2 control-label">邮箱:</label>
                                       <div class="col-sm-5">
                                           <input type="text" class="form-control" v-model="user.email">
                                       </div>
                                   </div>
                               </div>
                           </div>
                       </div>
                       <div class="modal-footer">
                           <button type="button" class="btn btn-outline" data-dismiss="modal">关闭</button>
                           <button type="button" class="btn btn-outline" data-dismiss="modal" @click="update">修改</button>
                       </div>
                   </div>
                   <!-- /.modal-content -->
               </div>
               <!-- /.modal-dialog -->
           </div>
           <!-- /.modal -->
       </div>
       <!--模态窗口/-->
   </tbody>
</table>

14.编写user.js代码

var vue=new Vue({
    el:"#app",
    data:{
            user:{id:"",username:"",password:"",age:"",sex:"",email:""},
            userList:[]
    },
    methods:{
        findAll:function () {
            var _this=this;
            axios.get("/user/findAll.do").then(function (responese) {
                /*将响应回来的数据绑定到data中*/
                _this.userList=responese.data;
                console.log(responese)
            }).catch(function (error) {
                alert("查询数据失败")
            })
        },
        findUserById:function(userid){
            var _this=this;
            axios.get("/user/findUserById.do",{
                params:{
                    id:userid
                }
            }).then(function (response) {
                _this.user=response.data;
                $('#myModal').modal("show")
            }).catch(function (error) {
                alert("findUserById失败!!")
            })
        },
        update:function(){
            var _this = this;
            axios.post("/user/updateUser.do",_this.user).then(function(response){
                // 响应成功  重新的调用findAll方法,将修改之后的数据重新加载
                _this.findAll();
            }).catch(function(){

            })
        }
    },
    //通过vue生命周期的钩子函数来触发findAll方法
    created(){
        this.findAll();
    }
})

15.测试是否能够完成查询和修改操作

点击编辑按钮弹出模态框,通过v-model绑定user对象的属性

更改模态框中的用户信息
在这里插入图片描述
点击修改之后

16.注意事项

1.html乱码问题解决方案:打开webapp/WEB-INF/的web.xml

2.我们在applicationContext.xml中配置了事务管理,通过如下方式配置的事务管理不需要我们在UserServiceImpl中写任何注解就可以实现对事务的管理(当我们在更新用户操作之后手动写一个异常,此时数据库的数据不会发送变化)

3.上面的代码等同于下面的代码


4.一定要在html中要引入两个js文件

5.我们在vue中接收到的成功的数据如下所示,而我们要用的是它下面的data中的值

6.如果需要源代码的小伙伴们,可以在下方百度网盘中下载

链接:https://pan.baidu.com/s/1KmSFLN5zcQse8uoR42WkCg 
提取码:jcth 
复制这段内容后打开百度网盘手机App,操作更方便哦

17.批量删除操作


18.添加操作

Logo

前往低代码交流专区

更多推荐