Addition, deletion, modification and query of SpringBoot + Vue simple front-end and back-end separation projects

SpringBoot is a way to provide a fast integration


Preparation

new database

drop table if exists emp;

create table emp
(
    empno int primary key auto_increment,
    ename varchar(20),
    job   varchar(9),
    hiredate date,
    sal  double
);

New Project

Create a new SpringBoot project, here is the third one , after the project is built, check the Application under the main/java folder

@SpringBootApplication: main startup class

Equivalent to @Configurationthe configuration class, @EnableAutoConfigurationenabling automatic configuration, and @CommponentScancomponent scanning (by default, the package and subpackages of the main startup class are scanned)

In the main startup class, two annotations need to be added above the class

@MapperScan("com.ssm.mapper") //mapper包的限定名
@EnableTransactionManagement  //开启事务管理

提示:以下是本篇文章正文内容,下面案例可供参考

config configuration package

MvcConfig class

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
public class MvcConfig implements WebMvcConfigurer {
    
    
 
	 /**
     * 跨域访问设置
     */
    public void addCorsMappings(CorsRegistry registry) {
    
    
       registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods(new String[]{
    
    "GET", "POST", "PUT", "DELETE"})
                .allowedHeaders("*")
                .exposedHeaders("*");
    }
 
}

application.yml

Rename it application.propertiesto:application.yml

server:
  port: 1234   # 配置内嵌Tomcat端口号
  servlet:      
    context-path: /ssm   # 配置应用名


# 配置数据库    
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver # mysql驱动程序类名 8-com.mysql.cj.jdbc.Driver 5-com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
    
# 配置日志输出级别    
logging:
  level:
    # 项目包名
    com.ssm: debug  

# 配置mybatis实体类的别名包
mybatis:
  type-aliases-package: com.ssm.po

Backend business development

Po class

@Data: Automatically generate Getter, Setter, and toString by
@AllArgsConstructordefault : Generate constructors with parameters by default (both are added when parameters are required)
There are no-parameters by default in the project
@NoArgsConstructor: Generate constructors without parameters by default

import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data  // 默认自动生成Getter、Setter、toString
// 需要有参的就加下面两个注解,因为默认就有无参的
@AllArgsConstructor // 默认生成有参构造方法
@NoArgsConstructor  // 默认生成无参构造方法
public class Emp {
    
    
	private Integer empno;
	private String ename;
	private String job;
	@JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8")
	private Date hiredate;
	private Double sal;
	
}

mapper interface

The parameters used for addition and modification are entity classes, and the deletion and id queries are used to int 主键
query all data and use List
simple sentences to write annotations:

@Mapper
public interface EmpMapper {
    
    
	// 主键自增,这里不用写
	@Insert("insert into emp (ename,job,hiredate,sal) values(#{ename},#{job},#{hiredate},#{sal})")
	int insert(Emp emp);
	
	@Delete("delete from emp where empno=#{no}")
	int delete(int empno);
	
	@Update("update emp set ename=#{ename},job=#{job},hiredate=#{hiredate},sal=#{sal} where empno=#{empno}")
	int update(Emp emp);
	// 查询所有数据的时候,把所有属性都写出来
	@Select("select empno,ename,job,hiredate,sal from emp")
	List<Emp> queryAllEmps();
	
}

service interface

public interface EmpService {
    
    
	
	String insert(Emp emp);
	String delete(int empno);
	String update(Emp emp);
	List<Emp> queryAllEmps();
}

service implementation class

@Service
public class EmpServiceImpl implements EmpService{
    
    
	// 添加依赖注入的注解
	@Autowired
	// 依赖关系,service依赖mapper
	private EmpMapper mapper;
	
	@Override
	public String insert(Emp emp) {
    
    
		// 添加未实现的方法
		return mapper.insert(emp)>0?"增加员工数据成功":"增加员工数据失败";
	}

	@Override    // int类型可以随意起名,这里是主键方便区分
	public String delete(int empno) {
    
    
		return mapper.delete(empno)>0?"删除员工数据成功":"删除员工数据失败";
	}

	@Override
	public String update(Emp emp) {
    
    
		return mapper.update(emp)>0?"修改员工数据成功":"修改员工数据失败";
	}

