Bootstrap

springboot+vue实现增删改查小demo

学习vue,就想着自己搭建一个框架学习一下,本文属于vue与后台的增删改查入门demo,不做讲解,只为了记录一下代码.
后台框架前台框架的搭建自己百度就可以做到了
项目的源码地址 https://gitee.com/cuixt/vueDemo01.git
附上一部自己实现的日记系统,springboot+vue实现github地址
先看一下大体结构

后台

在这里插入图片描述

前台

在这里插入图片描述
废话不多说,直接上代码

后台代码

1.Article

package com.mt.vuedemo.bean;

import javax.validation.constraints.NotNull;
import java.util.Date;

public class Article {
    private Integer id;
    @NotNull(message = "文章 姓名不能为空")
    private String articlename;

    private String articledesc;
    @NotNull(message = "文章 作者不能为空")
    private String articleauthor;

    private Integer idtopping;

    private Date createtime;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getArticlename() {
        return articlename;
    }

    public void setArticlename(String articlename) {
        this.articlename = articlename == null ? null : articlename.trim();
    }

    public String getArticledesc() {
        return articledesc;
    }

    public void setArticledesc(String articledesc) {
        this.articledesc = articledesc == null ? null : articledesc.trim();
    }

    public String getArticleauthor() {
        return articleauthor;
    }

    public void setArticleauthor(String articleauthor) {
        this.articleauthor = articleauthor == null ? null : articleauthor.trim();
    }

    public Integer getIdtopping() {
        return idtopping;
    }

    public void setIdtopping(Integer idtopping) {
        this.idtopping = idtopping;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }
}

2.ArticleExample

