欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring-boot react如何一步一步实现增删改查

程序员文章站 2024-02-28 21:36:16
 1、maven继承spring-boot org.springframework.bo...

 1、maven继承spring-boot

<parent>
	<groupid>org.springframework.boot</groupid>
	<artifactid>spring-boot-starter-parent</artifactid>
	<version>2.0.6.release</version>
	<relativepath/> <!-- lookup parent from repository -->
</parent>

2、指定jdk版本和字符集

<properties>
	<project.build.sourceencoding>utf-8</project.build.sourceencoding>
	<project.reporting.outputencoding>utf-8</project.reporting.outputencoding>
	<java.version>1.8</java.version>
</properties>

3、添加依赖

<dependencies>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-web</artifactid>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-test</artifactid>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupid>org.springframework.boot</groupid>
		<artifactid>spring-boot-starter-data-jpa</artifactid>
	</dependency>
	<dependency>
		<groupid>mysql</groupid>
		<artifactid>mysql-connector-java</artifactid>
	</dependency>
    <dependency>
      <groupid>com.alibaba</groupid>
      <artifactid>druid</artifactid>
      <version>1.1.10</version>
    </dependency>
    <dependency>
      <groupid>org.projectlombok</groupid>
      <artifactid>lombok</artifactid>
    </dependency>
	<dependency>
		<groupid>org.apache.commons</groupid>
		<artifactid>commons-text</artifactid>
		<version>1.2</version>
	</dependency>
</dependencies>

4、添加插件

<plugin>
	<groupid>org.springframework.boot</groupid>
	<artifactid>spring-boot-maven-plugin</artifactid>
</plugin>

5、配置src/main/resources/application.yml

spring:
 datasource:
  driver-class-name: com.mysql.jdbc.driver
  url: jdbc:mysql://localhost:3306/react
  username: root
  password: 123456
  type: com.alibaba.druid.pool.druiddatasource
 jpa:
  show-sql: true
  hibernate:
   ddl-auto: update
  database: mysql
  database-platform: org.hibernate.dialect.mysql5innodbdialect

6、编写启动类

package com.example.react;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;

@springbootapplication
public class reactapplication {

	public static void main(string[] args) {
		springapplication.run(reactapplication.class, args);
	}
}

7、持久化对象类

package com.example.react.model;

import lombok.*;
import lombok.experimental.accessors;

import javax.persistence.*;

/**
 * 用户类
 */
@table(name = "t_user")
@entity
@setter
@getter
@noargsconstructor
@allargsconstructor
@tostring
@accessors(chain = true)
public class user {
  /**
   * 用户id
   */
  @id
  @generatedvalue(strategy = generationtype.identity)
  private long id;
  /**
   * 用户名
   */
  private string name;
}

8、持久化操作接口

package com.example.react.dao;

import com.example.react.model.user;
import org.springframework.data.jpa.repository.jparepository;
import org.springframework.stereotype.repository;

@repository
public interface userdao extends jparepository<user,long> {


}

9、控制层

package com.example.react.controller;

import com.example.react.model.user;
import com.example.react.dao.userdao;
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 userdao userdao;

  /**
   * 查询所有用户
   * @return
   */
  @getmapping
  public list<user> all(){
    return this.userdao.findall();
  }

  /**
   * 保存用户
   * 新增或更新
   * @param user
   * @return
   */
  @postmapping
  public object save(@requestbody user user){
    this.userdao.save(user);
    return true;
  }

  /**
   * 根据id删除用户
   * @param id
   * @return
   */
  @deletemapping("/{id}")
  public object delete(@pathvariable long id){
    this.userdao.deletebyid(id);
    return true;
  }
}

10、启动后台项目

11、在项目根路径创建前端项目,使用create-react-app

npx create-react-app web

给命令会在当前目录下使用create-react-app创建一个react单页项目

12、进入web目录,添加依赖库

 npm install axios bootstrap@3.3.7 --save

13、在package.json中增加前后端交互代理

"proxy": http://localhost:8080

14、删除前端项目src 目录下无用的文件,只保留index.jsapp.js,并修改文件使其能够运行

目录结构

spring-boot react如何一步一步实现增删改查

index.js

