• 前后端分类 (增加,查询)


    目录

    一,后台代码

    二,前台代码


    一,后台代码

    一,配置文件

    application.yml

    1. server:
    2. port: 8080
    3. servlet:
    4. context-path: /spboot
    5. spring:
    6. datasource:
    7. type: com.alibaba.druid.pool.DruidDataSource
    8. driver-class-name: com.mysql.jdbc.Driver
    9. url: jdbc:mysql://localhost:3306/bookshop?useUnicode=true&characterEncoding=utf8&useSSL=false
    10. username: root
    11. password: 123456
    12. druid:
    13. initial-size: 5
    14. min-idle: 5
    15. max-active: 20
    16. max-wait: 60000
    17. time-between-eviction-runs-millis: 60000
    18. min-evictable-idle-time-millis: 30000
    19. validation-query: SELECT 1 FROM DUAL
    20. test-while-idle: true
    21. test-on-borrow: true
    22. test-on-return: false
    23. pool-prepared-statements: true
    24. max-pool-prepared-statement-per-connection-size: 20
    25. filter:
    26. stat:
    27. merge-sql: true
    28. slow-sql-millis: 5000
    29. web-stat-filter:
    30. enabled: true
    31. url-pattern: /*
    32. exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
    33. session-stat-enable: true
    34. session-stat-max-count: 100
    35. stat-view-servlet:
    36. enabled: true
    37. url-pattern: /druid/*
    38. reset-enable: true
    39. login-username: admin
    40. login-password: admin
    41. allow: 127.0.0.1
    42. #deny: 192.168.1.100
    43. freemarker:
    44. cache: false
    45. charset: UTF-8
    46. content-type: text/html
    47. suffix: .ftl
    48. template-loader-path: classpath:/templates
    49. mybatis:
    50. mapper-locations: classpath:mapper/*.xml
    51. type-aliases-package: com.zking.spboot.model
    52. configuration:
    53. map-underscore-to-camel-case: true
    54. logging:
    55. level:
    56. com.zking.spboot.mapper: debug
    57. pagehelper:
    58. helperDialect: mysql
    59. reasonable: true
    60. supportMethodsArguments: true
    61. params: count=countSql

     generatorConfig.xml

    1. "1.0" encoding="UTF-8" ?>
    2. generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    3. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
    4. <generatorConfiguration>
    5. <properties resource="jdbc.properties"/>
    6. <classPathEntry location="E:\maven mulu\mvn_repository2\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/>
    7. <context id="infoGuardian">
    8. <commentGenerator>
    9. <property name="suppressAllComments" value="true"/>
    10. <property name="suppressDate" value="true"/>
    11. commentGenerator>
    12. <jdbcConnection driverClass="${jdbc.driver}"
    13. connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>
    14. <javaTypeResolver>
    15. <property name="forceBigDecimals" value="false"/>
    16. javaTypeResolver>
    17. <javaModelGenerator targetPackage="com.zking.spboot.model"
    18. targetProject="src/main/java">
    19. <property name="enableSubPackages" value="false"/>
    20. <property name="constructorBased" value="true"/>
    21. <property name="trimStrings" value="false"/>
    22. <property name="immutable" value="false"/>
    23. javaModelGenerator>
    24. <sqlMapGenerator targetPackage="com.zking.spboot.mapper"
    25. targetProject="src/main/resources">
    26. <property name="enableSubPackages" value="false"/>
    27. sqlMapGenerator>
    28. <javaClientGenerator targetPackage="com.zking.spboot.mapper"
    29. targetProject="src/main/java" type="XMLMAPPER">
    30. <property name="enableSubPackages" value="false"/>
    31. javaClientGenerator>
    32. <table schema="" tableName="t_book" domainObjectName="Book"
    33. enableCountByExample="false" enableDeleteByExample="false"
    34. enableSelectByExample="false" enableUpdateByExample="false">
    35. table>
    36. context>
    37. generatorConfiguration>

    jdbc.properties

    1. jdbc.driver=com.mysql.jdbc.Driver
    2. jdbc.url=jdbc:mysql://localhost:3306/bookshop?useUnicode=true&characterEncoding=UTF-8
    3. jdbc.username=root
    4. jdbc.password=123456

    二,代码部分

     

    **Mapper.xml

    1. "1.0" encoding="UTF-8" ?>
    2. mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    3. <mapper namespace="com.zking.spboot.mapper.BookMapper" >
    4. <resultMap id="BaseResultMap" type="com.zking.spboot.model.Book" >
    5. <constructor >
    6. <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
    7. <arg column="bookname" jdbcType="VARCHAR" javaType="java.lang.String" />
    8. <arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
    9. <arg column="booktype" jdbcType="VARCHAR" javaType="java.lang.String" />
    10. constructor>
    11. resultMap>
    12. <sql id="Base_Column_List" >
    13. id, bookname, price, booktype
    14. sql>
    15. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
    16. select
    17. <include refid="Base_Column_List" />
    18. from t_book
    19. where id = #{id,jdbcType=INTEGER}
    20. select>
    21. <select id="qurey" resultType="com.zking.spboot.model.Book">
    22. select <include refid="Base_Column_List">include> from t_book where 1=1
    23. <if test="bookname!='' and bookname!=null">
    24. and bookname like concat('%',#{bookname},'%')
    25. if>
    26. select>
    27. <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    28. delete from t_book
    29. where id = #{id,jdbcType=INTEGER}
    30. delete>
    31. <insert id="insert" parameterType="com.zking.spboot.model.Book" >
    32. insert into t_book (id, bookname, price,
    33. booktype)
    34. values (#{id,jdbcType=INTEGER}, #{bookname,jdbcType=VARCHAR}, #{price,jdbcType=REAL},
    35. #{booktype,jdbcType=VARCHAR})
    36. insert>
    37. <insert id="insertSelective" parameterType="com.zking.spboot.model.Book" >
    38. insert into t_book
    39. <trim prefix="(" suffix=")" suffixOverrides="," >
    40. <if test="id != null" >
    41. id,
    42. if>
    43. <if test="bookname != null" >
    44. bookname,
    45. if>
    46. <if test="price != null" >
    47. price,
    48. if>
    49. <if test="booktype != null" >
    50. booktype,
    51. if>
    52. trim>
    53. <trim prefix="values (" suffix=")" suffixOverrides="," >
    54. <if test="id != null" >
    55. #{id,jdbcType=INTEGER},
    56. if>
    57. <if test="bookname != null" >
    58. #{bookname,jdbcType=VARCHAR},
    59. if>
    60. <if test="price != null" >
    61. #{price,jdbcType=REAL},
    62. if>
    63. <if test="booktype != null" >
    64. #{booktype,jdbcType=VARCHAR},
    65. if>
    66. trim>
    67. insert>
    68. <update id="updateByPrimaryKeySelective" parameterType="com.zking.spboot.model.Book" >
    69. update t_book
    70. <set >
    71. <if test="bookname != null" >
    72. bookname = #{bookname,jdbcType=VARCHAR},
    73. if>
    74. <if test="price != null" >
    75. price = #{price,jdbcType=REAL},
    76. if>
    77. <if test="booktype != null" >
    78. booktype = #{booktype,jdbcType=VARCHAR},
    79. if>
    80. set>
    81. where id = #{id,jdbcType=INTEGER}
    82. update>
    83. <update id="updateByPrimaryKey" parameterType="com.zking.spboot.model.Book" >
    84. update t_book
    85. set bookname = #{bookname,jdbcType=VARCHAR},
    86. price = #{price,jdbcType=REAL},
    87. booktype = #{booktype,jdbcType=VARCHAR}
    88. where id = #{id,jdbcType=INTEGER}
    89. update>
    90. mapper>

     **Mapper

    1. package com.zking.spboot.mapper;
    2. import com.zking.spboot.model.Book;
    3. import org.springframework.stereotype.Repository;
    4. import java.util.List;
    5. @Repository
    6. public interface BookMapper {
    7. int deleteByPrimaryKey(Integer id);
    8. //增加
    9. int insert(Book record);
    10. //模糊查询
    11. List qurey(Book book);
    12. int insertSelective(Book record);
    13. Book selectByPrimaryKey(Integer id);
    14. int updateByPrimaryKeySelective(Book record);
    15. int updateByPrimaryKey(Book record);
    16. }

    实体类:

    1. package com.zking.spboot.model;
    2. public class Book {
    3. private Integer id;
    4. private String bookname;
    5. private Float price;
    6. private String booktype;
    7. public Book(Integer id, String bookname, Float price, String booktype) {
    8. this.id = id;
    9. this.bookname = bookname;
    10. this.price = price;
    11. this.booktype = booktype;
    12. }
    13. public Book() {
    14. super();
    15. }
    16. public Integer getId() {
    17. return id;
    18. }
    19. public void setId(Integer id) {
    20. this.id = id;
    21. }
    22. public String getBookname() {
    23. return bookname;
    24. }
    25. public void setBookname(String bookname) {
    26. this.bookname = bookname;
    27. }
    28. public Float getPrice() {
    29. return price;
    30. }
    31. public void setPrice(Float price) {
    32. this.price = price;
    33. }
    34. public String getBooktype() {
    35. return booktype;
    36. }
    37. public void setBooktype(String booktype) {
    38. this.booktype = booktype;
    39. }
    40. }

    **Service

    1. package com.zking.spboot.service;
    2. import com.zking.spboot.model.Book;
    3. import java.util.List;
    4. public interface BookService {
    5. //增加
    6. int insert(Book record);
    7. //模糊查询
    8. List qurey(Book book);
    9. }

     ***Impl

    1. package com.zking.spboot.service.impl;
    2. import com.zking.spboot.mapper.BookMapper;
    3. import com.zking.spboot.model.Book;
    4. import com.zking.spboot.service.BookService;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Service;
    7. import java.util.List;
    8. @Service
    9. public class BookServiceImpl implements BookService {
    10. @Autowired
    11. private BookMapper bookMapper;
    12. @Override
    13. public int insert(Book record) {
    14. return bookMapper.insert(record);
    15. }
    16. @Override
    17. public List qurey(Book book) {
    18. return bookMapper.qurey(book);
    19. }
    20. }

     **Controller

    1. package com.zking.spboot.controller;
    2. import com.zking.spboot.model.Book;
    3. import com.zking.spboot.service.BookService;
    4. import lombok.AllArgsConstructor;
    5. import lombok.Data;
    6. import lombok.NoArgsConstructor;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.web.bind.annotation.RequestMapping;
    9. import org.springframework.web.bind.annotation.RestController;
    10. import java.util.List;
    11. /**
    12. * @author ruojuan
    13. * @site www.ruojuan.com
    14. * @company 玉渊工作室
    15. * @create 2022年11月18日 18:34
    16. **/
    17. @RestController
    18. @RequestMapping("/book")
    19. public class BookController {
    20. @Autowired
    21. private BookService bookService;
    22. //模糊查询
    23. @RequestMapping("/list")
    24. public JsonResponseBody list(Book book){
    25. List qurey = bookService.qurey(book);
    26. return new JsonResponseBody<>(1,"ok",qurey);
    27. }
    28. //增加
    29. @RequestMapping("/add")
    30. public JsonResponseBody insert(Book book){
    31. int insert = bookService.insert(book);
    32. return new JsonResponseBody<>();
    33. }
    34. @Data
    35. @AllArgsConstructor
    36. @NoArgsConstructor
    37. class JsonResponseBody{
    38. private Integer code = 200;
    39. private String msg="ok";
    40. private T date;
    41. }
    42. }

    解决跨域问题

    1. package com.zking.spboot.util;
    2. import org.springframework.context.annotation.Configuration;
    3. import org.springframework.web.servlet.config.annotation.CorsRegistry;
    4. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    5. @Configuration
    6. public class CorsMapping implements WebMvcConfigurer {
    7. /*@Override
    8. *
    9. * 重新跨域支持方法
    10. * CorsRegistry 开启跨域注册
    11. */
    12. public void addCorsMappings(CorsRegistry registry) {
    13. //addMapping 添加可跨域的请求地址
    14. registry.addMapping("/**")
    15. //设置跨域 域名权限 规定由某一个指定的域名+端口能访问跨域项目
    16. .allowedOrigins("*")
    17. //是否开启cookie跨域
    18. .allowCredentials(false)
    19. //规定能够跨域访问的方法类型
    20. .allowedMethods("GET","POST","DELETE","PUT","OPTIONS")
    21. //添加验证头信息 token
    22. //.allowedHeaders()
    23. //预检请求存活时间 在此期间不再次发送预检请求
    24. .maxAge(3600);
    25. }
    26. }

    二,前台代码

    首先输入命令 npm install

     npm install

     

    main.js

    1. // The Vue build version to load with the `import` command
    2. // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
    3. import Vue from 'vue'
    4. import ElementUI from 'element-ui' //新添加1
    5. import 'element-ui/lib/theme-chalk/index.css' //新添加2,避免后期打包样式不同,要放在import App from './App';之前
    6. import axios from '@/api/http' //vue项目对axios的全局配置
    7. import App from './App'
    8. import router from './router'
    9. import VueAxios from 'vue-axios'
    10. Vue.use(VueAxios,axios)
    11. Vue.use(ElementUI) //新添加3
    12. Vue.config.productionTip = false
    13. /* eslint-disable no-new */
    14. new Vue({
    15. el: '#app',
    16. router,
    17. components: { App },
    18. template: ''
    19. })

     App.vue

    1. <template>
    2. <div id="app">
    3. <router-view/>
    4. div>
    5. template>
    6. <script>
    7. export default {
    8. name: 'App'
    9. }
    10. script>
    11. <style>
    12. #app {
    13. font-family: 'Avenir', Helvetica, Arial, sans-serif;
    14. -webkit-font-smoothing: antialiased;
    15. -moz-osx-font-smoothing: grayscale;
    16. text-align: center;
    17. color: #2c3e50;
    18. margin-top: 60px;
    19. }
    20. style>

     router/index.js

    1. import Vue from 'vue'
    2. import Router from 'vue-router'
    3. import BookList from '@/views/BookList'
    4. Vue.use(Router)
    5. export default new Router({
    6. routes: [
    7. {
    8. path: '/',
    9. name: 'BookList',
    10. component: BookList
    11. }
    12. ]
    13. })

    api/actoin.js

    1. /**
    2. * 对后台请求的地址的封装,URL格式如下:
    3. * 模块名_实体名_操作
    4. */
    5. export default {
    6. //服务器
    7. 'SERVER': 'http://localhost:8080/spboot',
    8. 'getAll': '/book/list',
    9. 'add': '/book/add',
    10. //获得请求的完整地址,用于mockjs测试时使用
    11. 'getFullPath': k => {
    12. return this.SERVER + this[k];
    13. }
    14. }

    api/http.js

    1. /**
    2. * vue项目对axios的全局配置
    3. */
    4. import axios from 'axios'
    5. import qs from 'qs'
    6. //引入action模块,并添加至axios的类属性urls上
    7. import action from '@/api/action'
    8. axios.urls = action
    9. // axios默认配置
    10. axios.defaults.timeout = 10000; // 超时时间
    11. // axios.defaults.baseURL = 'http://localhost:8080/crm'; // 默认地址
    12. axios.defaults.baseURL = action.SERVER;
    13. //整理数据
    14. // 只适用于 POST,PUT,PATCH,transformRequest` 允许在向服务器发送前,修改请求数据
    15. axios.defaults.transformRequest = function(data) {
    16. data = qs.stringify(data);
    17. return data;
    18. };
    19. // 请求拦截器
    20. axios.interceptors.request.use(function(config) {
    21. // let jwt = sessionStorage.getItem('jwt');
    22. // if (jwt) {
    23. // config.headers['jwt'] = jwt;
    24. // }
    25. return config;
    26. }, function(error) {
    27. return Promise.reject(error);
    28. });
    29. // 响应拦截器
    30. axios.interceptors.response.use(function(response) {
    31. // let jwt = response.headers['jwt'];
    32. // if (jwt) {
    33. // sessionStorage.setItem('jwt', jwt);
    34. // }
    35. return response;
    36. }, function(error) {
    37. return Promise.reject(error);
    38. });
    39. // // 路由请求拦截
    40. // // http request 拦截器
    41. // axios.interceptors.request.use(
    42. // config => {
    43. // //config.data = JSON.stringify(config.data);
    44. // //config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    45. // //config.headers['Token'] = 'abcxyz';
    46. // //判断是否存在ticket,如果存在的话,则每个http header都加上ticket
    47. // // if (cookie.get("token")) {
    48. // // //用户每次操作,都将cookie设置成2小时
    49. // // cookie.set("token", cookie.get("token"), 1 / 12)
    50. // // cookie.set("name", cookie.get("name"), 1 / 12)
    51. // // config.headers.token = cookie.get("token");
    52. // // config.headers.name = cookie.get("name");
    53. // // }
    54. // return config;
    55. // },
    56. // error => {
    57. // return Promise.reject(error.response);
    58. // });
    59. // // 路由响应拦截
    60. // // http response 拦截器
    61. // axios.interceptors.response.use(
    62. // response => {
    63. // if (response.data.resultCode == "404") {
    64. // console.log("response.data.resultCode是404")
    65. // // 返回 错误代码-1 清除ticket信息并跳转到登录页面
    66. // // cookie.del("ticket")
    67. // // window.location.href='http://login.com'
    68. // return
    69. // } else {
    70. // return response;
    71. // }
    72. // },
    73. // error => {
    74. // return Promise.reject(error.response) // 返回接口返回的错误信息
    75. // });
    76. export default axios;

    view/界面

    1. <template>
    2. <div>
    3. <h1 align="center">SpringBoot阶段机试,ts={{ts}}h1>
    4. <el-form :inline="true">
    5. <el-form-item label="书本名称:">
    6. <el-input v-model="bookname" placeholder="请输入书本名称">el-input>
    7. el-form-item>
    8. <el-form-item>
    9. <el-button type="primary" @click="onSubmit">查询el-button>
    10. <el-button type="primary" @click="open">增加el-button>
    11. el-form-item>
    12. el-form>
    13. <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName">
    14. <el-table-column prop="id" label="书本编号" width="180">
    15. el-table-column>
    16. <el-table-column prop="bookname" label="书本名称" width="180">
    17. el-table-column>
    18. <el-table-column prop="price" label="书本价格" width="180">
    19. el-table-column>
    20. <el-table-column prop="booktype" label="书本类型" width="180">
    21. el-table-column>
    22. el-table>
    23. <el-dialog @close="close" title="增加书籍" :visible.sync="dialogFormVisible">
    24. <el-form :model="book" :rules="rules" ref="book">
    25. <el-form-item prop="bookname" label="书本名称" :label-width="formLabelWidth">
    26. <el-input v-model="book.bookname" autocomplete="off">el-input>
    27. el-form-item>
    28. <el-form-item prop="price" label="书本价格" :label-width="formLabelWidth">
    29. <el-input v-model="book.price" autocomplete="off">el-input>
    30. el-form-item>
    31. <el-form-item prop="booktype" label="书本类型" :label-width="formLabelWidth">
    32. <el-select v-model="book.booktype" placeholder="请选择书本类型">
    33. <el-option label="历史" value="历史">el-option>
    34. <el-option label="科学" value="科学">el-option>
    35. el-select>
    36. el-form-item>
    37. el-form>
    38. <div slot="footer" class="dialog-footer">
    39. <el-button @click="dialogFormVisible = false">取 消el-button>
    40. <el-button type="primary" @click="onSubmit1">确 定el-button>
    41. div>
    42. el-dialog>
    43. div>
    44. template>
    45. <style>
    46. .el-table .warning-row {
    47. background: oldlace;
    48. }
    49. .el-table .success-row {
    50. background: #f0f9eb;
    51. }
    52. style>
    53. <script>
    54. export default {
    55. data:function(){
    56. return {
    57. ts:new Date().getTime(),
    58. bookname:'',
    59. tableData:[],
    60. dialogFormVisible:false,
    61. book:{
    62. bookname:'',
    63. price:'',
    64. booktype:'',
    65. },
    66. rules: {
    67. bookname: [
    68. { required: true, message: '请输入书本名称', trigger: 'blur' },
    69. ],
    70. price: [
    71. { required: true, message: '请输入书本价格', trigger: 'blur' },
    72. ],
    73. booktype: [
    74. { required: true, message: '请选择书本类型', trigger: 'blur' },
    75. ],
    76. },
    77. };
    78. },
    79. methods:{
    80. tableRowClassName({row, rowIndex}) {
    81. if (rowIndex === 1) {
    82. return 'warning-row';
    83. } else if (rowIndex === 3) {
    84. return 'success-row';
    85. }
    86. return '';
    87. },
    88. open:function(){
    89. this.dialogFormVisible=true;
    90. },
    91. close:function(){
    92. this.$refs['book'].resetFields();
    93. },
    94. onSubmit:function(){
    95. //1.查询参数
    96. let params = {
    97. bookname:this.bookname
    98. };
    99. //2.请求路径
    100. let url = this.axios.urls.getAll;
    101. //3.发送
    102. this.axios.post(url,params).then(resp=>{
    103. let rs = resp.data;
    104. console.log(rs);
    105. this.tableData = rs.date;
    106. }).catch(err=>{
    107. })
    108. },
    109. onSubmit1:function(){
    110. this.$refs['book'].validate((valid) => {
    111. if(valid){
    112. let url = this.axios.urls.add;
    113. this.axios.post(url,this.book).then(resp=>{
    114. let rs = resp.data;
    115. if(rs.code==200){
    116. this.dialogFormVisible=false;
    117. this.onSubmit();
    118. }
    119. }).catch(err=>{
    120. })
    121. }else{
    122. console.log('error submit!!');
    123. return false;
    124. }
    125. });
    126. }
    127. }
    128. }
    129. script>
    130. <style>
    131. style>

    ==========================以下内容一样可以不用看了===========================

     


       


     


       


     

     

  • 相关阅读:
    这些仪表板常用的数据分析模型,你都见过吗?
    或许你也想做一个这样的动态魔方吗?
    Ribbon负载均衡
    MySQL数据库管理
    怎样自动开始播放网页视频?
    Windows系统配置CUDA编程环境
    pdfjs简单用法
    【Linux】基础:进程的概念
    vue生态技术总结
    go fmt包详解
  • 原文地址:https://blog.csdn.net/weixin_67338832/article/details/127957286