package com.mt.vuedemo.bean;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ArticleExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List<Criteria> oredCriteria;

    public ArticleExample() {
        oredCriteria = new ArrayList<Criteria>();
    }

    public void setOrderByClause(String orderByClause) {
        this.orderByClause = orderByClause;
    }

    public String getOrderByClause() {
        return orderByClause;
    }

    public void setDistinct(boolean distinct) {
        this.distinct = distinct;
    }

    public boolean isDistinct() {
        return distinct;
    }

    public List<Criteria> getOredCriteria() {
        return oredCriteria;
    }

    public void or(Criteria criteria) {
        oredCriteria.add(criteria);
    }

    public Criteria or() {
        Criteria criteria = createCriteriaInternal();
        oredCriteria.add(criteria);
        return criteria;
    }

    public Criteria createCriteria() {
        Criteria criteria = createCriteriaInternal();
        if (oredCriteria.size() == 0) {
            oredCriteria.add(criteria);
        }
        return criteria;
    }

    protected Criteria createCriteriaInternal() {
        Criteria criteria = new Criteria();
        return criteria;
    }

    public void clear() {
        oredCriteria.clear();
        orderByClause = null;
        distinct = false;
    }

    protected abstract static class GeneratedCriteria {
        protected List<Criterion> criteria;

        protected GeneratedCriteria() {
            super();
            criteria = new ArrayList<Criterion>();
        }

        public boolean isValid() {
            return criteria.size() > 0;
        }

        public List<Criterion> getAllCriteria() {
            return criteria;
        }

        public List<Criterion> getCriteria() {
            return criteria;
        }

        protected void addCriterion(String condition) {
            if (condition == null) {
                throw new RuntimeException("Value for condition cannot be null");
            }
            criteria.add(new Criterion(condition));
        }

        protected void addCriterion(String condition, Object value, String property) {
            if (value == null) {
                throw new RuntimeException("Value for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value));
        }

        protected void addCriterion(String condition, Object value1, Object value2, String property) {
            if (value1 == null || value2 == null) {
                throw new RuntimeException("Between values for " + property + " cannot be null");
            }
            criteria.add(new Criterion(condition, value1, value2));
        }

        public Criteria andIdIsNull() {
            addCriterion("id is null");
            return (Criteria) this;
        }

        public Criteria andIdIsNotNull() {
            addCriterion("id is not null");
            return (Criteria) this;
        }

        public Criteria andIdEqualTo(Integer value) {
            addCriterion("id =", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotEqualTo(Integer value) {
            addCriterion("id <>", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThan(Integer value) {
            addCriterion("id >", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdGreaterThanOrEqualTo(Integer value) {
            addCriterion("id >=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThan(Integer value) {
            addCriterion("id <", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdLessThanOrEqualTo(Integer value) {
            addCriterion("id <=", value, "id");
            return (Criteria) this;
        }

        public Criteria andIdIn(List<Integer> values) {
            addCriterion("id in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotIn(List<Integer> values) {
            addCriterion("id not in", values, "id");
            return (Criteria) this;
        }

        public Criteria andIdBetween(Integer value1, Integer value2) {
            addCriterion("id between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andIdNotBetween(Integer value1, Integer value2) {
            addCriterion("id not between", value1, value2, "id");
            return (Criteria) this;
        }

        public Criteria andArticlenameIsNull() {
            addCriterion("articleName is null");
            return (Criteria) this;
        }

        public Criteria andArticlenameIsNotNull() {
            addCriterion("articleName is not null");
            return (Criteria) this;
        }

        public Criteria andArticlenameEqualTo(String value) {
            addCriterion("articleName =", value, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameNotEqualTo(String value) {
            addCriterion("articleName <>", value, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameGreaterThan(String value) {
            addCriterion("articleName >", value, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameGreaterThanOrEqualTo(String value) {
            addCriterion("articleName >=", value, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameLessThan(String value) {
            addCriterion("articleName <", value, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameLessThanOrEqualTo(String value) {
            addCriterion("articleName <=", value, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameLike(String value) {
            addCriterion("articleName like", value, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameNotLike(String value) {
            addCriterion("articleName not like", value, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameIn(List<String> values) {
            addCriterion("articleName in", values, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameNotIn(List<String> values) {
            addCriterion("articleName not in", values, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameBetween(String value1, String value2) {
            addCriterion("articleName between", value1, value2, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticlenameNotBetween(String value1, String value2) {
            addCriterion("articleName not between", value1, value2, "articlename");
            return (Criteria) this;
        }

        public Criteria andArticledescIsNull() {
            addCriterion("articleDesc is null");
            return (Criteria) this;
        }

        public Criteria andArticledescIsNotNull() {
            addCriterion("articleDesc is not null");
            return (Criteria) this;
        }

        public Criteria andArticledescEqualTo(String value) {
            addCriterion("articleDesc =", value, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescNotEqualTo(String value) {
            addCriterion("articleDesc <>", value, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescGreaterThan(String value) {
            addCriterion("articleDesc >", value, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescGreaterThanOrEqualTo(String value) {
            addCriterion("articleDesc >=", value, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescLessThan(String value) {
            addCriterion("articleDesc <", value, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescLessThanOrEqualTo(String value) {
            addCriterion("articleDesc <=", value, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescLike(String value) {
            addCriterion("articleDesc like", value, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescNotLike(String value) {
            addCriterion("articleDesc not like", value, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescIn(List<String> values) {
            addCriterion("articleDesc in", values, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescNotIn(List<String> values) {
            addCriterion("articleDesc not in", values, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescBetween(String value1, String value2) {
            addCriterion("articleDesc between", value1, value2, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticledescNotBetween(String value1, String value2) {
            addCriterion("articleDesc not between", value1, value2, "articledesc");
            return (Criteria) this;
        }

        public Criteria andArticleauthorIsNull() {
            addCriterion("articleAuthor is null");
            return (Criteria) this;
        }

        public Criteria andArticleauthorIsNotNull() {
            addCriterion("articleAuthor is not null");
            return (Criteria) this;
        }

        public Criteria andArticleauthorEqualTo(String value) {
            addCriterion("articleAuthor =", value, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorNotEqualTo(String value) {
            addCriterion("articleAuthor <>", value, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorGreaterThan(String value) {
            addCriterion("articleAuthor >", value, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorGreaterThanOrEqualTo(String value) {
            addCriterion("articleAuthor >=", value, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorLessThan(String value) {
            addCriterion("articleAuthor <", value, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorLessThanOrEqualTo(String value) {
            addCriterion("articleAuthor <=", value, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorLike(String value) {
            addCriterion("articleAuthor like", value, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorNotLike(String value) {
            addCriterion("articleAuthor not like", value, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorIn(List<String> values) {
            addCriterion("articleAuthor in", values, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorNotIn(List<String> values) {
            addCriterion("articleAuthor not in", values, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorBetween(String value1, String value2) {
            addCriterion("articleAuthor between", value1, value2, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andArticleauthorNotBetween(String value1, String value2) {
            addCriterion("articleAuthor not between", value1, value2, "articleauthor");
            return (Criteria) this;
        }

        public Criteria andIdtoppingIsNull() {
            addCriterion("idTopping is null");
            return (Criteria) this;
        }

        public Criteria andIdtoppingIsNotNull() {
            addCriterion("idTopping is not null");
            return (Criteria) this;
        }

        public Criteria andIdtoppingEqualTo(Integer value) {
            addCriterion("idTopping =", value, "idtopping");
            return (Criteria) this;
        }

        public Criteria andIdtoppingNotEqualTo(Integer value) {
            addCriterion("idTopping <>", value, "idtopping");
            return (Criteria) this;
        }

        public Criteria andIdtoppingGreaterThan(Integer value) {
            addCriterion("idTopping >", value, "idtopping");
            return (Criteria) this;
        }

        public Criteria andIdtoppingGreaterThanOrEqualTo(Integer value) {
            addCriterion("idTopping >=", value, "idtopping");
            return (Criteria) this;
        }

        public Criteria andIdtoppingLessThan(Integer value) {
            addCriterion("idTopping <", value, "idtopping");
            return (Criteria) this;
        }

        public Criteria andIdtoppingLessThanOrEqualTo(Integer value) {
            addCriterion("idTopping <=", value, "idtopping");
            return (Criteria) this;
        }

        public Criteria andIdtoppingIn(List<Integer> values) {
            addCriterion("idTopping in", values, "idtopping");
            return (Criteria) this;
        }

        public Criteria andIdtoppingNotIn(List<Integer> values) {
            addCriterion("idTopping not in", values, "idtopping");
            return (Criteria) this;
        }

        public Criteria andIdtoppingBetween(Integer value1, Integer value2) {
            addCriterion("idTopping between", value1, value2, "idtopping");
            return (Criteria) this;
        }

        public Criteria andIdtoppingNotBetween(Integer value1, Integer value2) {
            addCriterion("idTopping not between", value1, value2, "idtopping");
            return (Criteria) this;
        }

        public Criteria andCreatetimeIsNull() {
            addCriterion("createTime is null");
            return (Criteria) this;
        }

        public Criteria andCreatetimeIsNotNull() {
            addCriterion("createTime is not null");
            return (Criteria) this;
        }

        public Criteria andCreatetimeEqualTo(Date value) {
            addCriterion("createTime =", value, "createtime");
            return (Criteria) this;
        }

        public Criteria andCreatetimeNotEqualTo(Date value) {
            addCriterion("createTime <>", value, "createtime");
            return (Criteria) this;
        }

        public Criteria andCreatetimeGreaterThan(Date value) {
            addCriterion("createTime >", value, "createtime");
            return (Criteria) this;
        }

        public Criteria andCreatetimeGreaterThanOrEqualTo(Date value) {
            addCriterion("createTime >=", value, "createtime");
            return (Criteria) this;
        }

        public Criteria andCreatetimeLessThan(Date value) {
            addCriterion("createTime <", value, "createtime");
            return (Criteria) this;
        }

        public Criteria andCreatetimeLessThanOrEqualTo(Date value) {
            addCriterion("createTime <=", value, "createtime");
            return (Criteria) this;
        }

        public Criteria andCreatetimeIn(List<Date> values) {
            addCriterion("createTime in", values, "createtime");
            return (Criteria) this;
        }

        public Criteria andCreatetimeNotIn(List<Date> values) {
            addCriterion("createTime not in", values, "createtime");
            return (Criteria) this;
        }

        public Criteria andCreatetimeBetween(Date value1, Date value2) {
            addCriterion("createTime between", value1, value2, "createtime");
            return (Criteria) this;
        }

        public Criteria andCreatetimeNotBetween(Date value1, Date value2) {
            addCriterion("createTime not between", value1, value2, "createtime");
            return (Criteria) this;
        }
    }

    public static class Criteria extends GeneratedCriteria {

        protected Criteria() {
            super();
        }
    }

    public static class Criterion {
        private String condition;

        private Object value;

        private Object secondValue;

        private boolean noValue;

        private boolean singleValue;

        private boolean betweenValue;

        private boolean listValue;

        private String typeHandler;

        public String getCondition() {
            return condition;
        }

        public Object getValue() {
            return value;
        }

        public Object getSecondValue() {
            return secondValue;
        }

        public boolean isNoValue() {
            return noValue;
        }

        public boolean isSingleValue() {
            return singleValue;
        }

        public boolean isBetweenValue() {
            return betweenValue;
        }

        public boolean isListValue() {
            return listValue;
        }

        public String getTypeHandler() {
            return typeHandler;
        }

        protected Criterion(String condition) {
            super();
            this.condition = condition;
            this.typeHandler = null;
            this.noValue = true;
        }

        protected Criterion(String condition, Object value, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.typeHandler = typeHandler;
            if (value instanceof List<?>) {
                this.listValue = true;
            } else {
                this.singleValue = true;
            }
        }

        protected Criterion(String condition, Object value) {
            this(condition, value, null);
        }

        protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
            super();
            this.condition = condition;
            this.value = value;
            this.secondValue = secondValue;
            this.typeHandler = typeHandler;
            this.betweenValue = true;
        }

        protected Criterion(String condition, Object value, Object secondValue) {
            this(condition, value, secondValue, null);
        }
    }
}
  1. ResultCode
package com.mt.vuedemo.bean;

/**
 * @author tian
 * @description
 * @create 2019-02-12 15:39
 */
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;
    }
}

  1. VueLoginInfoVo
package com.mt.vuedemo.bean;

import javax.validation.constraints.NotNull;

/**
 * @author tian
 * @description
 * @create 2019-02-12 15:37
 */
public class VueLoginInfoVo {
    @NotNull(message="用户名不允许为空")
    private String username;

    @NotNull(message="密码不允许为空")
    private String 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;
    }
}

  1. ResultFactory
package com.mt.vuedemo.config;

import com.mt.vuedemo.bean.ResultCode;
import com.mt.vuedemo.result.Result;

/**
 * @author tian
 * @description 返回结构处理生成工厂
 * @create 2019-02-12 15:40
 */
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);
    }
}

  1. SimpleCorsConfig
package com.mt.vuedemo.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author tian
 * @description cors跨域处理
 * @resource https://www.cnblogs.com/cityspace/p/6858969.html
 * @resource https://www.jianshu.com/p/f9c21da2c661
 * @create 2019-01-24 17:10
 */
@Configuration
public class SimpleCorsConfig {
    /**
     * 设置 跨域请求参数,处理跨域请求
     *
     * @return
     */
    @Bean
    public CorsFilter corsFilter()
    {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig());
        return new CorsFilter(source);
    }

    private CorsConfiguration buildConfig()
    {
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 允许跨域访问的域名
        corsConfiguration.addAllowedOrigin("*");
        // 请求头
        corsConfiguration.addAllowedHeader("*");
        // 请求方法
        corsConfiguration.addAllowedMethod(HttpMethod.DELETE);
        corsConfiguration.addAllowedMethod(HttpMethod.POST);
        corsConfiguration.addAllowedMethod(HttpMethod.GET);
        corsConfiguration.addAllowedMethod(HttpMethod.PUT);
        corsConfiguration.addAllowedMethod(HttpMethod.DELETE);
        corsConfiguration.addAllowedMethod(HttpMethod.OPTIONS);
        // 预检请求的有效期,单位为秒。
        corsConfiguration.setMaxAge(3600L);
        // 是否支持安全证书
        corsConfiguration.setAllowCredentials(true);
        return corsConfiguration;
    }
}

  1. ArticleController
package com.mt.vuedemo.controller;

import com.mt.vuedemo.bean.Article;
import com.mt.vuedemo.config.ResultFactory;
import com.mt.vuedemo.result.Result;
import com.mt.vuedemo.server.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * @author tian
 * @description 文章控制器
 * @create 2019-02-13 11:12
 */
@RestController
@RequestMapping("/api")
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    /**
     * @Author cui
     * @Description  查看全部
     * @Date 09:04 2019/2/14 0014
     * @param
     * @return com.mt.vuedemo.result.Result
     **/
    @PostMapping("/getArticleList")
    public Result getArticleList(){
        return articleService.getArticleList();
    }
    /**
     * @Author cui
     * @Description  删除
     * @Date 11:35 2019/2/14 0014
     * @param id
     * @return com.mt.vuedemo.result.Result
     **/
    @GetMapping("/deleteById")
    public Result deleteById( Integer id){
        return articleService.deleteById(id);
    }
    /**
     * @Author cui
     * @Description  添加
     * @Date 11:35 2019/2/14 0014
     * @param article
     * @param bindingResult
     * @return com.mt.vuedemo.result.Result
     **/
    @PostMapping("/addArticle")
    public Result addArticle(@Valid @RequestBody Article article, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            String message = String.format("添加失败,详细信息[%s]。", bindingResult.getFieldError().getDefaultMessage());
            return ResultFactory.buildFailResult(message);
        }
        return articleService.addArticle(article);
    }
    /**
     * @Author cui
     * @Description 根据id查询
     * @Date 11:37 2019/2/14 0014
     * @param id
     * @return com.mt.vuedemo.result.Result
     **/
    @GetMapping("/getArticleById")
    public Result getArticleById(Integer id){
        return articleService.getArticleById(id);
    }
    /**
     * @Author cui
     * @Description  修改
     * @Date 11:55 2019/2/14 0014 
     * @param article
     * @param bindingResult
     * @return com.mt.vuedemo.result.Result
     **/
    @PostMapping("/updateArticle")
    public Result updateArticle(@Valid @RequestBody Article article, BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            String message = String.format("修改失败,详细信息[%s]。", bindingResult.getFieldError().getDefaultMessage());
            return ResultFactory.buildFailResult(message);
        }
        return articleService.updateArticle(article);
    }
}

  1. LoginController
package com.mt.vuedemo.controller;

import com.mt.vuedemo.bean.VueLoginInfoVo;
import com.mt.vuedemo.config.ResultFactory;
import com.mt.vuedemo.result.Result;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Objects;

/**
 * @author tian
 * @description
 * @create 2019-02-12 15:52
 */
@Controller
public class LoginController {
    /**
     * 登录控制器,前后端分离用的不同协议和端口,所以需要加入@CrossOrigin支持跨域。
     * 给VueLoginInfoVo对象加入@Valid注解,并在参数中加入BindingResult来获取错误信息。
     * 在逻辑处理中我们判断BindingResult知否含有错误信息,如果有错误信息,则直接返回错误信息。
     */
    @CrossOrigin
    @RequestMapping(value = "/api/login", method = RequestMethod.POST, produces = "application/json; charset=UTF-8")
    @ResponseBody
    public Result login(@Valid @RequestBody VueLoginInfoVo loginInfoVo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String message = String.format("登陆失败,详细信息[%s]。", bindingResult.getFieldError().getDefaultMessage());
            return ResultFactory.buildFailResult(message);
        }
        if (!Objects.equals("root", loginInfoVo.getUsername()) || !Objects.equals("123456", loginInfoVo.getPassword())) {
            String message = String.format("登陆失败,详细信息[用户名、密码信息不正确]。");
            return ResultFactory.buildFailResult(message);
        }
        return ResultFactory.buildSuccessResult("登陆成功。");
    }

}

  1. ArticleMapper
package com.mt.vuedemo.dao;

import com.mt.vuedemo.bean.Article;
import com.mt.vuedemo.bean.ArticleExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

@Repository
public interface ArticleMapper {
    long countByExample(ArticleExample example);

    int deleteByExample(ArticleExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Article record);

    int insertSelective(Article record);

    List<Article> selectByExample(ArticleExample example);

    Article selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") Article record, @Param("example") ArticleExample example);

    int updateByExample(@Param("record") Article record, @Param("example") ArticleExample example);

    int updateByPrimaryKeySelective(Article record);

    int updateByPrimaryKey(Article record);
}

10.result

package com.mt.vuedemo.result;

/**
 * @author tian
 * @description
 * @create 2019-02-12 15:38
 */
public class Result {
    /**
     * 响应状态码
     */
    private int code;
    /**
     * 响应提示信息
     */
    private String message;
    /**
     * 响应结果对象
     */
    private Object data;

    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;
    }
}

  1. ArticleService
package com.mt.vuedemo.server;

import com.mt.vuedemo.bean.Article;
import com.mt.vuedemo.bean.ArticleExample;
import com.mt.vuedemo.config.ResultFactory;
import com.mt.vuedemo.dao.ArticleMapper;
import com.mt.vuedemo.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.Date;

/**
 * @author tian
 * @description 文章服务
 * @create 2019-02-13 11:15
 */
@Service
public class ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    public Result getArticleList() {
        ArticleExample example = new ArticleExample();
        example.createCriteria().andIdIsNotNull();
        return ResultFactory.buildSuccessResult(articleMapper.selectByExample(example));
    }

    public Result deleteById(Integer id) {
        Assert.notNull(id,"id为空");
        int i = articleMapper.deleteByPrimaryKey(id);
        return commonResult(i,"删除");
    }

    public Result addArticle(Article article) {
        article.setCreatetime(new Date());
        int i = articleMapper.insertSelective(article);
        return commonResult(i,"添加");
    }

    public Result commonResult(int i,String msg){
        if (i==1){
            return ResultFactory.buildSuccessResult(msg+"成功");
        }else {
            return ResultFactory.buildSuccessResult(msg+"失败");
        }
    }

    public Result getArticleById(Integer id) {
        Assert.notNull(id,"id为空");
        return ResultFactory.buildSuccessResult( articleMapper.selectByPrimaryKey(id));

    }

    public Result updateArticle(Article article) {
        int i = articleMapper.updateByPrimaryKeySelective(article);
        return commonResult(i,"修改");
    }
}

  1. generatorConfigHaveExample.xml

修改数据库连接驱动,数据库连接信息

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<!-- 配置Run As Maven build : Goals 参数 : mybatis-generator:generate -Dmybatis.generator.overwrite=true -->
<!-- 配置 tableName,使用 Run As Maven build 生成 dao model 层 -->
<!--带example 驱动连接高级-->
<generatorConfiguration>
    <!-- 配置文件路径-->
    <!--<properties url="${mybatis.generator.generatorConfig.properties}"/>-->

    <!--数据库驱动包路径 -->
    <classPathEntry location="G:\desktop\generator\lib\mysql-connector-java-8.0.13.jar"/>

    <context id="DB2Tables" targetRuntime="MyBatis3">
        <!--关闭注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>

        <!--数据库连接信息 -->
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
                        connectionURL="jdbc:mysql://127.0.0.1:3306/vuedemo01?useUnicode=true;characterEncoding=utf-8;useSSL=false;serverTimezone=GMT%2B8"
                        userId="root"
                        password="root">
            <property name="nullCatalogMeansCurrent" value="true"/>
        </jdbcConnection>

        <!--生成的model 包路径 -->
        <javaModelGenerator targetPackage="com.mt.vuedemo.bean" targetProject="src/main/java">
            <property name="enableSubPackages" value="ture"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>

        <!--生成xml mapper文件 路径 -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <!-- 生成的Dao接口 的包路径 -->
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.mt.vuedemo.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="ture"/>
        </javaClientGenerator>

        <!--对应数据库表名,多个表,请复制指定 -->
        <!--<table tableName="article"></table>-->

        <table schema="vuedemo01"  tableName="article" domainObjectName="Article" />
        <!--<table tableName="T_ROLE"></table>-->
        <!--<table tableName="T_USER_ROLE"></table>-->
        <!--<table tableName="T_PERMISSION"></table>-->
    </context>
</generatorConfiguration>
  1. ArticleMapper.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.mt.vuedemo.dao.ArticleMapper">
  <resultMap id="BaseResultMap" type="com.mt.vuedemo.bean.Article">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="articleName" jdbcType="VARCHAR" property="articlename" />
    <result column="articleDesc" jdbcType="VARCHAR" property="articledesc" />
    <result column="articleAuthor" jdbcType="VARCHAR" property="articleauthor" />
    <result column="idTopping" jdbcType="INTEGER" property="idtopping" />
    <result column="createTime" jdbcType="TIMESTAMP" property="createtime" />
  </resultMap>
  <sql id="Example_Where_Clause">
    <where>
      <foreach collection="oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Update_By_Example_Where_Clause">
    <where>
      <foreach collection="example.oredCriteria" item="criteria" separator="or">
        <if test="criteria.valid">
          <trim prefix="(" prefixOverrides="and" suffix=")">
            <foreach collection="criteria.criteria" item="criterion">
              <choose>
                <when test="criterion.noValue">
                  and ${criterion.condition}
                </when>
                <when test="criterion.singleValue">
                  and ${criterion.condition} #{criterion.value}
                </when>
                <when test="criterion.betweenValue">
                  and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
                </when>
                <when test="criterion.listValue">
                  and ${criterion.condition}
                  <foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
                    #{listItem}
                  </foreach>
                </when>
              </choose>
            </foreach>
          </trim>
        </if>
      </foreach>
    </where>
  </sql>
  <sql id="Base_Column_List">
    id, articleName, articleDesc, articleAuthor, idTopping, createTime
  </sql>
  <select id="selectByExample" parameterType="com.mt.vuedemo.bean.ArticleExample" resultMap="BaseResultMap">
    select
    <if test="distinct">
      distinct
    </if>
    <include refid="Base_Column_List" />
    from article
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
    <if test="orderByClause != null">
      order by ${orderByClause}
    </if>
  </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from article
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from article
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <delete id="deleteByExample" parameterType="com.mt.vuedemo.bean.ArticleExample">
    delete from article
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </delete>
  <insert id="insert" parameterType="com.mt.vuedemo.bean.Article">
    insert into article (id, articleName, articleDesc, 
      articleAuthor, idTopping, createTime
      )
    values (#{id,jdbcType=INTEGER}, #{articlename,jdbcType=VARCHAR}, #{articledesc,jdbcType=VARCHAR}, 
      #{articleauthor,jdbcType=VARCHAR}, #{idtopping,jdbcType=INTEGER}, #{createtime,jdbcType=TIMESTAMP}
      )
  </insert>
  <insert id="insertSelective" parameterType="com.mt.vuedemo.bean.Article">
    insert into article
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="articlename != null">
        articleName,
      </if>
      <if test="articledesc != null">
        articleDesc,
      </if>
      <if test="articleauthor != null">
        articleAuthor,
      </if>
      <if test="idtopping != null">
        idTopping,
      </if>
      <if test="createtime != null">
        createTime,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="articlename != null">
        #{articlename,jdbcType=VARCHAR},
      </if>
      <if test="articledesc != null">
        #{articledesc,jdbcType=VARCHAR},
      </if>
      <if test="articleauthor != null">
        #{articleauthor,jdbcType=VARCHAR},
      </if>
      <if test="idtopping != null">
        #{idtopping,jdbcType=INTEGER},
      </if>
      <if test="createtime != null">
        #{createtime,jdbcType=TIMESTAMP},
      </if>
    </trim>
  </insert>
  <select id="countByExample" parameterType="com.mt.vuedemo.bean.ArticleExample" resultType="java.lang.Long">
    select count(*) from article
    <if test="_parameter != null">
      <include refid="Example_Where_Clause" />
    </if>
  </select>
  <update id="updateByExampleSelective" parameterType="map">
    update article
    <set>
      <if test="record.id != null">
        id = #{record.id,jdbcType=INTEGER},
      </if>
      <if test="record.articlename != null">
        articleName = #{record.articlename,jdbcType=VARCHAR},
      </if>
      <if test="record.articledesc != null">
        articleDesc = #{record.articledesc,jdbcType=VARCHAR},
      </if>
      <if test="record.articleauthor != null">
        articleAuthor = #{record.articleauthor,jdbcType=VARCHAR},
      </if>
      <if test="record.idtopping != null">
        idTopping = #{record.idtopping,jdbcType=INTEGER},
      </if>
      <if test="record.createtime != null">
        createTime = #{record.createtime,jdbcType=TIMESTAMP},
      </if>
    </set>
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByExample" parameterType="map">
    update article
    set id = #{record.id,jdbcType=INTEGER},
      articleName = #{record.articlename,jdbcType=VARCHAR},
      articleDesc = #{record.articledesc,jdbcType=VARCHAR},
      articleAuthor = #{record.articleauthor,jdbcType=VARCHAR},
      idTopping = #{record.idtopping,jdbcType=INTEGER},
      createTime = #{record.createtime,jdbcType=TIMESTAMP}
    <if test="_parameter != null">
      <include refid="Update_By_Example_Where_Clause" />
    </if>
  </update>
  <update id="updateByPrimaryKeySelective" parameterType="com.mt.vuedemo.bean.Article">
    update article
    <set>
      <if test="articlename != null">
        articleName = #{articlename,jdbcType=VARCHAR},
      </if>
      <if test="articledesc != null">
        articleDesc = #{articledesc,jdbcType=VARCHAR},
      </if>
      <if test="articleauthor != null">
        articleAuthor = #{articleauthor,jdbcType=VARCHAR},
      </if>
      <if test="idtopping != null">
        idTopping = #{idtopping,jdbcType=INTEGER},
      </if>
      <if test="createtime != null">
        createTime = #{createtime,jdbcType=TIMESTAMP},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.mt.vuedemo.bean.Article">
    update article
    set articleName = #{articlename,jdbcType=VARCHAR},
      articleDesc = #{articledesc,jdbcType=VARCHAR},
      articleAuthor = #{articleauthor,jdbcType=VARCHAR},
      idTopping = #{idtopping,jdbcType=INTEGER},
      createTime = #{createtime,jdbcType=TIMESTAMP}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>
  1. application.yml
server:
  port: 8088

spring:
  datasource:
    name: test
    url: jdbc:mysql://127.0.0.1:3306/vuedemo01?useUnicode=true;characterEncoding=utf-8;useSSL=false;serverTimezone=GMT%2B8
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20

## 该配置节点为独立的节点,有很多同学容易将这个配置放在spring的节点下,导致配置无法被识别
mybatis:
  mapper-locations: classpath:mapper/*.xml  #注意:一定要对应mapper映射xml文件的所在路径
  type-aliases-package: com.mt.vuedemo.bean  # 注意:对应实体类的路径
  1. pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.mt</groupId>
    <artifactId>vuedemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>vuedemo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <!-- alibaba的druid数据库连接池 -->
        <!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.13</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <configurationFile>src/main/resources/generator/generatorConfigHaveExample.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
                <executions>
                    <execution>
                        <id>Generate MyBatis Artifacts</id>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.5</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

前台代码

1.config/index.js

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    // proxyTable: {},
    // 路由接口代理配置
    proxyTable: {
      '/api': {
        target: 'https://localhost:8088',
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    },

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8081, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: true,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: false,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

  1. BlogFooter
<template>
    <div>
      <!--页面尾部-->
    </div>
</template>
<script>
  export default {
    name: 'BlogFooter'
  }
</script>
<style scoped>

</style>

  1. BlogHeader
<template>
    <div>
      <!--页面头部-->
    </div>
</template>
<script>
  export default {
    name: 'BlogHeader'
}
</script>
<style scoped>

</style>

  1. BlogIndex

<template>
  <div>
  <el-table
    :data="tableData"
    style="width: 100%">
    <el-table-column
      prop="id"
      label="序号"
      width="180">
    </el-table-column>
    <el-table-column
      prop="articlename"
      label="名称"
      width="180">
    </el-table-column>
    <el-table-column
      prop="articleauthor"
      label="作者">
    </el-table-column>
    <el-table-column
      fixed="right"
      label="操作"
      width="150">
      <template slot-scope="scope">
        <el-button type="text" @click="open6(scope.row)" size="small">删除</el-button>
        <el-button type="text" @click="open1(true,scope.row.id)" size="small">修改</el-button>
      </template>
    </el-table-column>
  </el-table>
    <el-button type="primary" @click="open1(false)" id="id1">添加</el-button>
  </div>

</template>


<script>

import BlogHeader from './BlogHeader'
import BlogFooter from './BlogFooter'
export default {
  name: 'BlogIndex',
  components: { BlogHeader, BlogFooter},
  // comments: { BlogHeader, BlogFooter },
  inject:['reload'],
  data() {
    return {
      tableData: []
    }
  },
  mounted:function() {
    this.getArticleList();
  },
  methods: {
    getArticleList () {
      this.$axios
        .post('/getArticleList',{
        })
        .then(successResponse =>{
          this.tableData = successResponse.data.data
          console.log(successResponse.data.data)
        })
    },
    deleteClick(row) {
      this.$axios
        .get('/deleteById',{
          params :{
            id:row.id
          }
        })
        .then(successResponse =>{
          this.reload()
        })
    },
      open6(row) {
      let _row = row
        this.$confirm('请确认是否删除?', '确认信息', {
          distinguishCancelAndClose: true,
          confirmButtonText: '删除',
          cancelButtonText: '放弃'
        })
          .then(() => {
            this.$message({
              type: 'success',
              message: '删除成功',
            });
            this.deleteClick(_row)
          })
          .catch(action => {
            this.$message({
              type: 'info',
              message: action === 'cancel'
                ? '操作取消'
                : '操作关闭'
            })
          });
      },
      open1 (isUpdate,rowId) {
        //传对象
        // row['isUpdate']=isUpdate;
        // this.$router.push({path: '/add',query:row});
        this.$router.push({path: '/add',query:{isUpdate:isUpdate,rowId:rowId}});
      }
  }
}

</script>

<style scoped>
  #id1 {
    float: right;
    margin:10px  70px;
  }
</style>

  1. BlogLogin
<template>
  <div>
      <blog-header></blog-header>
      <hr/>
  <div >
  用户名:<input type = "text" v-model="loginInfoVo.username" placeholder="请输入用户名"/>
  <br/>
  密码:<input type="password" v-model="loginInfoVo.password" placeholder="请输入密码">
  <br/>
    <button v-on:click="login">登录</button>
    <br/>
    <br/>
    登录验证情况:<textarea cols ="30" rows="3" v-model = "responseResult"></textarea></div>
  <blog-footer></blog-footer>
  </div>

</template>

<script>
import BlogHeader from './BlogHeader'
import BlogFooter from './BlogFooter'
export default {
  name: 'BlogLogin',
  components: {BlogFooter, BlogHeader },
  data () {
    return {
      loginInfoVo: { username: '', password: '' },
      responseResult: []
    }
  },
  methods: {
    login () {
      this.$axios
        .post('/login', {
          username: this.loginInfoVo.username,
          password: this.loginInfoVo.password
        })
        .then(successResponse => {
          this.responseResult = JSON.stringify(successResponse.data)
          if (successResponse.data.code === 200) {
            this.$router.replace({path: '/index'})

          }
        })
        .catch(failResponse => {})
    }
  }
}
</script>

<style scoped>

</style>

  1. BlogUpdate
<template>
  <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
    <el-form-item label="文章名称" prop="name">
      <el-input v-model="ruleForm.name"></el-input>
    </el-form-item>
    <el-form-item label="文章作者" prop="authorName">
      <el-input v-model="ruleForm.authorName"></el-input>
    </el-form-item>
    <!--<el-form-item label="文章类型" prop="region">-->
      <!--<el-select v-model="ruleForm.region" placeholder="请选择文章类型">-->
        <!--<el-option label="原创" value="shanghai"></el-option>-->
        <!--<el-option label="转载" value="beijing"></el-option>-->
      <!--</el-select>-->
    <!--</el-form-item>-->
    <!--<el-form-item label="是否置顶" prop="delivery">-->
      <!--<el-switch v-model="ruleForm.delivery"></el-switch>-->
    <!--</el-form-item>-->
    <el-form-item>
      <el-button type="primary" @click="updateForm('ruleForm',ruleForm)" v-if="isUpdate">
        更新修改</el-button>
      <el-button type="primary" @click="submitForm('ruleForm',ruleForm)" v-else>
        立即创建</el-button>
      <el-button @click="resetForm('ruleForm')">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  name: 'BlogUpdate',
  data() {
    return {
      isUpdate: '',
      ruleForm: {
        name: '',
        authorName: '',
        region: '',
        delivery: false
      },
      rules: {
        name: [
          { required: true, message: '请输入文章名称', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        authorName: [
          { required: true, message: '请输入文章作者', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '请选择文章类型', trigger: 'change' }
        ]
      }
    };

  },
  mounted:function () {
    this.isUpdateTrue();
  },
  methods: {
    submitForm(formName,ruleForm) {
      console.log(ruleForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          this.$axios
            .post('/addArticle',{
              articlename :ruleForm.name,
              articleauthor: ruleForm.authorName
            })
            .then(successResponse =>{
              this.$message({
                message: '添加成功',
                type: 'success'
              });
              this.$router.push({path: '/index'});
              // alert('submit success!');
            })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    updateForm(formName,ruleForm) {
      console.log(ruleForm)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          this.$axios
            .post('/updateArticle',{
              id:this.$route.query.rowId,
              articlename :ruleForm.name,
              articleauthor: ruleForm.authorName
            })
            .then(successResponse =>{
              //alert('update success!');
              this.$message({
                message: '修改成功',
                type: 'success'
              });
              this.$router.push({path: '/index'});
            })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    isUpdateTrue() {
      this.isUpdate=this.$route.query.isUpdate;
      let rowId = this.$route.query.rowId;
      if (rowId != undefined && rowId != '' && rowId != null){
        this.$axios.get('/getArticleById',{
          params: {
            id:rowId
          }
        }).then(successResponse =>{
          this.ruleForm.name =successResponse.data.data.articlename;
          this.ruleForm.authorName = successResponse.data.data.articleauthor;
        })
      }
    }
  }
}
</script>

<style scoped>

</style>

  1. src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
// import HelloWorld from '@/components/HelloWorld'
import BlogLogin from '@/components/BlogLogin'
import BlogIndex from '@/components/BlogIndex'
import BlogUpdate from '../components/BlogUpdate'
Vue.use(Router)
export default new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/index',
      name: 'BlogIndex',
      component: BlogIndex
    },
    {
      path: '/manage',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'BlogLogin',
      component: BlogLogin
    },
    {
      path: '/add',
      name: 'BlogUpdate',
      component: BlogUpdate
    }
  ]
})

  1. App.Vue
<template>
  <div id="app">
    <!--<img src="./assets/logo.png">-->
    <router-view v-if="isRouterAlive"/>
  </div>
</template>
<script>
export default {
  name: 'App',
  provide () {
    return {
      reload : this.reload
    }
  },
  data () {
    return {
      isRouterAlive: true
    }
  },
  methods: {
    reload () {
      this.isRouterAlive = false
      this.$nextTick(function () {
        this.isRouterAlive = true
      })
    }
  }
}
</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

  1. 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 App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

// 引用axios,并设置基础URL为后端服务api地址
var axios = require('axios')
axios.defaults.baseURL = 'http://localhost:8088/api'
// 将API方法绑定到全局
Vue.prototype.$axios = axios
Vue.config.productionTip = false
Vue.use(ElementUI)

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

mysql

/*
 Navicat Premium Data Transfer

 Source Server         : localhost
 Source Server Type    : MySQL
 Source Server Version : 80014
 Source Host           : localhost:3306
 Source Schema         : vuedemo01

 Target Server Type    : MySQL
 Target Server Version : 80014
 File Encoding         : 65001

 Date: 14/02/2019 13:55:39
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for article
-- ----------------------------
DROP TABLE IF EXISTS `article`;
CREATE TABLE `article`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `articleName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文章名称',
  `articleDesc` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文章描述',
  `articleAuthor` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '文章作者',
  `idTopping` int(11) NULL DEFAULT NULL COMMENT '是否置顶 0 不置顶 1 置顶 ',
  `createTime` datetime(0) NULL DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 22 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

现在项目已经全部搭建完成,根据个人配置情况修改下配置即可使用,主要是数据库连接地址。有错误欢迎留言

;