Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize user column form page with Vue and Springboot

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to realize the user list form page by Vue combined with Springboot". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn "Vue combined with Springboot how to achieve user list form page" it!

Introduction to the development project of user list page

User list page development, you can achieve simple query, delete, modify, and add user information functions. The front end uses the vue framework and the back end uses the springboot framework, a simple vue+springboot front-end separation project.

The main modules and technical points of this project are shown in the figure.

Project source code + notes + materials

Vue-springboot_jb51.rar

1. Write the front-end html page

Page:

Code:

Add vue series course user list Serial number, name, salary, age, personal introduction operation {{user.id}} {{user.name}} {{user.salary}} {{user.age}} {{user.description}} Delete the modification number

0001

Name, salary, age. Profile Submit var app = new Vue ({el: "# app" Data: {msg: "vue Lifecycle", users: [],}, methods: {}, computed: {}, created () {/ / send axios request / * axios.get ("http://localhost:8989/users").then(res=>{ this.users = res.data" }); * / this.users = [{id:1,name: "Xiao Chen", age:23,salary:2300,description: "he is a rookie!!"]},})

We put the html page in the following location:

Vue and axios resource files are stored in the js directory.

2. Springboot framework building 2.1, project creation

1. Create a new maven project and name it vue_day3_admin.

2. Introduce sprinboot-web dependency

Org.springframework.boot spring-boot-starter-web

3. Write the startup class AdminApplication

Package com.xiao;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class AdminApplication {public static void main (String [] args) {SpringApplication.run (AdminApplication.class,args);}}

4. Test

2.2. Connect to the database

1. Create a vue_day3 database

CREATE TABLE t_user (id INT (6) PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR (40), salary DOUBLE (7) 2), age INT (3), des VARCHAR (200)

2. Introduce database-related dependencies

Org.mybatis.spring.boot mybatis-spring-boot-starter 2.1.3 mysql mysql-connector-java 5.1.38 com.alibaba druid 1.2.1

3. Application.properties configuration file compilation

Server.port=8990# integrates mybatisspring.datasource.type=com.alibaba.druid.pool.DruidDataSourcespring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/vue_day3?characterEncoding=utf-8spring.datasource.username=rootspring.datasource.password=root# where the specified mapper appears mybatis.mapper-locations=classpath:com/xiao/mapper/*.xmlmybatis.type-aliases-package=com.xiao.entity# shows the sql statement logging.level.com.xiao.dao=debug during execution

4. Springboot connects to mysql database

Open the Data Sources and Deivers input database user and password, and select the database to connect to.

4.2.Setting time zone to UTC

5. Start the test

There's no problem.

2.3 、 The project fully depends on 4.0.0 org.example vue_day3_admin 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.5.0 org.springframework.boot spring-boot-starter-web org.mybatis.spring.boot Mybatis-spring-boot-starter 2.1.3 mysql mysql-connector-java 5.1.38 com.alibaba druid 1.2.1 org.springframework.boot Spring-boot-starter-test 1.5.12.RELEASE test 3 、 Write entity layer

Create a user entity class

Package com.xiao.entity;public class User {private Integer id; private String name; private Double salary; private Integer age; private String des; public User () {} public User (Integer id, String name, Double salary, Integer age, String des) {this.id = id; this.name = name; this.salary = salary; this.age = age; this.des = des } public Integer getId () {return id;} public void setId (Integer id) {this.id = id;} public String getName () {return name;} public void setName (String name) {this.name = name;} public Double getSalary () {return salary;} public void setSalary (Double salary) {this.salary = salary } public Integer getAge () {return age;} public void setAge (Integer age) {this.age = age;} public String getDes () {return des;} public void setDes (String des) {this.des = des } @ Override public String toString () {return "User {" + "id=" + id + ", name="+ name +" + ", salary=" + salary + ", age=" + age + ", des="+ des +" + "}" 4. Query user information 4.1 and write back-end code

1. UserDAO writing

Package com.xiao.dao;import com.xiao.entity.User;import java.util.List;public interface UserDAO {/ / query all user information List findAll ();}

2. UserDAOMapper.xml writing

Create the following directory under resources

Code:

Select id,name,salary,age,des from t_user

3. Service layer programming

UserService interface

Package com.xiao.service;import com.xiao.entity.User;import java.util.List;public interface UserService {/ / query all user methods List findAll ();}

UserServiceImpl implementation class

Package com.xiao.service;import com.xiao.dao.UserDAO;import com.xiao.entity.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;import java.util.List @ Service / / means this is a business layer component function: to create a userServiceImpl object @ Transactional / / in the spring factory to add transaction control to all methods in the class public class UserServiceImpl implements UserService {@ Autowired private UserDAO userDAO; @ Override @ Transactional (propagation = Propagation.SUPPORTS) / / declare transaction annotations public List findAll () {return userDAO.findAll ();}}

4. Conduct test test

BasicTest class

Package com.xiao.test;import com.xiao.AdminApplication;import org.junit.runner.RunWith;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;@SpringBootTest (classes = AdminApplication.class) / / specify the entry class @ RunWith (SpringRunner.class) / / launch factory public class BasicTest {}

TestUserService class

Package com.xiao.test;import com.xiao.service.UserService;import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired;public class TestUserService extends BasicTest {@ Autowired private UserService userService; @ Test public void findAll () {userService.findAll () .forEach (user-> System.out.println (user));}}

The test was successful!

4.2. Front-end code writing

1. Add the axios request in the created () function

# Lifecycle Hook: lifecycle function

Initialization phase

1.beforeCreate vue instance's own event lifecycle initialization

2.created completes custom data methods computed injection and verification recommendations

3.beforeMount compiles el to html into a template and does not complete template injection

4.Mounted injects the compiled template into data, and completes the injection template to form a virtual dom replacement el to point to the original dom

Code:

Var app = new Vue ({el: "# app", data: {msg: "vue Lifecycle", users: [], / / define an empty users array Used to store all users' information}, methods: {}, computed: {}, created () {/ / execute data methods computed, etc. Complete injection and verification / / send axios request axios.get ("http://localhost:8990/users").then(res=>{ console.log (res.data)) This.users = res.data;}); / / es6 Arrow function Note: arrow function does not have its own this simplified function () {} / / has its own this},})

2. Testing

The test was successful!

5. Add user information 5.1 and write back-end code

1. UserDAO interface layer

/ / query all user information List findAll ()

2 、 UserDAOMapper.xml

Insert into t_user values (# {id}, # {name}, # {salary}, # {age}, # {des})

Using the mysql self-growing sequence, how do you get the primary key when you insert a new piece of data?

Just add the following attributes:

UseGeneratedKeys= "true" keyProperty= "id"

The value range of useGeneratedKeys is true, and the default value of false is false. Meaning: sets whether to use the getGenereatedKeys method of JDBC to get the primary key and assign it to the domain model property of the keyProperty setting.

KeyProperty takes the key value of id. When the primary key is self-increasing, you can use the primary key value directly after it is successfully added. The value of keyProperty is the attribute value of the object, not the field name in the database table.

3. Service layer programming

UserService class

/ / Save user information void save (User user)

UserServiceImpl class

@ Overridepublic void save (User user) {userDAO.save (user);}

4. UserController control class,

/ / add employee information interface @ PostMapping ("saveOrUpdate") public void saveOrUpdate (@ RequestBody User user) {System.out.println (user); userService.save (user);} 5.2. Frontend code writing

1. Add v-model bi-directional binding to the form form

Name, salary, age, personal profile submitted

2. Bind the saveOrUpdate method to the submit button

Var app = new Vue ({el: "# app", data: {msg: "vue Lifecycle", users: [], / / define an empty users array Used to store information for all users user: {}, / / defines an empty json object}, methods: {saveOrUpdate () {/ / Save or modify method / / send an added request console.log (this.user) Axios.post ("http://localhost:8990/saveOrUpdate",this.user).then(res=>{ this.user= {}; / / added successfully, empty the data alert (" user information updated successfully! "); / / update the data this.findAll () of the original list / / call to query all}) .catch (err= > {alert ("user information update failed!")}) }, findAll () {/ / send axios request axios.get ("http://localhost:8990/users").then(res=>{ console.log (res.data); this.users = res.data;}) / / es6 Arrow function Note: arrow function does not have its own this simplified function () {} / / has its own this}}

3. Test it.

The test was successful!

6. Modify user information 6.1 and backend code

1. UserDAO class

/ / update user information void update (User user); / / query user information User findById (Integer id) based on id

2 、 UserDAOMapper.xml

Update t_user set name = # {name}, age = # {age}, salary = # {salary}, des = # {des} where id = # {id} select id,name,age,salary,des from t_user where id = # {id}

3. Service layer

UserService class

/ / modify user information void update (User user); / / query user information User findById (Integer id) based on id

UserServiceImpl implementation class

@ Overridepublic void update (User user) {userDAO.update (user);} @ Override@Transactional (propagation = Propagation.SUPPORTS) / / declare transaction comments on the method Propagation: transaction propagation attribute supports transaction public User findById (Integer id) {return userDAO.findById (id);}

4. Control layer

Here we need to judge according to the parameters requested by the front end. If the id in the parameter requested by the frontend is empty, it means that it is an add operation, otherwise it is an update operation, and we execute the corresponding code.

/ / add employee information interface @ PostMapping ("saveOrUpdate") public void saveOrUpdate (@ RequestBody User user) {log.info ("received business logic: {}", user); / / determine whether there is id / / exist: update operation does not exist id: add operation if (StringUtils.isEmpty (user.getId () {/ / if empty log.info ("add business logic.") UserService.save (user); / / add} else {log.info ("update business logic."); userService.update (user);}} 6.2, frontend code

We click the modify button to display the user information.

1. Let's first add an event to query user information according to id to the modify button.

Modify

2. UserEditDetail (id)

UserEditDetail (id) {/ / is used to echo the currently clicked user information in the form axios.get ("http://localhost:8990/user/"+id).then(res=>{ this.user = res.data; / / complete data echo});}

3. Bind and modify or add user information events to the submit button

Submit

4. SaveOrUpdate ()

SaveOrUpdate () {/ / Save or modify method if (! this.user.name) {alert ("name cannot be empty!"); return;} console.log (this.user); axios.post ("http://localhost:8990/saveOrUpdate",this.user).then(res=>{ this.user= {}; / / added successfully, empty data alert (" user information updated successfully! ") / / update the data of the original list this.findAll (); / / call to query all}) .catch (err= > {alert ("user information update failed!")};},}, findAll () {/ / send axios request axios.get ("http://localhost:8990/users").then(res=>{ console.log (res.data); this.users = res.data)" }); / / es6 Arrow function Note: the arrow function does not have its own this simplified function () {} / / has its own this}

5. Test it.

The test was successful!

7. Delete user information 7.1 and backend code

1. UserDAO interface

/ / Delete user information void delete (Integer id) based on id

2 、 UserDAOMapper.xml

Delete from t_user where id = # {id}

3. Service layer

UserService class

/ / Delete user information void delete (Integer id) according to id

UserServiceImpl class

@ Overridepublic void delete (Integer id) {userDAO.delete (id);}

4. Controller class

/ / API @ DeleteMapping ("delete/ {id}") public void delete (@ PathVariable Integer id) {userService.delete (id);} 7.2, frontend code for deleting user information according to id

1. Bind the delete event to the delete button

Delete

2. DelUser (id) delete user method

DelUser (id) {/ / Delete user method / / friendly reminder to delete if (window.confirm ("are you sure you want to delete this record?")) {axios.delete ("http://localhost:8990/delete/"+id).then(res=>{ alert (" user information deleted successfully! "); this.findAll (); call to query all}) .catch (err= > {alert (" user information deletion failed! ");});}}

3. Test it.

Delete message successfully!

At this point, I believe that everyone on the "Vue combined with Springboot how to achieve user list page" have a deeper understanding, might as well to the actual operation of it! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report