栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java之Spring Boot+Vue+Element UI前后端分离项目(下-功能完善-发布文章-文章搜索) 【博客论坛项目高仿CSDN】(一篇文章精通系列)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java之Spring Boot+Vue+Element UI前后端分离项目(下-功能完善-发布文章-文章搜索) 【博客论坛项目高仿CSDN】(一篇文章精通系列)

Java 之 Spring Boot + Vue + Element UI 前后端分离项目(上-项目搭建)
Java之Spring Boot+Vue+Element UI前后端分离项目(中-功能完善-实现查询)
Java之Spring Boot+Vue+Element UI前后端分离项目(下-功能完善-发布文章-文章搜索)

源代码下载:https://download.csdn.net/download/qq_44757034/85045367
Java SpringBoot 前后端分离项目高仿CSDN项目源代码(前端Vue+Element UI 后端Java的SpringBoot+Myabtis,数据库Mysql)

一、实现文章发布需要使用富文本编辑框

安装富文本编辑框

1、npm安装
npm install vue-quill-editor     //富文本编辑器

npm install quill           //依赖项

2、创建Write.vue







3、设置访问路径

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'
import 'default-passive-events'
import './http';
Vue.config.productionTip = false
Vue.use(ElementUI)


new Vue({
  el: '#app',
  router,
  components: { App },
  template: ''
})
4、访问

访问:http://localhost:8080/#/Write

二、实现上传图片 1、实现上传图片的接口

在BlogController当中创建对应的上传图片的接口

    @PostMapping("image")
    public ResponseEntity uploadImage(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws IOException {
        String name = file.getOriginalFilename();
        IdWorker idWorker = new IdWorker(new Random().nextInt(10), 1);
        long l = idWorker.nextId();
        name = l+name;
        String property = System.getProperty("user.dir");
        file.transferTo(new File(System.getProperty("user.dir")+"\src\main\webapp\img\"+name));
        return ResponseEntity.ok(name);
    }
2、修改前端上传图片的路径


          
          
        
3、重新运行后端程序测试上传图片的功能




上传图片成功

4、发表文章页面的全部代码






三、设置Axios发起请求统一前缀的路径

https://code100.blog.csdn.net/article/details/123302546

1、HelloWorld.vue

getInfo() {
        this.$http.get('blog/queryBlogByPage?title=' + this.title + '&page=' + this.page + '&rows=' + this.rows)
          .then(response => (
            this.info = response.data,
              this.total = this.info.total,
              this.totalPage = this.info.totalPage,
              this.items = this.info.items
          )).catch(function (error) { // 请求失败处理
          console.log(error);
        });
      },
2、Article.vue

 getInfo() {
            this.$http.get('/blog/queryBlogArticleById?id=' + this.id )
              .then(response => (
                this.info = response.data,
                  this.title = this.info.title
              )).catch(function (error) { // 请求失败处理
              console.log(error);
            });
          },
          selectBlog() {
            this.page = 1;
            this.rows = 10;
            let startTime = (new Date(((this.value1+"").split(",")[0]))).getTime();
            let endTime = (new Date(((this.value1+"").split(",")[1]))).getTime();
            this.startBlogTime = startTime;
            this.endBlogTime = endTime;
            this.getInfo();
          },
          like(){
            this.$http.get('blog/blogLikeId?id=' + this.id );
            this.getInfo();
          },
四、实现登录功能 1、创建ConsumerService


package cn.itbluebox.springbootcsdn.service.Impl;

import cn.itbluebox.springbootcsdn.domain.Consumer;
import cn.itbluebox.springbootcsdn.enums.ExceptionEnum;
import cn.itbluebox.springbootcsdn.exception.BlException;
import cn.itbluebox.springbootcsdn.mapper.ConsumerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.REQUIRED)
public class ConsumerService {

    @Autowired
    private ConsumerMapper consumerMapper;

    public Boolean checkData(String data, Integer type) {

        Consumer consumer = new Consumer();
        //判断数据类型
        switch (type) {
            case 1:
                consumer.setEmail(data);
                break;
            case 2:
                consumer.setPhone(Long.parseLong(data));
                break;
            default:
                return null;
        }
        return consumerMapper.selectCount(consumer) == 0;

    }

    public Consumer queryUser(String email, String password) {
        // 查询
        Consumer consumer = new Consumer();
        consumer.setEmail(email);
        consumer.setPassword(password);
        Consumer consumer1 = this.consumerMapper.selectOne(consumer);
        // 校验用户名
        if (consumer1 == null) {
            return null;
        }
        // 用户名密码都正确
        return consumer1;
    }

    public String saveConsumer(Consumer consumer) {
        int insert = consumerMapper.insert(consumer);
        if (insert != 1) {
            throw new BlException(ExceptionEnum.CONSUMER_SAVE_ERROR);
        }
        return insert + "";
    }

    public Consumer queryConsumerById(Long id) {
        Consumer consumer = new Consumer();
        consumer.setId(id);
        Consumer consumer1 = consumerMapper.selectOne(consumer);
        consumer1.setPassword("");
        return consumer1;
    }
}


2、创建AuthService


package cn.itbluebox.springbootcsdn.properties;

import cn.itbluebox.springbootcsdn.utils.RsaUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

@ConfigurationProperties(prefix = "sc.jwt")
@Data
@Slf4j
public class JwtProperties {

    private String secret; // 密钥

    private String pubKeyPath;// 公钥

    private String priKeyPath;// 私钥

    private int expire;// token过期时间

    private PublicKey publicKey; // 公钥

    private PrivateKey privateKey; // 私钥

    private String cookieName;

    private Integer cookieMaxAge;

//    private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);

    
    @PostConstruct
    public void init(){
        try {
            File pubKey = new File(pubKeyPath);
            File priKey = new File(priKeyPath);
            if (!pubKey.exists() || !priKey.exists()) {
                // 生成公钥和私钥
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            // 获取公钥和私钥
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            log.error("初始化公钥和私钥失败!", e);
            throw new RuntimeException();
        }
    }

}

3、创建AuthController


package cn.itbluebox.springbootcsdn.web;


import cn.itbluebox.springbootcsdn.enums.ExceptionEnum;
import cn.itbluebox.springbootcsdn.exception.BlException;
import cn.itbluebox.springbootcsdn.properties.JwtProperties;
import cn.itbluebox.springbootcsdn.service.Impl.AuthService;
import cn.itbluebox.springbootcsdn.utils.cookieUtils;
import cn.itbluebox.springbootcsdn.utils.JwtUtils;
import cn.itbluebox.springbootcsdn.utils.UserInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.cookievalue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
@Slf4j
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties prop;

    
    @GetMapping("accredit")
    public ResponseEntity authentication(
            @RequestParam("email") String email,
            @RequestParam("password") String password,
            HttpServletRequest request,
            HttpServletResponse response) {
        // 登录校验
        System.out.println(" 登录校验 登录校验 登录校验 登录校验");
        String token = authService.authentication(email, password);
        if (StringUtils.isBlank(token)) {
            log.info("用户授权失败");
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
        cookie cookie = cookieUtils.setGetcookie(request, response, prop.getcookieName(), token, prop.getcookieMaxAge(), true);
        return ResponseEntity.ok(cookie);
    }

    @GetMapping("verify")
    public ResponseEntity verify(
            @cookievalue("SC_TOKEN") String token,
            HttpServletRequest request,
            HttpServletResponse response
    ) {
        //解析token
        System.out.println("解析token解析token解析token解析token解析token");
        try {
            UserInfo userInfo = JwtUtils.getUserInfo(prop.getPublicKey(), token);

            //刷新token,重新生成token
            String newToken = JwtUtils.generateToken(userInfo, prop.getPrivateKey(), prop.getExpire());
            //写回cookie
            cookieUtils.setcookie(request, response, prop.getcookieName(), newToken, prop.getcookieMaxAge(), true);
            //返回用户信息
            return ResponseEntity.ok(userInfo);
        } catch (Exception e) {
            //token以过期,或者token篡改
            throw new BlException(ExceptionEnum.UN_AUTHORIZED);
        }
    }
}

5、创建Login.vue







6、设置访问路径

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Article from '@/components/Article'
import Write from '@/components/Write'
import Login from '@/components/Login'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/Article',
      name: 'Article',
      component: Article
    },
    {
      path: '/Write',
      name: 'Write',
      component: Write
    },
    {
      path: '/Login',
      name: 'Login',
      component: Login
    },
  ]
})

访问页面:http://localhost:8080/#/Login

五、实现发布文章的功能 1、在HelloWorld.vue 节目添加跳转写文章的功能

写文章

goToWrite() {
        this.$router.push("/Write");
      },


2、在Write.vue设置初始化的时候校验是否登录


没有登录跳转回登录页面

 created() {//编写构造函数
      this.$http.get("verify/")
        .then((res) => {
        }).catch(() => {
        this.$router.push({path: "/Login"})
        this.$message.error("没有登录请登录后发布文章!");
      });
    },
3、实现文章保存功能 (1)修改Blog实体类用于接收参数

package cn.itbluebox.springbootcsdn.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "blog")
public class Blog {
    private Long id;              //文章id
    private String title;         //文章标题
    private String abstract_text;       //文章内容
    private String thumbnail;       //缩略图
    private Date create_time;      //创建时间
    private Long like_count;              //点赞数量
    private Long view_count;     //浏览量
    private Long consumer_id;     //用户ID
    private String type_id;       //类型
    private Long blog_article_id;     //博客文章ID
    @Transient
    private String context;
    @Transient
    private Date last_update_time;      //更新时间
    @Transient
    private Character is_original;
    @Transient //Transient声明当前字段不是数据对应的字段
    private Long[] typeId;
}
(2)在BlogController当中创建保存的接口

   @PostMapping("save")
    public ResponseEntity saveBlogging(
            @RequestBody Blog blog,
            @cookievalue("SC_TOKEN") String token,
            HttpServletRequest request, HttpServletResponse response
    ){
        UserInfo userInfo = JwtUtils.getUserInfo(prop.getPublicKey(), token);
        //刷新token,重新生成token
        String newToken = JwtUtils.generateToken(userInfo, prop.getPrivateKey(), prop.getExpire());
        //写回cookie
        cookieUtils.setcookie(request, response, prop.getcookieName(), newToken, prop.getcookieMaxAge(), true);
        //返回用户信息
        blog.setConsumer_id(userInfo.getId());
        String blog_code = blogService.saveBlogging(blog);
        return ResponseEntity.ok(blog_code);
    }
(3)在blogService和对应实现类当中创建对应的方法


  String saveBlogging(Blog blog);

实现类当中的方法

(4)实现BlogServiceImpl和对应的Mapper
```java
 @Transactional
    @Override
    public String saveBlogging(Blog blog) {
        //先插入博客的文章部分
        long l = new IdWorker(new Random().nextInt(10), 1).nextId();
        String ls = (l + "");
        ls = ls.substring(5, ls.length());
        BlogArticle blogArticle = new BlogArticle();
        blogArticle.setId(Long.parseLong(ls));
        blogArticle.setContext(blog.getContext());
        blogArticle.setLast_update_time(new Date());
        blogArticle.setIs_original(blog.getIs_original());
        //插入博客文章的代码
        int insert2 = blogArticleMapper.insertSql(blogArticle);
        if (insert2 != 1) {
            throw new BlException(ExceptionEnum.BLOG_SAVE_ERROR);
        }
        //插入博客
        blog.setCreate_time(new Date());
        blog.setLike_count(1L);
        blog.setView_count(1L);
        blog.setBlog_article_id(blogArticle.getId());
        int insert1 = blogMapper.insert(blog);
        if (insert1 != 1) {
            throw new BlException(ExceptionEnum.BLOG_SAVE_ERROR);
        }
        return "success";
    }

    @Insert("insert into blog_article  VALUES (#{id},#{context},#{last_update_time},#{is_original})")
    int insertSql(BlogArticle blogArticle);

运行测试



六、实现文章搜索 1、 在首页设置文章搜索框

   
      
        
搜索

输入内容

七、项目源代码

https://download.csdn.net/download/qq_44757034/85045367

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781246.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号