import react from 'react';
import reactdom from 'react-dom';
import app from './app';

reactdom.render(<app />, document.getelementbyid('root'));

app.js

import react, { component } from 'react';

class app extends component {
 render() {
  return (
   <div>
    
   </div>
  );
 }
}

export default app;

15、在index.js中引入bootstrap样式文件

注意:这里只需要引入css文件即可

import react from 'react';
import reactdom from 'react-dom';
import 'bootstrap/dist/css/bootstrap.min.css';
import app from './app';

reactdom.render(<app />, document.getelementbyid('root'));

16、接下来进行页面布局,这是一个简单的增删改查功能,所以只需要在一个页面编写全部功能即可,左侧为一个表格,右侧为一个表单,如下图

spring-boot react如何一步一步实现增删改查

17、首先利用bootstrap中提供的栅格模式,将页面分为左右两栏,两栏中分别有一个panel

render() {
  return (
    <div classname="container-fluid" style={{margintop: '20px'}}>
      <div classname="row">
        <div classname="col-xs-4 col-xs-offset-1">
          <div classname="panel panel-default">
            <div classname="panel-body">
              表格区域
            </div>
          </div>
        </div>
        <div classname="col-xs-3 col-xs-offset-1">
          <div classname="panel panel-default">
            <div classname="panel-body">
              表单区域
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

18、添加表格

<table classname="table table-bordered">
 <thead>
  <tr>
    <th>id</th>
    <th>用户名</th>
    <th>操作</th>
  </tr>
  </thead>
  <tbody>

  </tbody>
</table>

19、添加表单

<form classname="form-horizontal">
  <div classname="form-group">
    <label htmlfor="name" classname="col-xs-3">用户名</label>
    <div classname="col-xs-8">
      <input type="text" id="name" classname="form-control"/>
    </div>
  </div>
  <div classname="form-group">
    <div classname="col-sm-offset-2 col-sm-10">
      <button classname="btn btn-default">提交</button>
    </div>
  </div>
</form>

20、初始化 state

constructor(props) {
  super(props);
  this.state = {
    id:'',
    name:'',
    list:[]
  }
}

21、实现查询函数,并在app组件挂载渲染完成后执行查询函数

引入axios

import axios from 'axios';

声明查询函数

query = () =>{
	axios.get('/user').then(({data})=>{
		this.setstate({
			list:data	
		});
	});
}

组件挂载完成后执行查询函数

componentdidmount(){
	this.query();
}

22、向表格中填充数据

<tbody>
{
  this.state.list.map(item=>{
    return (
      <tr key={item.id}>
        <td>{item.id}</td>
        <td>{item.name}</td>
        <td>
          <button classname="btn btn-primary">修改</button>
          <button classname="btn btn-danger" style={{marginleft:'5px'}}>删除</button>
        </td>
      </tr>
    )
  })
}
</tbody>

23、对表单中的文本框和提交按钮进行控制

文本框

<input type="text" id="name" classname="form-control" value={this.state.name} onchange={
  (e)=>{
    this.setstate({
      name:e.target.value
    })
  }
}/>

提交按钮点击事件

<button classname="btn btn-default" onclick={this.handleformsubmit}>提交</button>

点击事件函数

handleformsubmit = (e) => {
  e.preventdefault();
  if (this.state.name != '') {
    axios.post('/user', {
      id: !this.state.id ? '' : this.state.id,
      name: this.state.name
    }).then(({data}) => {
      this.setstate({
        id: '',
        name: ''
      });
      this.query();
    })
  }
}

24、对表格中每一行的修改和删除按钮进行事件处理

<button classname="btn btn-primary" onclick={() => {
   this.setstate({id: item.id, name: item.name})
 }}>修改
 </button>
 <button classname="btn btn-danger" style={{marginleft: '5px'}}
     onclick={() => {
       this.deleteitem(item)
     }}>删除
 </button>

删除操作函数

deleteitem = (item) => {
  axios.delete(`/user/${item.id}`).then(({data}) => {
    this.query();
  })
}

25、执行npm start启动前端

26、表单数据居中显示添加app.css

.table th, .table td {
  text-align: center;
  vertical-align: middle!important;
}

app.js中引入app.css

import './app.css'

源码地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。