[development section] 10 minutes fast start spring boot + react login before and after separation

mind_ programmonkey 2020-11-13 04:19:19
development section minutes fast start


【 Development of article 】10 Minutes to get started spring boot+react Before and after login separation

Pre knowledge :

This time it's going to bring the front and rear ends apart spring boot+react The login demo.

Next , Let's swim in the ocean of learning !!!

One 、 Fore and aft end separation

1.1 Fore and aft end separation

In the application mode where the front and back ends are not separated , The effect of the front page is controlled by the back end , Page rendering or redirection by backend , That is, the back end needs to control the display of the front end , The coupling between the front end and the back end is very high .

1.2 Fore and aft end separation

In the application mode of front and back end separation , The back end only returns the data required by the front end , Don't render anymore HTML page , No longer control the effect of the front end . As for the effect that front-end users see , How the data requested from the back end is loaded into the front and back end , The front end decides for itself , There are ways to deal with web pages , But no matter which front end , The data required is basically the same , The back end only needs to develop a set of logic to provide external data .

Two 、 Back end design

2.1 Database table design

2.2 technology

  • spring boot
  • mybatis

2.3 Project structure

1.entity

package com.lcz.login.entity;
/**
* @author : codingchao
* @date : 2020-08-16 14:02
* @Description:
**/
public class User {
private int id;
private String username;
private String password;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.lcz.login.entity;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* @author : codingchao
* @date : 2020-08-16 14:15
* @Description:
**/
public class Result<T> {
// Error code
private Integer code;
// Prompt information
private String msg;
// The specific content
private T data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}

2.mapper

package com.lcz.login.mapper;
/**
* @author : codingchao
* @date : 2020-08-16 14:04
* @Description:
**/
import com.lcz.login.entity.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
@Mapper
public interface UserMapper {
// Check the password by account name
User findUserByName(String username);
}

3.service

package com.lcz.login.service;
import com.lcz.login.entity.User;
import com.lcz.login.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author : codingchao
* @date : 2020-08-16 14:07
* @Description:
**/
public interface UserSerice {
public User findUserByName(String name);
}

4.service/impl

package com.lcz.login.service.impl;
import com.lcz.login.entity.Result;
import com.lcz.login.entity.User;
import com.lcz.login.mapper.UserMapper;
import com.lcz.login.service.UserSerice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* @author : codingchao
* @date : 2020-08-16 14:09
* @Description:
**/
@Service
public class UserServiceImpl implements UserSerice {
@Autowired
private UserMapper userMapper;
@Override
public User findUserByName(String name) {
User user = userMapper.findUserByName(name);
return user;
}
}

5.controller

package com.lcz.login.controller;
import com.lcz.login.entity.Result;
import com.lcz.login.entity.User;
import com.lcz.login.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author : codingchao
* @date : 2020-08-16 14:10
* @Description:
**/
@RestController
@RequestMapping(value="/crud",method = {RequestMethod.GET,RequestMethod.POST})
public class UserController {
@Autowired
private UserServiceImpl userService;
@PostMapping("/listUserByName")
public Result<User> findUserByName(@RequestParam("username")String username,
@RequestParam("password")String password){
User user = userService.findUserByName(username);
Result result = new Result();
if (user.getPassword().equals(password)){
result.setCode(0);
result.setMsg(" success ");
result.setData(user);
}else{
result.setCode(-1);
result.setMsg(" Failure ");
result.setData("");
}
return result;
}
}

6.resource/mapper/UserMapper.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.lcz.login.mapper.UserMapper">
<resultMap id="result" type="com.lcz.login.entity.User">
<result property="username" column="username"/>
<result property="password" column="password"/>
</resultMap>
<select id="findUserByName" resultMap="result">
SELECT * FROM user where username=#{username}
</select>
</mapper>

The rest of the configuration , May refer to [ Development of article ]10 Minutes to get started spring
boot+mybatis Additions and deletions

3、 ... and 、 Front end design

The front end is in a bootstrap Open source framework for the operation of .

3.1 technology

  • React
  • Bootstrap
  • font-awesome

3.2 Function realization

Enter the account and password in the login interface -> Send the request to the back end for verification -> Verification successfully entered the home page -> Choose exit account -> Go back to the login page

3.3 Key technologies

1. Cross-domain request

  • The front port is in localhost:3000
  • The ports on the back end are in localhost:8081

Belongs to cross domain request , This time through the front end http-proxy-middleware Module to implement cross domain requests

stay src Under the new setupProxy.js

// Cross-domain request
const {createProxyMiddleware} = require('http-proxy-middleware');
module.exports = function (app) {
app.use(createProxyMiddleware('/listUserByName', {target: 'http://localhost:8081/crud/', changeOrigin: true}))
}

2.LocalStoage access

//localstorage Read
setStorage(name,data){
let dataType = typeof data;
// json
if(dataType === 'object'){
window.localStorage.setItem(name,JSON.stringify(data));
}else if( ['number','string','boolean'].indexOf(dataType) >=0 ){
window.localStorage.setItem(name,data);
}else{
alert(" This type cannot be used for local storage ");
}
}
getStorage(name){
let data = window.localStorage.getItem(name);
if(data){
return JSON.parse(data);
}else{
return '';
}
}
removeStorage(name){
window.localStorage.removeItem(name);
}

3. Sign in

  • Form validation is at the front end , Check whether the account and password are empty and meet the requirements
  • Press enter to submit the form request
  • After successful login, the user will be saved to localstorage
  • The home page interface reads localstorage And display the user name
request(param) {
return new Promise((resolve, reject) => {
$.ajax({
type: param.type || 'get',
url: param.url || '',
dataType: param.dataType || 'json',
data: param.data || null,
success: res => {
resolve(res);
},
error: err => {
resolve(err);
}
})
})
}
 onSubmit = () => {
let loginInfo = {
username: this.state.username,
password: this.state.password,
redirect : '/'
};
// Form validation
let checkResult = _mm.checkLoginInfo(loginInfo);
// console.log(checkResult);
if (checkResult.status) {
_mm.request({
type : 'post',
url: '/listUserByName',
data:{
username: this.state.username,
password: this.state.password
}
}).then((res) => {
if(res.code==-1){
_mm.errorTips(" Wrong account password ");
}else if(res.code==0){
_mm.setStorage('userInfo',res);
this.props.history.push(this.state.redirect);
}
}, (errMsg) => {
console.log(errMsg);
})
} else {
_mm.errorTips(checkResult.msg);
}
}

4. sign out

  • Click to exit , Delete localstorage Information in
  • The tourist can't get localstorage Information , Enter the login interface
// This is logout
onLogout = () => {
_mm.removeStorage('userInfo');
window.location.href = ("/login");
}
// Verify that you have login information
componentWillMount(){
if(_mm.getStorage("userInfo") == ''){
window.location.href = ("/login");
}
}

Okay , This learning journey , To this end !!!

版权声明
本文为[mind_ programmonkey]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple