idea与vue+ElementUI搭建前后端分离的CRUD

目录

  • 一、前端
    • 1、先下载四个指令
    • 2、修改端口号&action.js
    • 3、main.js
    • 4、Articles.vue
  • 二、后端
    • 1、导入pom依赖
    • 1、六个配置文件
      • ①applicationContext.xml
      • ②applicationContext-mybatis.xml
      • ③generatorConfig.xml
      • ④jdbc.properties
      • ⑤log4j2.xml
      • ⑥mybatis.cfg.xml
    • 2、配置web.xml&springmvc-servlet.xml
      • ①web.xml:
      • ②springmvc-servlet.xml
    • 3、引入util工具类
      • ①CorsFilter
      • ②JsonData
      • ③PageBean
      • ④ResponseUtil
      • ⑤SeesionUtil
    • 4、自动生成mapper层和model层
    • 5、Biz层和Biz实现层
    • 6、controller
    • 7、运行效果

一、前端

1、先下载四个指令

npm install element-ui -S
npm install axios -S
npm install qs -S
npm install vue-axios -S

2、修改端口号&action.js

3、main.js

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import ElementUI from 'element-ui' // 新添加 1
import 'element-ui/lib/theme-chalk/index.css' // 新添加 2
import App from './App'
import axios from '@/api/http'  //vue项目对axios的全局配置
import VueAxios from 'vue-axios'
import router from './router'

Vue.use(ElementUI);   // 新添加 3
Vue.use(VueAxios,axios);
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

4、Articles.vue

<template>
  <div>
    <el-form :inline="true" :model="formInline" class="user-search">
      <el-form-item label="搜索:">
        <el-input size="small" v-model="formInline.title" placeholder="输入文章标题">el-input>
      el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit()">添加el-button>
      el-form-item>
    el-form>
    
    <el-table size="small" :data="listData" element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" min-width="1">
      el-table-column>
      <el-table-column sortable prop="id" label="文章ID" min-width="1">
      el-table-column>
      <el-table-column sortable prop="title" label="文章标题" min-width="2">
      el-table-column>
      <el-table-column sortable prop="body" label="文章内容" min-width="5">
      el-table-column>
      <el-table-column align="center" label="操作" min-width="1">
        <template slot-scope="scope">
          <el-button size="mini" @click="doEdit(scope.$index, scope.row)">编辑el-button>
          <el-button size="mini" type="danger" @click="deleteUser(scope.$index, scope.row)">删除el-button>
        template>
      el-table-column>
    el-table>
    <el-pagination style="margin-top: 20px;" @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="formInline.page" :page-sizes="[10, 20, 30, 50]" :page-size="100"
      layout="total, sizes, prev, pager, next, jumper" :total="total">
    el-pagination>
    
    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @before-close="closeDialog">
      <el-form label-width="120px" :model="editForm" :rules="rules" ref="editForm">
        <el-form-item label="文章标题" prop="title">
          <el-input size="small" v-model="editForm.title" auto-complete="off" placeholder="请输入文章标题">el-input>
        el-form-item>
        <el-form-item label="文章内容" prop="body">
          <el-input size="small" v-model="editForm.body" auto-complete="off" placeholder="请输入文章内容">el-input>
        el-form-item>
      el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消el-button>
        <el-button size="small" type="primary" class="title" @click="submitForm('editForm')">保存el-button>
      div>
    el-dialog>
  div>
template>