	@Override
	public List<Emp> queryAllEmps() {
    
    
		return mapper.queryAllEmps();
	}

}

controller class

reststyle based

@RequestBodyAnnotation function: Prompt that the request data format sent by the SpringMVC framework client is JSON,
@PathVariable("主键")indicating that the primary key parameter in the request path is obtained and bound to the primary key parameter of the method.

@RestController
@RequestMapping("/emp")
public class EmpController {
    
    
	@Autowired
	// controller依赖service接口
	private EmpService service;
	
	@PostMapping
	// @RequestBody注解作用:提示SpringMVC框架客户端发送的请求数据格式是JSON
	public String add(@RequestBody Emp emp) {
    
    
		// 返回service处理的结果
		return service.insert(emp);
	}
	
	@DeleteMapping("/{empno}")
	public String delete(@PathVariable("empno")int empno) {
    
    
		return service.delete(empno);
	}
	
	@PutMapping
	public String update(@RequestBody Emp emp) {
    
    
		return service.update(emp);
	}
	
	@GetMapping
	public List<Emp> query(){
    
    
		return service.queryAllEmps();
	}
}

test

Right-click the main startup class in the backend program to start the Spring Boot App

Add data test

POST request
Please add a picture description
Back to the database, you can see that a piece of data has been added

delete data test

DELETE method, the link is followed by the primary key.
insert image description here
Back to the database, you can see that the No. 2 data is deleted

Modify data test

The value in the PUT request
Headers is not deleted, and the primary key to be modified and the corresponding data to be modified are added to the Body
insert image description here

Go back to the database and you can see that the No. 1 data has been modified

Check new data test

GET request
insert image description here

Front-end page development

Delete useless code after vue creates a new project

Add, modify, and query views

Next, configure routing in the index.js file

import Query from '@/views/Query'
import Add from '@/views/Add'
import Update from '@/views/Update'

const routes = [
  {
    
    
    path:'/',
    name:'query',
    component:Query
  },
  {
    
    
    path:'/add',
    name:'add',
    component:Add
  },
  {
    
    
    path:'/update',
    name:'update',
    component:Update
  }
]

query page

in query view

Add instructions and interpolation syntax @click=" "
to the data table when you see the buttonvfor

<template>
  <div>
    <button @click="query">查询</button>
    <button @click="goAdd">增加</button>
    <table>
        <tr>
            <th>员工编号</th>
            <th>员工姓名</th>
            <th>员工岗位</th>
            <th>入职日期</th>
            <th>员工工资</th>
            <th>修改</th>
            <th>删除</th>
        </tr>
        <tr v-for="(item, index) in items" :key="index">
            <th>{
   
   { item.empno }}</th>
            <th>{
   
   { item.ename }}</th>
            <th>{
   
   { item.job }}</th>
            <th>{
   
   { item.hiredate }}</th>
            <th>{
   
   { item.sal }}</th>
            <th><button @click="goUpdate(index)">修改</button></th>
            <th><button @click="del(index)">删除</button></th>
        </tr>
    </table>
  </div>
</template>

Next, the data is now configured: vforin the commanditems

  data () {
    
    
    return {
    
    
        items:[]
    }
  },

Next, the focus is on the method. All the data needs to be connected, and the front and back ends must be connected, and the Ajax library should be imported.axios

import axios from 'axios'

methodsConfigure the query method inside

    query(){
    
    
        axios.get('http://localhost:1234/ssm/emp')
        
    },

Because deletion, addition, and modification require requests, the address is http://localhost:1234/ssm/emp, which is a bit troublesome

Next configure a proxy server to simplify the path

vue.config.jsConfigure in the last file of the project :

// 最后一行})前回车,前面代码后加逗号
devServer: {
    
    
     proxy:{
    
    
       '/api':{
    
    
         //target: 'http://localhost',
         //target: 'http://localhost:端口号/后端文件名/'
         target: 'http://localhost:1234/ssm/',
         ws: true,
         changeOrigin: true,
         pathRewrite: {
    
    
           '^/api': ''
         }
       }
     }
   }

