Vue + Spring Boot 例子

后端构建

 UserController



import com.aaa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserRepository userRepository ;

    @GetMapping("/findAll")
    @CrossOrigin
    public List<User> findAll(){
        return userRepository.findAll();
    }

    @GetMapping("/findById/{id}")
    @CrossOrigin
    public User findById(@PathVariable("id") Integer id){
        return userRepository.findById(id);
    }
    @PostMapping("/save")
    @CrossOrigin
    public void save(@RequestBody User user){
        userRepository.save(user);

    }

    @PutMapping("/update")
    @CrossOrigin
    public void update(@RequestBody User user){
        userRepository.update(user);

    }
    @GetMapping("/delete/{id}")
    @CrossOrigin
    public void delete(@PathVariable("id") Integer id){
        userRepository.delete(id);

    }
}

实体类



import lombok.Data;

import java.util.Date;
@Data
public class User {
    private Integer id ;
    private String name ;
    private String password;
    private Double score ;
    private Date birthday ;
}

跨域处理



import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*",filterName = "handerFilter")
public class HanderFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response= (HttpServletResponse)servletResponse;
        HttpServletRequest request =(HttpServletRequest) servletRequest ;
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin",request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE");
        response.setHeader("Access-Control-Allow-Max-Age","0");
        response.setHeader("Access-Control-Allow-Headers","Origin,No-Cache, X-Requested-With,If-Modified-Since,Last-Modified,Cache-Control ,Expiress," +
                           "Content-Type,X-E4M-With,token");
        response.setHeader("Access-Control-Allow-Credentials","true");
        filterChain.doFilter(request,response);

    }

    @Override
    public void destroy() {

    }
}

Mybatis 接口


import com.aaa.entity.User;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public interface UserRepository {
    public List<User> findAll();

    public User findById(Integer id);

    public void  save(User user);

    public void delete(int id);

    public void update(User user);
}

运行文件



import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.wujun.repository")
public class application {
    public static void main(String[] args) {
        SpringApplication.run(application.class ,args);
    }
}