<script>
  export default {
    data() {
      return {
        listData: [],
        formInline: {
          page: 1,
          rows: 10,
          title: ''
        },
        total: 0,
        title: '',
        editFormVisible: false,
        editForm: {
          title: '',
          body: '',
          id: 0
        },
        rules: {
          title: [{
              required: true,
              message: '请输入文章标题',
              trigger: 'blur'
            },
            {
              min: 5,
              max: 10,
              message: '长度在 5 到 10 个字符',
              trigger: 'blur'
            }
          ],
          body: [{
            required: true,
            message: '请输入文章内容',
            trigger: 'blur'
          }]
        }
      };
    },
    methods: {
      handleSizeChange(rows) {
        this.formInline.page = 1;
        this.formInline.rows = rows;
        this.search();
      },
      handleCurrentChange(page) {
        this.formInline.page = page;
        this.search();
      },
      doSearch(params) {
        let url = this.axios.urls.SYSTEM_ARTICLE_LIST;
        // let url = 'http://localhost:8080/T216_SSH/vue/userAction_login.action';

        this.axios.post(url, params).then((response) => {
          console.log(response);
          this.listData = response.data.result;
          this.total = response.data.pageBean.total;
        }).catch(function(error) {
          console.log(error);
        });
      },
      search() {
        this.doSearch(this.formInline);
    },
    closeDialog() {
      this.clearData();
    },
    handleEdit() {
      this.editFormVisible = true;
      this.title = '新增窗体';
    },
    doEdit(index, row) {
      this.editForm.id = row.id;
      this.editForm.title = row.title;
      this.editForm.body = row.body
      this.editFormVisible = true;
      this.title = '编辑窗体';
    },
    clearData() {
      this.title = '';
      this.editForm.id = 0;
      this.editForm.title = '';
      this.editForm.body = '';
      this.editFormVisible = false;
    },
    deleteUser(index, row) {
      this.$confirm('此操作将永久删除该文件,是否继续?','提示',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning'
      }).then(()=>{

        let url = this.axios.urls.SYSTEM_ARTICLE_DEL;
        this.axios.post(url, {id:row.id}).then((response) => {
          console.log(response);
          this.$message({
            message:response.data.msg,
            type:'success'
          });
          this.clearData();
          this.search();
        }).catch(function(error) {
          console.log(error);
        });
      }).catch(()=>{
        this.$message({
          type:'info',
          message:'已取消删除'
        });
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url;
          if (this.editForm.id == 0) {
            url = this.axios.urls.SYSTEM_ARTICLE_ADD;
          } else {
            url = this.axios.urls.SYSTEM_ARTICLE_EDIT;
          }

          this.axios.post(url, this.editForm).then((response) => {
            console.log(response);
            this.$message({
              message:response.data.msg,
              type:'success'
            });
            this.clearData();
            this.search();
          }).catch(function(error) {
            console.log(error);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      }
    },
    created() {
      this.doSearch({});
    }
  }
script>

<style>

style>

二、后端

1、导入pom依赖

<dependencies>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-ormartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aspectsartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>
    
    <dependency>
      <groupId>com.github.pagehelpergroupId>
      <artifactId>pagehelperartifactId>
      <version>${pagehelper.version}version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>${mybatis.spring.version}version>
    dependency>

    
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-dbcp2artifactId>
      <version>${commons.dbcp2.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.commonsgroupId>
      <artifactId>commons-pool2artifactId>
      <version>${commons.pool2.version}version>
    dependency>

    
    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-coreartifactId>
      <version>${log4j2.version}version>
    dependency>
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-apiartifactId>
      <version>${log4j2.version}version>
    dependency>
    
    <dependency>
      <groupId>org.apache.logging.log4jgroupId>
      <artifactId>log4j-webartifactId>
      <version>${log4j2.version}version>
    dependency>

    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>${junit.version}version>
      <scope>testscope>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>${servlet.version}version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>${lombok.version}version>
      <scope>providedscope>
    dependency>

    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>

    
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>
    <dependency>
      <groupId>taglibsgroupId>
      <artifactId>standardartifactId>
      <version>1.1.2version>
    dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.9.3version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-coreartifactId>
      <version>2.9.3version>
    dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-annotationsartifactId>
      <version>2.9.3version>
    dependency>


  dependencies>
<resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.xmlinclude>
        includes>
      resource>
      
      <resource>
        <directory>src/main/resourcesdirectory>
        <includes>
          <include>jdbc.propertiesinclude>
          <include>*.xmlinclude>
        includes>
      resource>
    resources>
<plugin>
          <groupId>org.apache.maven.pluginsgroupId>
          <artifactId>maven-compiler-pluginartifactId>
          <version>${maven.compiler.plugin.version}version>
          <configuration>
            <source>${maven.compiler.source}source>
            <target>${maven.compiler.target}target>
            <encoding>${project.build.sourceEncoding}encoding>
          configuration>
        plugin>
        <plugin>
          <groupId>org.mybatis.generatorgroupId>
          <artifactId>mybatis-generator-maven-pluginartifactId>
          <version>1.3.2version>
          <dependencies>
            
            <dependency>
              <groupId>mysqlgroupId>
              <artifactId>mysql-connector-javaartifactId>
              <version>${mysql.version}version>
            dependency>
          dependencies>
          <configuration>
            <overwrite>trueoverwrite>
          configuration>
        plugin>

1、六个配置文件

①applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    <import resource="applicationContext-mybatis.xml">import>
beans>


②applicationContext-mybatis.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    
    <context:annotation-config/>
    
    <context:component-scan base-package="com.xnx"/>

    <context:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        
        <property name="initialSize" value="10"/>
        
        <property name="maxTotal" value="100"/>
        
        <property name="maxIdle" value="50"/>
        
        <property name="minIdle" value="10"/>
        
        
        <property name="maxWaitMillis" value="-1"/>
    bean>

    
    
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        
        <property name="dataSource" ref="dataSource"/>
        
        <property name="mapperLocations" value="classpath*:com/xnx/**/mapper/*.xml"/>
        
        <property name="typeAliasesPackage" value="com/xnx/**/model"/>
        
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <value>
                            helperDialect=mysql
                        value>
                    property>
                bean>
            array>
        property>
    bean>

    
    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        
        <property name="basePackage" value="com/xnx/**/mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    bean>

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
    <tx:annotation-driven transaction-manager="transactionManager" />
    <aop:aspectj-autoproxy/>
beans>


③generatorConfig.xml


DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    
    <properties resource="jdbc.properties"/>

    
    <classPathEntry location="D:\\0803\\mvn_repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>

    
    <context id="infoGuardian">
        
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
            <property name="suppressDate" value="true"/> 
        commentGenerator>

        
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>

        
        <javaTypeResolver>
            
            <property name="forceBigDecimals" value="false"/>
        javaTypeResolver>

        
        
        
        <javaModelGenerator targetPackage="com.xnx.model"
                            targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false"/>
            
            <property name="constructorBased" value="true"/>
            
            <property name="trimStrings" value="false"/>
            
            <property name="immutable" value="false"/>
        javaModelGenerator>

        
        <sqlMapGenerator targetPackage="com.xnx.mapper"
                         targetProject="src/main/java">
            
            <property name="enableSubPackages" value="false"/>
        sqlMapGenerator>

        
        
        
        
        <javaClientGenerator targetPackage="com.xnx.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            
            <property name="enableSubPackages" value="false"/>
        javaClientGenerator>

        
        
        
        
        
        
        
        
        
        
        
        
        

        <table schema="" tableName="t_vue_articles" domainObjectName="Articles"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            
            
            
            
        table>

    context>
generatorConfiguration>

④jdbc.properties

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

⑤log4j2.xml




<Configuration status="WARN" monitorInterval="30">
    <Properties>
        
        <Property name="LOG_HOME">/root/workspace/lucenedemo/logsProperty>
        <property name="ERROR_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/errorproperty>
        <property name="WARN_LOG_FILE_NAME">/root/workspace/lucenedemo/logs/warnproperty>
        <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%nproperty>
    Properties>

    <Appenders>
        
        <Console name="Console" target="SYSTEM_OUT">
            
            <ThresholdFilter level="trace" onMatch="ACCEPT"
                             onMismatch="DENY" />
            
            
            <PatternLayout pattern="${PATTERN}" />
        Console>

        
        
        <File name="log" fileName="logs/test.log" append="false">
            <PatternLayout
                    pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
        File>
        
        <RollingFile name="RollingFileInfo" fileName="${LOG_HOME}/info.log"
                     filePattern="${LOG_HOME}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            
            <ThresholdFilter level="info" onMatch="ACCEPT"
                             onMismatch="DENY" />
            <PatternLayout
                    pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                
                
                
                <TimeBasedTriggeringPolicy interval="1"
                                           modulate="true" />
                
                
            Policies>
        RollingFile>

        <RollingFile name="RollingFileWarn" fileName="${WARN_LOG_FILE_NAME}/warn.log"
                     filePattern="${WARN_LOG_FILE_NAME}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
            <ThresholdFilter level="warn" onMatch="ACCEPT"
                             onMismatch="DENY" />
            <PatternLayout
                    pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy />
                <SizeBasedTriggeringPolicy size="2 kB" />
            Policies>
            
            <DefaultRolloverStrategy max="20" />
        RollingFile>

        <RollingFile name="RollingFileError" fileName="${ERROR_LOG_FILE_NAME}/error.log"
                     filePattern="${ERROR_LOG_FILE_NAME}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd-HH-mm}-%i.log">
            <ThresholdFilter level="error" onMatch="ACCEPT"
                             onMismatch="DENY" />
            <PatternLayout
                    pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
            <Policies>
                
                <TimeBasedTriggeringPolicy interval="1"
                                           modulate="true" />
                
            Policies>
        RollingFile>

    Appenders>

    
    <Loggers>
        
        <logger name="org.springframework" level="INFO">logger>
        <logger name="org.mybatis" level="INFO">logger>

        
        <logger name="org.springframework" level="ERROR" />
        <logger name="org.hibernate" level="ERROR" />
        <logger name="org.apache.struts2" level="ERROR" />
        <logger name="com.opensymphony.xwork2" level="ERROR" />
        <logger name="org.jboss" level="ERROR" />


        
        <root level="all">
            <appender-ref ref="Console" />
            <appender-ref ref="RollingFileInfo" />
            <appender-ref ref="RollingFileWarn" />
            <appender-ref ref="RollingFileError" />
        root>

    Loggers>

Configuration>

⑥mybatis.cfg.xml


DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <properties resource="jdbc.properties"/>

    <settings>
        <setting name="logImpl" value="LOG4J2"/>
    settings>

    
    <typeAliases>
        
    typeAliases>

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
        plugin>
    plugins>

    
    <environments default="development">
        <environment id="development">
            
            <transactionManager type="jdbc"/>

            
            
            
            
            <dataSource type="POOLED">
                <property name="driver"
                          value="${jdbc.driver}"/>
                <property name="url"
                          value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>


    <mappers>
        <mapper resource="com/xnx/ssm/mapper/BookMapper.xml"/>
    mappers>
configuration>

2、配置web.xml&springmvc-servlet.xml

①web.xml:

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <display-name>Archetype Created Web Applicationdisplay-name>
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>
  
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>

  
  <servlet>
    <servlet-name>SpringMVCservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>/WEB-INF/springmvc-servlet.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
    
    <async-supported>trueasync-supported>
  servlet>
  <servlet-mapping>
    <servlet-name>SpringMVCservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  
  <filter>
    <filter-name>corsFilterfilter-name>
    <filter-class>com.xnx.util.CorsFilterfilter-class>
  filter>
  <filter-mapping>
    <filter-name>corsFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

  <filter>
    <filter-name>encodingFilterfilter-name>
    <filter-class>
      org.springframework.web.filter.CharacterEncodingFilter
    filter-class>
    <async-supported>trueasync-supported>
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
  filter>
  <filter-mapping>
    <filter-name>encodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>
web-app>


②springmvc-servlet.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
    
    <aop:aspectj-autoproxy/>
    <context:component-scan base-package="com.xnx"/>

    
    
    
    <mvc:annotation-driven>mvc:annotation-driven>

    
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView">property>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    bean>

    
    
    
    

    
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="mappingJackson2HttpMessageConverter"/>
            list>
        property>
    bean>
    <bean id="mappingJackson2HttpMessageConverter"
          class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        
        <property name="supportedMediaTypes">
            <list>
                <value>text/html;charset=UTF-8value>
                <value>text/json;charset=UTF-8value>
                <value>application/json;charset=UTF-8value>
            list>
        property>
    bean>
beans>


3、引入util工具类

①CorsFilter

package com.xnx.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xnx
 * @create 2022-09-15 22:17
 */
public class CorsFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

        // Access-Control-Allow-Origin就是我们需要设置的域名
        // Access-Control-Allow-Headers跨域允许包含的头。
        // Access-Control-Allow-Methods是允许的请求方式
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");// *,任何域名
        httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

}

②JsonData

package com.xnx.util;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 服务器返回给客户端的JSON格式的数据
 *
 */
public class JsonData extends HashMap<String, Object> implements Serializable {

	private static final long serialVersionUID = -8855960778711040221L;
	private int code;
	private String msg;
	private Object result;
	
	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public Object getResult() {
		return result;
	}

	public void setResult(Object result) {
		this.result = result;
	}

	public JsonData(int code, String msg, Object result) {
		super();
		this.put("code", code);
		this.put("msg", msg);
		this.put("result", result);
	}

	public JsonData() {
		super();
	}

}

③PageBean

package com.xnx.util;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Map;

public class PageBean implements Serializable {

	private static final long serialVersionUID = 2422581023658455731L;

	//页码
	private int page=1;
	//每页显示记录数
	private int rows=10;
	//总记录数
	private int total=0;
	//是否分页
	private boolean isPagination=true;
	//上一次的请求路径
	private String url;
	//获取所有的请求参数
	private Map<String,String[]> map;
	
	public PageBean() {
		super();
	}
	
	//设置请求参数
	public void setRequest(HttpServletRequest req) {
		String page=req.getParameter("page");
		String rows=req.getParameter("rows");
		String pagination=req.getParameter("pagination");
		this.setPage(page);
		this.setRows(rows);
		this.setPagination(pagination);
		this.url=req.getContextPath()+req.getServletPath();
		this.map=req.getParameterMap();
	}
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map<String, String[]> getMap() {
		return map;
	}

	public void setMap(Map<String, String[]> map) {
		this.map = map;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public void setPage(String page) {
		if(null!=page&&!"".equals(page.trim()))
			this.page = Integer.parseInt(page);
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}
	
	public void setRows(String rows) {
		if(null!=rows&&!"".equals(rows.trim()))
			this.rows = Integer.parseInt(rows);
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}
	
	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return isPagination;
	}
	
	public void setPagination(boolean isPagination) {
		this.isPagination = isPagination;
	}
	
	public void setPagination(String isPagination) {
		if(null!=isPagination&&!"".equals(isPagination.trim()))
			this.isPagination = Boolean.parseBoolean(isPagination);
	}
	
	/**
	 * 获取分页起始标记位置
	 * @return
	 */
	public int getStartIndex() {
		//(当前页码-1)*显示记录数
		return (this.getPage()-1)*this.rows;
	}
	
	/**
	 * 末页
	 * @return
	 */
	public int getMaxPage() {
		int totalpage=this.total/this.rows;
		if(this.total%this.rows!=0)
			totalpage++;
		return totalpage;
	}
	
	/**
	 * 下一页
	 * @return
	 */
	public int getNextPage() {
		int nextPage=this.page+1;
		if(this.page>=this.getMaxPage())
			nextPage=this.getMaxPage();
		return nextPage;
	}
	
	/**
	 * 上一页
	 * @return
	 */
	public int getPreivousPage() {
		int previousPage=this.page-1;
		if(previousPage<1)
			previousPage=1;
		return previousPage;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
				+ "]";
	}
}

④ResponseUtil

package com.xnx.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

public class ResponseUtil {

	public static void write(HttpServletResponse response,Object o)throws Exception{
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		out.println(o.toString());
		out.flush();
		out.close();
	}
}

⑤SeesionUtil

package com.xnx.util;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SessionUtil {
    private static SqlSessionFactory sessionFactory;
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    static {
        sessionFactory = new SqlSessionFactoryBuilder().build(SessionUtil.class.getResourceAsStream("/mybatis.cfg.xml"));
    }

    public static SqlSession openSession() {
        SqlSession session = threadLocal.get();
        if (null == session) {
            session = sessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }

    public static void main(String[] args) {
        SqlSession session = openSession();
        System.out.println(session.getConnection());
        session.close();
//        System.out.println(session.getConnection());
    }

}

4、自动生成mapper层和model层

在mapper层中加入分页模糊查询的方法
Mapper.xml

<select id="listPager" resultType="java.util.Map" parameterType="java.util.Map">
  select * from t_vue_articles where title like concat(concat('%',#{title}),'%')
select>

Mapper

    List<Map> listPager(Map map);

5、Biz层和Biz实现层

Biz:

package com.xnx.biz;

import com.xnx.model.Articles;
import com.xnx.util.PageBean;

import java.util.List;
import java.util.Map;

public interface ArticlesBiz {
    int deleteByPrimaryKey(Integer id);

    int insert(Articles record);

    public int insertSelective(Articles record);

    Articles selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Articles record);

    int updateByPrimaryKeyWithBLOBs(Articles record);

    int updateByPrimaryKey(Articles record);

    List<Map> listPager(Map map, PageBean pageBean);
}

BizImpl

package com.xnx.biz.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xnx.biz.ArticlesBiz;
import com.xnx.mapper.ArticlesMapper;
import com.xnx.model.Articles;
import com.xnx.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author xnx
 * @create 2022-09-15 14:35
 */
@Service
public class ArticlesBizImpl implements ArticlesBiz {
    @Autowired
    private ArticlesMapper articlesMapper;
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return articlesMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Articles record) {
        return articlesMapper.insert(record);
    }

    @Override
    public int insertSelective(Articles record) {
        return articlesMapper.insertSelective(record);
    }

    @Override
    public Articles selectByPrimaryKey(Integer id) {
        return articlesMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Articles record) {
        return articlesMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKeyWithBLOBs(Articles record) {
        return articlesMapper.updateByPrimaryKeyWithBLOBs(record);
    }

    @Override
    public int updateByPrimaryKey(Articles record) {
        return articlesMapper.updateByPrimaryKey(record);
    }

    @Override
    public List<Map> listPager(Map map, PageBean pageBean) {
        if(pageBean!=null&&pageBean.isPagination()){
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
        }
        List<Map> maps = articlesMapper.listPager(map);
        if(pageBean!=null&&pageBean.isPagination()){
            PageInfo info = new PageInfo(maps);
            System.out.println(info);
            pageBean.setTotal(info.getTotal()+"");
        }
        return maps;
//        return articlesMapper.listPager(map);
    }
}

6、controller

package com.xnx.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xnx.biz.ArticlesBiz;
import com.xnx.model.Articles;
import com.xnx.util.PageBean;
import com.xnx.util.JsonData;
import com.xnx.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.rmi.MarshalledObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xnx
 * @create 2022-09-15 14:40
 */
@Controller
@RequestMapping("/articles")
public class ArticlesController {
    @Autowired
    private ArticlesBiz articlesBiz;

    @ResponseBody
    @RequestMapping("/add")
    public String add(Articles articles){
        this.articlesBiz.insertSelective(articles);
        return null;
    }

    @ResponseBody
    @RequestMapping("/update")
    public String update(Articles articles){
        this.articlesBiz.updateByPrimaryKeySelective(articles);
        return null;
    }

    @ResponseBody
    @RequestMapping("/del")
    public String del(Integer id){
        this.articlesBiz.deleteByPrimaryKey(id);
        return null;
    }

    @ResponseBody
    @RequestMapping("/list")
    public List<Map> list(HttpServletRequest request,HttpServletResponse response) throws Exception {
        PageBean pageBean = new PageBean();
        pageBean.setRequest(request);
        ObjectMapper om = new ObjectMapper();
//        ObjectMapper om = new ObjectMapper();
        Map map = new HashMap();
        String title = request.getParameter("title");
        if (title==null){
            title="";
        }
        map.put("title",title);
        List<Map> list = this.articlesBiz.listPager(map,pageBean);
        JsonData js = new JsonData(1,"操作成功",list);
        js.put("pageBean",pageBean);
        ResponseUtil.write(response, om.writeValueAsString(js));
        return null;
    }
}

7、运行效果

idea与vue+ElementUI搭建前后端分离的CRUD_第1张图片
idea与vue+ElementUI搭建前后端分离的CRUD_第2张图片
idea与vue+ElementUI搭建前后端分离的CRUD_第3张图片
在这里插入图片描述

idea与vue+ElementUI搭建前后端分离的CRUD_第4张图片
在这里插入图片描述
idea与vue+ElementUI搭建前后端分离的CRUD_第5张图片
idea与vue+ElementUI搭建前后端分离的CRUD_第6张图片

你可能感兴趣的:(elementui,vue.js,intellij-idea)