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

 更新时间:2018年11月02日 15:04:41   作者:心扬  
这篇文章主要介绍了spring-boot react如何一步一步实现增删改查,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

 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中增加前后端交互代理

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

目录结构

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

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'

源码地址:react-crud_jb51.rar

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

相关文章

  • SpringBoot如何自定义starter

    SpringBoot如何自定义starter

    这篇文章主要介绍了SpringBoot如何自定义starter,Springboot的出现极大的简化了开发人员的配置,而这之中的一大利器便是springboot的starter,starter是springboot的核心组成部分,下面来看看集体引用过程吧
    2022-01-01
  • MyBatis-Plus执行SQL分析打印过程

    MyBatis-Plus执行SQL分析打印过程

    这篇文章主要介绍了MyBatis-Plus执行SQL分析打印过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-09-09
  • Google Kaptcha验证码生成的使用实例说明

    Google Kaptcha验证码生成的使用实例说明

    这篇文章主要为大家介绍了Google Kaptcha验证码的使用实例说明,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-03-03
  • Java之BigDecimal实现详解

    Java之BigDecimal实现详解

    这篇文章主要介绍了Java之BigDecimal实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-01-01
  • Activiti常用类简介

    Activiti常用类简介

    这篇文章主要介绍了Activiti常用类,需要的朋友可以参考下
    2014-08-08
  • Spring Boot文件上传原理与实现详解

    Spring Boot文件上传原理与实现详解

    这篇文章主要介绍了Spring Boot 文件上传原理与实现详解,前端文件上传是面向多用户的,多用户之间可能存在上传同一个名称、类型的文件;为了避免文件冲突导致的覆盖问题这些应该在后台进行解决,需要的朋友可以参考下
    2024-01-01
  • Spring ApplicationListener监听器用法详解

    Spring ApplicationListener监听器用法详解

    这篇文章主要介绍了Spring ApplicationListener监听器用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • Java多线程之同步工具类CountDownLatch

    Java多线程之同步工具类CountDownLatch

    这篇文章主要介绍了Java多线程之同步工具类CountDownLatch,CountDownLatch是一个同步工具类,它允许一个或多个线程一直等待,直到其他线程执行完后再执行。例如,应用程序的主线程希望在负责启动框架服务的线程已经启动所有框架服务之后执行,下面一起来学习学习内容吧
    2021-10-10
  • 详解ZXing-core生成二维码的方法并解析

    详解ZXing-core生成二维码的方法并解析

    本文给大家介绍ZXing-core生成二维码的方法并解析,主要用到goggle发布的jar来实现二维码功能,对此文感兴趣的朋友一起学习吧
    2016-05-05
  • Spring注解@Configuration和@Component区别详解

    Spring注解@Configuration和@Component区别详解

    @Component和@Configuration都可以作为配置类,之前一直都没觉得这两个用起来有什么差别,可能有时程序跑的和自己想的有所区别也没注意到,下面这篇文章主要给大家介绍了关于Spring注解@Configuration和@Component区别的相关资料,需要的朋友可以参考下
    2023-04-04

最新评论