spring-boot react如何一步一步實現增刪改查

這篇文章主要介紹了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 [email protected] --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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持神馬文庫。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章