Mybatis接口xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aaa.repository.UserRepository">



    <select id="findAll" resultType="com.aaa.entity.User">
        select * from user
    </select>


    <select id="findById" parameterType="java.lang.Integer" resultType="com.aaa.entity.User">
        select * from user where id=#{id}
    </select>


    <insert id="save" parameterType="com.aaa.entity.User">
        insert into user (name, password, score, birthday)
        VALUES(#{name},#{password},#{score},#{birthday})

    </insert>

    <update id="update" parameterType="com.aaa.entity.User">
        update user set name = #{name} ,password = #{password}
        ,score = #{score},birthday = #{birthday}
        where id = #{id}
    </update>
    <delete id="delete" parameterType="java.lang.Integer">
        delete from user where id=#{id}
    </delete>
</mapper>

配置文件(yml)

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useSSL=true&useUnicode=true&serverTimezone=UTC&characterEncoding=utf8&rewriteBatchedStatements=true
    password: 342901
    username: root
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath:/mapper/*xml

  #提前包名
server:
  port: 8081

依赖文件

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>

    <groupId>com.aaa</groupId>
    <artifactId>bloodend</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.1.5.RELEASE</version>
    </parent>
    <dependencies>
        <!--   web 启动 jar-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.6</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.18</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

Vue 前端文件

Index

<template>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column
      fixed
      prop="id"
      label="编号"
      width="150">
    </el-table-column>
    <el-table-column
      prop="name"
      label="姓名"
      width="120">
    </el-table-column>
    <el-table-column
      prop="password"
      label="密码"
      width="120">
    </el-table-column>
    <el-table-column
      prop="score"
      label="分数"
      width="120">
    </el-table-column>
    <el-table-column
      prop="birthday"
      label="生日"
      width="300">
    </el-table-column>
    <el-table-column
      prop="zip"
      label="邮编"
      width="120">
    </el-table-column>

<!-- 操作按钮 -->
    <el-table-column
      fixed="right"
      label="操作"
      width="300">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete( scope.row)">删除</el-button>
      </template>
    </el-table-column>


  
  </el-table>
</template>


<script>
export default {
    name:'FindAll',
    methods:{
      
      handleEdit(row){
       this.$router.push({ name: 'update', params: { id: row.id ,name: row.name,score:row.score ,password:row.password ,birthday:row.birthday } })
      }
    
    ,
      handleDelete(row){
        let _this = this ;
        this.$confirm('是否删除用户'+row.name, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.get('http://localhost:8081//user/delete/'+row.id).then(function(resp){
            if(resp){
              _this.$alert(row.name+'删除成功', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                location.reload()
                // this.$message({
                //   type: 'info',
                //   message: `action: ${ action }`
                // });
          }
        });
             
            }
          })
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    },
    created(){
      let _this = this ;
      axios.get('http://localhost:8081/user/findAll').then(function (resp) {
          console.log(resp.data)
          _this.tableData = resp.data
      })
      // axios.get('http://localhost:8081/user/findAll').then(function (resp) {
      //     console.log(resp.data)
      //     _this.tableData = resp.data
      // })
    }
    ,
    

    data() {
      return {
        tableData:[]
      }
    }

}

</script>

<style>

</style>

update

<template>
<div style="width:300px">
    <el-form ref="form" :model="sizeForm" label-width="80px" size="mini">
        <el-form-item label="id">
            <el-input v-model="sizeForm.id" readonly></el-input>
        </el-form-item>

        <el-form-item label="name">
            <el-input v-model="sizeForm.name"></el-input>
        </el-form-item>

        <el-form-item label="密码">
            <el-input v-model="sizeForm.password"></el-input>
        </el-form-item>
          
        <el-form-item label="分数">
            <el-input v-model="sizeForm.score"></el-input>
        </el-form-item>

        <el-form-item label="生日">
            <el-input v-model="sizeForm.birthday"></el-input>
        </el-form-item>
 
  <el-form-item size="large">
    <el-button type="primary" @click="onSubmit()">立即创建</el-button>
    <el-button>取消</el-button>
  </el-form-item>
</el-form>
</div>
</template>

<script>
import Vue from 'vue';
export default {
    name: 'update',
    
    created(){
        let _this = this
        this.$route.params.id
        this.sizeForm=this.$route.params;
        
        
        console.log(this.$route.params)
        
       
    },
    data() {
      return {
        sizeForm: {
          id: '',//this.$route.params.id,
          name:'',// this.$route.params.name,
          password: '',//this.$route.params.password,
          score:'',// this.$route.params.score,
          birthday:'',//this.$route.params.birthday
        }
      };
    },
    methods: {
      onSubmit(){
        let _this = this
        this.$route.params.id
        this.sizeForm=this.$route.params;
        
        
        console.log(' onSubmit()')
        console.log(this.sizeForm)
         axios.put('http://localhost:8081/user/update',this.$route.params).then(function(resp){
            if(resp){
              _this.$alert('修改成功', '提示', {
              confirmButtonText: '确定',
              callback: action => {
              location.href="./Index"; 
                // this.$message({
                //   type: 'info',
                //   message: `action: ${ action }`
                // });
          }
        });
             
            }
          })
        
      }
    }

}
</script>

<style>

</style>

在点击事件方法处理上不够完美

 onSubmit(){
        let _this = this
        this.$route.params.id
        this.sizeForm=this.$route.params;
        
        
        console.log(' onSubmit()')
        console.log(this.sizeForm)
         axios.put('http://localhost:8081/user/update',this.$route.params).then(function(resp){
            if(resp){
              _this.$alert('修改成功', '提示', {
              confirmButtonText: '确定',
              callback: action => {
              location.href="./Index"; 
                );
          }
        });
             
            }
          })
        
      }

添加 Add.vue

<template>
  <el-table :data="tableData" border style="width: 100%">
    <el-table-column
      fixed
      prop="id"
      label="编号"
      width="150">
    </el-table-column>
    <el-table-column
      prop="name"
      label="姓名"
      width="120">
    </el-table-column>
    <el-table-column
      prop="password"
      label="密码"
      width="120">
    </el-table-column>
    <el-table-column
      prop="score"
      label="分数"
      width="120">
    </el-table-column>
    <el-table-column
      prop="birthday"
      label="生日"
      width="300">
    </el-table-column>
    <el-table-column
      prop="zip"
      label="邮编"
      width="120">
    </el-table-column>

<!-- 操作按钮 -->
    <el-table-column
      fixed="right"
      label="操作"
      width="300">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete( scope.row)">删除</el-button>
      </template>
    </el-table-column>


  
  </el-table>
</template>


<script>
export default {
    name:'FindAll',
    methods:{
      
      handleEdit(row){
       this.$router.push({ name: 'update', params: { id: row.id ,name: row.name,score:row.score ,password:row.password ,birthday:row.birthday } })
      }
    
    ,
      handleDelete(row){
        let _this = this ;
        this.$confirm('是否删除用户'+row.name, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          axios.get('http://localhost:8081//user/delete/'+row.id).then(function(resp){
            if(resp){
              _this.$alert(row.name+'删除成功', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                location.reload()
                // this.$message({
                //   type: 'info',
                //   message: `action: ${ action }`
                // });
          }
        });
             
            }
          })
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    },
    created(){
      let _this = this ;
      axios.get('http://localhost:8081/user/findAll').then(function (resp) {
          console.log(resp.data)
          _this.tableData = resp.data
      })
      // axios.get('http://localhost:8081/user/findAll').then(function (resp) {
      //     console.log(resp.data)
      //     _this.tableData = resp.data
      // })
    }
    ,
    

    data() {
      return {
        tableData:[]
      }
    }

}

</script>

<style>

</style>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值