【SpringBoot总结】历史文章
SpringBoot总结(一)——第一个SpringBoot项目
SpringBoot总结(二)——Spring Boot的自动配置
SpringBoot总结(三)——SpringBoot的配置文件
SpringBoot总结(四)——@Value和@ConfigurationProperties的区别
SpringBoot总结(五)——@PropertySource注解与@ImportResource注解
SpringBoot总结(六)——SpringBoot配置文件占位符
SpringBoot总结(七)——Profile的使用
SpringBoot总结(八)——配置文件的加载位置
SpringBoot总结(九)——@Conditional注解与自动配置报告
SpringBoot总结(十)——SpringBoot+Mybatis实现数据库的CRUD(从创建到实现【超详细附代码】)
SpringBoot总结(十一)——SpringBoot的静态资源映射规则
SpringBoot总结(十二)——登录界面的实现
SpringBoot总结(十三)——修改嵌入式Servlet容器配置
实现后台获取数据在前台显示
在上一篇文章中,用了一个十分简陋的界面实现登录注册的功能,本篇文章将会介绍怎样从后台获取数据库中的学生信息在前台显示;以及搜索学生信息的功能。
文章目录
实现后台获取数据在前台显示前言一、页面实现1.1、 Element的简单使用 二、后端的实现2.1、数据库表结构2.2、项目结构2.3、创建实体2.4、结果集的封装2.5、编写Controller2.6、编写Service2.7、编写Mapper2.8、编写Mapper对应的xml文件2.9、配置文件2.10、解决跨域问题 三、运行效果总结前言
开发工具:HBuilderX、 IDEA、Maven、jdk1.8、Mysql。
一、页面实现
Student.vue
<template><div><el-row style="height: 700px;"><search-bar @onSearch="searchResult" ref="searchBar"></search-bar><el-table :data="students" style="width: 100%"><el-table-column label="学号" width="180"><template slot-scope="scope"><span style="margin-left: 10px">{{scope.row.sno }}</span></template></el-table-column><el-table-column label="姓名" width="180"><template slot-scope="scope"><span style="margin-left: 10px">{{scope.row.sname }}</span></template></el-table-column><el-table-column label="出生年月" width="180"><template slot-scope="scope"><i class="el-icon-time"></i><span style="margin-left: 10px">{{scope.row.sbirthday }}</span></template></el-table-column><el-table-column label="年龄" width="180"><template slot-scope="scope"><span style="margin-left: 10px">{{scope.row.sage }}</span></template></el-table-column><el-table-column label="家庭住址" width="180"><template slot-scope="scope"><span style="margin-left: 10px">{{scope.row.saddress }}</span></template></el-table-column><el-table-column label="操作"><template slot-scope="scope"><el-button size="mini" @click="handleEdit(scope.row.sno)">编辑</el-button><el-button size="mini" type="danger" @click="handleDelete(scope.row.sno)">删除</el-button></template></el-table-column></el-table></el-row><el-row><el-pagination @current-change="handleCurrentChange" :current-page="currentPage" :page-size="pagesize" :total="students.length"></el-pagination></el-row></div></template><script>import SearchBar from './SearchBar'export default {name: 'Students',components: {SearchBar},data() {return {students: [],currentPage: 1,pagesize: 18}},mounted: function() {this.loadStudents()},methods: {loadStudents() {var _this = thisthis.$axios.get('/student/findAllStudents').then(resp => {if (resp.data.code === 200) {_this.students = resp.data.data}})},handleCurrentChange: function(currentPage) {this.currentPage = currentPage},searchResult() {var _this = this// alert(this.$refs.searchBar.keywords) //测试输入框中的内容this.$axios//向后端发送数据.get('/student/search?keywords=' + this.$refs.searchBar.keywords, {}).then(resp => {if (resp && resp.data.code === 200) {_this.students = resp.data.data}})},//编辑handleEdit(sno) {console.log(sno);this.$router.push({path:'/EditStudent',query:{sno:sno}});},//删除handleDelete(sno) {var _this = thisthis.$axios//向后端发送数据I.post('/student/delete?sno=' + sno, {}).then(resp => {if (resp && resp.data.code === 200) {_this.students = resp.data.data //重新刷新数据this.$message.warning(resp.data.message)}})}}}</script>
编写一个搜索栏组件,并在Student.vue中引入
SearchBar.vue
<template><div style="margin-bottom: 30px;display: flex;justify-content: center;align-items: center"><el-input@keyup.enter.native="searchClick"placeholder="输入学号或姓名进行搜索..."prefix-icon="el-icon-search"size="small"style="width: 400px;margin-right: 10px"v-model="keywords"></el-input><el-button size="small" type="primary" icon="el-icon-search" @click="searchClick">搜索</el-button></div></template><script>export default {name: 'SearchBar',data () {return {keywords: '',books: [],cardLoading: []}},methods: {searchClick () {this.$emit('onSearch')}}}</script><style scoped></style>
注:在上面的界面中使用了 Element组件,可以使我们的界面更加的美观;
1.1、 Element的简单使用
Element官方链接地址:http://element-cn.eleme.io/#/zh-CN
安装方法:
用cd命令进入项目文件夹下。执行命令:npm i element-ui -S
在main.js文件中引入Element
import ElementUI from 'element-ui'import 'element-ui/lib/theme-chalk/index.css'Vue.use(ElementUI)
二、后端的实现
后端同样使用了SpringBoot与Mybatis的整合来进行操作数据库。
2.1、数据库表结构
表名为t_student
2.2、项目结构
创建SpringBoot项目vue-project02
2.3、创建实体
Student.java
package com.example.entity;/*** @author 810402084*/public class Student {private int sno;private String sname;private String sage;private String sbirthday;private String saddress;public int getSno() {return sno;}public void setSno(int sno) {this.sno = sno;}public String getSname() {return sname;}public void setSname(String sname) {this.sname = sname;}public String getSage() {return sage;}public void setSage(String sage) {this.sage = sage;}public String getSbirthday() {return sbirthday;}public void setSbirthday(String sbirthday) {this.sbirthday = sbirthday;}public String getSaddress() {return saddress;}public void setSaddress(String saddress) {this.saddress = saddress;}}
2.4、结果集的封装
Result.java
package com.example.response;/*** @author 810402084*/public class Result {private int code;private String message;private Object data;public Result() {}public Result(int code, String message, Object data) {this.code = code;this.message = message;this.data = data;}public int getCode() {return code;}public void setCode(int code) {this.code = code;}public String getMessage() {return message;}public void setMessage(String message) {this.message = message;}public Object getData() {return data;}public void setData(Object data) {this.data = data;}}
ResultCode.java
package com.example.response;/*** @author 810402084*/public enum ResultCode {SUCCESS(200),FAIL(400),UNAUTHORIZED(401),NOT_FOUND(404),INTERNAL_SERVER_ERROR(500);public int code;ResultCode(int code) {this.code = code;}}
ResultFactory.java
package com.example.response;/*** @author 810402084*/public class ResultFactory {public static Result buildSuccessResult(Object data) {return buildResult(ResultCode.SUCCESS, "成功", data);}public static Result buildFailResult(String message) {return buildResult(ResultCode.FAIL, message, null);}public static Result buildResult(ResultCode resultCode, String message, Object data) {return buildResult(resultCode.code, message, data);}public static Result buildResult(int resultCode, String message, Object data) {return new Result(resultCode, message, data);}}
2.5、编写Controller
StudentController.java
package com.example.controller;import com.example.entity.Student;import com.example.response.Result;import com.example.response.ResultFactory;import com.example.service.StudentService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import java.util.List;/*** @author 810402084*/@RestController@RequestMapping("/student")@CrossOriginpublic class StudentController {@Autowiredprivate StudentService studentService;@CrossOrigin@RequestMapping(value = "/findAllStudents", method = RequestMethod.GET)public Result findAllStudentsList() {List<Student> booksList = studentService.findAllStudents();return ResultFactory.buildSuccessResult(booksList);}@CrossOrigin@RequestMapping(value = "/search", method = RequestMethod.GET)public Result searchBooksList(@RequestParam String keywords) {if ("".equals(keywords)) {return ResultFactory.buildSuccessResult(studentService.findAllStudents());} else {return ResultFactory.buildSuccessResult(studentService.searchStudentsList(keywords));}}}
2.6、编写Service
StudentService.java
package com.example.service;import com.example.entity.Student;import com.example.mapper.StudentMapper;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;/*** @author 810402084*/@Servicepublic class StudentService {@Autowiredprivate StudentMapper studentMapper;public List<Student> findAllStudents() {return studentMapper.findAllStudents();}public List<Student> searchStudentsList(String keywords) {return studentMapper.searchStudentsList(keywords);}}
2.7、编写Mapper
StudentMapper.java
package com.example.mapper;import com.example.entity.Student;import org.apache.ibatis.annotations.Mapper;import java.util.List;/*** @author 810402084*/@Mapperpublic interface StudentMapper {public List<Student> findAllStudents();public List<Student> searchStudentsList(String keywords);}
2.8、编写Mapper对应的xml文件
StudentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapperPUBLIC "-////DTD Mapper 3.0//EN""/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.mapper.StudentMapper"><select id="findAllStudents" resultType="Student">select * from t_student</select><select id="searchStudentsList" resultType="Student">select * from t_student where sno like '%${keywords}%' or sname like '%${keywords}%'</select></mapper>
2.9、配置文件
application.properties
#配置端口号server.port=8082spring.datasource.username=rootspring.datasource.password=123spring.datasource.url=jdbc:mysql://localhost:3306/vue-project02?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghaispring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.thymeleaf.cache=falsemybatis.type-aliases-package=com.example.entitymybatis.mapper-locations=classpath:mybatis/mapper/*.xml
2.10、解决跨域问题
下面是用配置类的方式。
package com.example.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;//解决跨域问题@Configurationpublic class MyConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("*").allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS").allowCredentials(true).maxAge(3600).allowedHeaders("*");}}
三、运行效果
总结
本篇文章创建了一个简单的学生信息表、实现了从后台获取数据后,在前台进行显示的功能;同时可以根据学号与姓名进行搜索的功能。希望能给予大家帮助。😊