/apiThis path can be replaced by sending a request later

Follow the path .then(), add an arrow function inside, write the response (resp) inside, and write the assignment at the end

So the path and code of the final query view:

    query(){
    
    
        axios.get('/api/emp')
        .then((resp)=> {
    
    
            this.items = resp.data
        })
    },

Start the project: click to inquire
insert image description here

delete function

in the query view

Copy the method in the delete button above and add it to methodsthe method:

send request directly

// i代表数组下标
    del(i){
    
    
        axios.delete(`/api/emp/${
      
      this.items[i].empno}`)
        .then( (resp)=>{
    
    
            alert(resp.data)
            // 删完后查询一下
            this.query()
        })
    },

Please add a picture description

add page

First, add the added method to the home view for jumping

No need to pass parameters, only the path to jump

    goAdd(){
    
    
        this.$router.push('/add')
    },

At this time, you can jump, but the big white screen

inside add view

<template>
  <div>
    员工姓名:<input type="text" v-model="emp.ename"> <br>
    员工岗位:<input type="text" v-model="emp.job"> <br>
    入职日期:<input type="date" v-model="emp.hiredate"> <br>
    员工工资:<input type="number" v-model="emp.sal"> <br>
    <button @click="add">提交</button>
  </div>
</template>

import firstaxios

import axios from 'axios'

dataIn the data:

  data () {
    
    
    return {
    
    
        emp:{
    
    
            ename: '',
            job: '',
            hiredate: '',
            sal: ''
        }
    }
  },

Finally add methodsthe method

  methods: {
    
    
    add(){
    
    
    // 增加post请求,方法里面两个参,一个地址一个数据
        axios.post('/api/emp',this.emp)
        // 响应
        .then( (resp)=>{
    
    
        // 弹窗
            alert(resp.data)
        })
    }
  },

Click Add on the query page:
insert image description here

edit page

methodsAdd the modification method to the method in the query view

Session parameter passing method:

    goUpdate(i){
    
    
    					//起个名字,数组数据用JSON格式格式化一下
        sessionStorage.setItem('emp',JSON.stringify(this.items[i]))
        // 跳转
        this.$router.push('/update')
    }

Inside the modify view:

Modifying the code structure is basically the same as adding, here you can directly copy the added code, and then modify part of the code

If you modify it, you need to specify the number, but the number cannot be modified (the setting is read-only)

<input type="text" v-model="emp.empno" readonly> <br>

Then modify the method name of the button

<button @click="update">修改</button>

If you modify it, you need to take the data of the previous session out of the hook function

    mounted () {
    
    
      // 按照名字取出数据
        let s = sessionStorage.getItem('emp')
      // 恢复成对象形式,再赋值给emp表
        this.emp = JSON.parse(s)
    }

methodsThe modification method name (update) and request type in the method need to be changed (put)

    methods: {
    
    
        update(){
    
    
          axios.put('/api/emp',this.emp)
          .then( (resp)=>{
    
    
              alert(resp.data)
          })
      }
    },

The complete code of the last modified view:

<template>
    <div>
      <input type="text" v-model="emp.empno" readonly> <br>
      <input type="text" v-model="emp.ename"> <br>
      <input type="text" v-model="emp.job"> <br>
      <input type="date" v-model="emp.hiredate"> <br>
      <input type="number" v-model="emp.sal"> <br>
      <button @click="update">修改</button>
    </div>
  </template>
  
  <script>
  import axios from 'axios'
  export default {
    
    
    data () {
    
    
      return {
    
    
          emp:{
    
    
              ename: '',
              job: '',
              hiredate: '',
              sal: ''
          }
      }
    },
    methods: {
    
    
        update(){
    
    
          axios.put('/api/emp',this.emp)
          .then( (resp)=>{
    
    
              alert(resp.data)
          })
      }
    },
    components: {
    
    },
    computed: {
    
    },
    watch: {
    
    },
    mounted () {
    
    
      // 取出数据
        let s = sessionStorage.getItem('emp')
        this.emp = JSON.parse(s)
    }
  }
  </script>
<style scoped>
</style>

insert image description here

Guess you like

Origin blog.csdn.net/rej177/article/details/132174411