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

x33g5p2x  于2022-03-28 转载在 Java  
字(21.4k)|赞(0)|评价(0)|浏览(547)
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安装

  1. npm install vue-quill-editor //富文本编辑器

  1. npm install quill //依赖项

2、创建Write.vue

  1. <template>
  2. <div style="width: 90%; background-color: #99a9bf;margin: auto;top: 0px;left: 0px">
  3. <div style="width:80%;background-color: white;margin: auto;">
  4. <div style="clear: both"></div>
  5. <el-input style="margin-top: 50px;width: 80%" v-model="title" placeholder="请输入文章标题"></el-input>
  6. <div style="text-align: left;width: 80%;margin: auto;margin-top: 30px ">
  7. 上传文章缩略图:
  8. <el-upload
  9. class="avatar-uploader"
  10. action="http://localhost:9090/image"
  11. :show-file-list="false"
  12. :on-success="handleAvatarSuccess"
  13. :before-upload="beforeAvatarUpload">
  14. <img v-if="imageUrl" :src="imageUrl" class="avatar">
  15. <i v-else class="el-icon-plus avatar-uploader-icon" style="border-style: solid;border-radius: 15px"></i>
  16. </el-upload>
  17. </div>
  18. <div style="clear: both"></div>
  19. <div style="margin-top: 20px;float:left; margin-left: 130px ">
  20. 是否原创:
  21. <el-switch
  22. v-model="checked"
  23. active-color="#13ce66"
  24. inactive-color="#ff4949">
  25. </el-switch>
  26. </div>
  27. <div style="clear: both"></div>
  28. <el-input style="margin-top: 50px; margin-bottom: 50px;width: 80%"
  29. type="textarea"
  30. :rows="10"
  31. placeholder="文章摘要"
  32. v-model="abstract_text">
  33. </el-input>
  34. <div style="width: 80%;margin: auto">
  35. <span style="text-align: left;display: block">文章内容:</span>
  36. <quill-editor
  37. ref="myQuillEditor"
  38. v-model="content"
  39. :options="editorOption"
  40. style="height: 500px"
  41. />
  42. </div>
  43. <el-button type="primary" @click="submit" style="margin-top:150px">提交</el-button>
  44. </div>
  45. <div style="margin-top: 100px"></div>
  46. </div>
  47. </template>
  48. <script>
  49. import 'quill/dist/quill.core.css' //引入富文本
  50. import 'quill/dist/quill.snow.css' //引入富文本
  51. import 'quill/dist/quill.bubble.css' //引入富文本
  52. import {quillEditor} from 'vue-quill-editor' //引入富文本
  53. export default {
  54. components: {
  55. quillEditor
  56. },
  57. name: "Write",
  58. data() {
  59. return {
  60. abstract_text: '',
  61. title: "",
  62. checked: false,
  63. is_original: this.checked ? "是" : "否",
  64. imageUrl: "",
  65. thumbnail: "",
  66. content: '<h2>请输入文章内容</h2>',
  67. //富文本编辑器配置
  68. editorOption: {},
  69. blogType : "",
  70. typeName: "选择文章类型",
  71. typeId : ""
  72. }
  73. },
  74. created() {//编写构造函数
  75. this.$axios.get("http://localhost:9090/verify/")
  76. .then((res) => {
  77. }).catch(() => {
  78. this.$router.push({path: "/Login"})
  79. this.$message.error("没有登录请登录后发布文章!");
  80. });
  81. //获取顶部分类信息
  82. this.$axios.get('http://localhost:9090/blogType/queryBlogType')
  83. .then(response => (
  84. this.blogType = response.data
  85. )).catch(function (error) { // 请求失败处理
  86. console.log(error);
  87. });
  88. },
  89. methods: {
  90. submit() {
  91. this.$axios.post('http://localhost:9090/blogging/save', {
  92. title: this.title,
  93. abstract_text: this.abstract_text,
  94. thumbnail: this.thumbnail,
  95. context: this.content,
  96. is_original: this.checked ? "是" : "否",
  97. typeId : this.typeId,
  98. }).then((res) => {
  99. this.$router.push("/");
  100. this.$message.success("文章发布成功!");
  101. }).catch(() => {
  102. this.$message.error("文章发布失败!");
  103. });
  104. },
  105. handleAvatarSuccess(res, file) {
  106. this.imageUrl = URL.createObjectURL(file.raw);
  107. this.thumbnail = "http://localhost:9090/img/" + res;
  108. },
  109. selectType(typename,id) {
  110. this.typeName = typename;
  111. this.typeId = id;
  112. },
  113. beforeAvatarUpload(file) {
  114. const isJPG = file.type === 'image/jpeg';
  115. const isLt2M = file.size / 1024 / 1024 < 2;
  116. if (!isJPG) {
  117. this.$message.error('上传头像图片只能是 JPG 格式!');
  118. }
  119. if (!isLt2M) {
  120. this.$message.error('上传头像图片大小不能超过 2MB!');
  121. }
  122. return isJPG && isLt2M;
  123. }
  124. }
  125. }
  126. </script>
  127. <style scoped>
  128. .avatar-uploader .el-upload {
  129. border: 1px dashed #d9d9d9;
  130. border-radius: 6px;
  131. cursor: pointer;
  132. position: relative;
  133. overflow: hidden;
  134. }
  135. .avatar-uploader .el-upload:hover {
  136. border-color: #409EFF;
  137. }
  138. .avatar-uploader-icon {
  139. font-size: 28px;
  140. color: #8c939d;
  141. width: 178px;
  142. height: 178px;
  143. line-height: 178px;
  144. text-align: center;
  145. }
  146. .avatar {
  147. width: 178px;
  148. height: 178px;
  149. display: block;
  150. }
  151. </style>

3、设置访问路径

  1. import Vue from 'vue'
  2. import App from './App'
  3. import router from './router'
  4. import ElementUI from 'element-ui'
  5. import 'element-ui/lib/theme-chalk/index.css'
  6. import 'default-passive-events'
  7. import './http';
  8. Vue.config.productionTip = false
  9. Vue.use(ElementUI)
  10. /* eslint-disable no-new */
  11. new Vue({
  12. el: '#app',
  13. router,
  14. components: { App },
  15. template: '<App/>'
  16. })

4、访问

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

二、实现上传图片

1、实现上传图片的接口

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

  1. @PostMapping("image")
  2. public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws IOException {
  3. String name = file.getOriginalFilename();
  4. IdWorker idWorker = new IdWorker(new Random().nextInt(10), 1);
  5. long l = idWorker.nextId();
  6. name = l+name;
  7. String property = System.getProperty("user.dir");
  8. file.transferTo(new File(System.getProperty("user.dir")+"\\src\\main\\webapp\\img\\"+name));
  9. return ResponseEntity.ok(name);
  10. }

2、修改前端上传图片的路径

  1. <el-upload
  2. class="avatar-uploader"
  3. action="http://localhost:9090/blog/image"
  4. :show-file-list="false"
  5. :on-success="handleAvatarSuccess"
  6. :before-upload="beforeAvatarUpload">
  7. <img v-if="imageUrl" :src="imageUrl" class="avatar">
  8. <i v-else class="el-icon-plus avatar-uploader-icon" style="border-style: solid;border-radius: 15px"></i>
  9. </el-upload>

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

上传图片成功

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

  1. <template>
  2. <div style="width: 90%; background-color: #99a9bf;margin: auto;top: 0px;left: 0px">
  3. <div style="width:80%;background-color: white;margin: auto;">
  4. <div style="clear: both"></div>
  5. <el-input style="margin-top: 50px;width: 80%" v-model="title" placeholder="请输入文章标题"></el-input>
  6. <div style="text-align: left;width: 80%;margin: auto;margin-top: 30px ">
  7. 上传文章缩略图:
  8. <el-upload
  9. class="avatar-uploader"
  10. action="http://localhost:9090/blog/image"
  11. :show-file-list="false"
  12. :on-success="handleAvatarSuccess"
  13. :before-upload="beforeAvatarUpload">
  14. <img v-if="imageUrl" :src="imageUrl" class="avatar">
  15. <i v-else class="el-icon-plus avatar-uploader-icon" style="border-style: solid;border-radius: 15px"></i>
  16. </el-upload>
  17. </div>
  18. <div style="clear: both"></div>
  19. <div style="margin-top: 20px;float:left; margin-left: 130px ">
  20. 是否原创:
  21. <el-switch
  22. v-model="checked"
  23. active-color="#13ce66"
  24. inactive-color="#ff4949">
  25. </el-switch>
  26. </div>
  27. <div style="clear: both"></div>
  28. <el-input style="margin-top: 50px; margin-bottom: 50px;width: 80%"
  29. type="textarea"
  30. :rows="10"
  31. placeholder="文章摘要"
  32. v-model="abstract_text">
  33. </el-input>
  34. <div style="width: 80%;margin: auto">
  35. <span style="text-align: left;display: block">文章内容:</span>
  36. <quill-editor
  37. ref="myQuillEditor"
  38. v-model="content"
  39. :options="editorOption"
  40. style="height: 500px"
  41. />
  42. </div>
  43. <el-button type="primary" @click="submit" style="margin-top:150px">提交</el-button>
  44. </div>
  45. <div style="margin-top: 100px"></div>
  46. </div>
  47. </template>
  48. <script>
  49. import 'quill/dist/quill.core.css'
  50. import 'quill/dist/quill.snow.css'
  51. import 'quill/dist/quill.bubble.css'
  52. import {quillEditor} from 'vue-quill-editor'
  53. export default {
  54. components: {
  55. quillEditor
  56. },
  57. name: "Write",
  58. data() {
  59. return {
  60. abstract_text: '',
  61. title: "",
  62. checked: false,
  63. is_original: this.checked ? "是" : "否",
  64. imageUrl: "",
  65. thumbnail: "",
  66. content: '<h2>请输入文章内容</h2>',
  67. //富文本编辑器配置
  68. editorOption: {},
  69. blogType : "",
  70. typeName: "选择文章类型",
  71. typeId : ""
  72. }
  73. },
  74. created() {//编写构造函数
  75. },
  76. methods: {
  77. submit() {
  78. this.$http.post('/blog/save', {
  79. title: this.title,
  80. abstract_text: this.abstract_text,
  81. thumbnail: this.thumbnail,
  82. context: this.content,
  83. is_original: this.checked ? "是" : "否",
  84. typeId : this.typeId,
  85. }).then((res) => {
  86. this.$router.push("/");
  87. this.$message.success("文章发布成功!");
  88. }).catch(() => {
  89. this.$message.error("文章发布失败!");
  90. });
  91. },
  92. handleAvatarSuccess(res, file) {
  93. this.imageUrl = URL.createObjectURL(file.raw);
  94. this.thumbnail = "http://localhost:9090/img/" + res;
  95. },
  96. selectType(typename,id) {
  97. this.typeName = typename;
  98. this.typeId = id;
  99. },
  100. beforeAvatarUpload(file) {
  101. const isJPG = file.type === 'image/jpeg';
  102. const isLt2M = file.size / 1024 / 1024 < 2;
  103. if (!isJPG) {
  104. this.$message.error('上传头像图片只能是 JPG 格式!');
  105. }
  106. if (!isLt2M) {
  107. this.$message.error('上传头像图片大小不能超过 2MB!');
  108. }
  109. return isJPG && isLt2M;
  110. }
  111. }
  112. }
  113. </script>
  114. <style scoped>
  115. .avatar-uploader .el-upload {
  116. border: 1px dashed #d9d9d9;
  117. border-radius: 6px;
  118. cursor: pointer;
  119. position: relative;
  120. overflow: hidden;
  121. }
  122. .avatar-uploader .el-upload:hover {
  123. border-color: #409EFF;
  124. }
  125. .avatar-uploader-icon {
  126. font-size: 28px;
  127. color: #8c939d;
  128. width: 178px;
  129. height: 178px;
  130. line-height: 178px;
  131. text-align: center;
  132. }
  133. .avatar {
  134. width: 178px;
  135. height: 178px;
  136. display: block;
  137. }
  138. </style>

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

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

1、HelloWorld.vue

  1. getInfo() {
  2. this.$http.get('blog/queryBlogByPage?title=' + this.title + '&page=' + this.page + '&rows=' + this.rows)
  3. .then(response => (
  4. this.info = response.data,
  5. this.total = this.info.total,
  6. this.totalPage = this.info.totalPage,
  7. this.items = this.info.items
  8. )).catch(function (error) { // 请求失败处理
  9. console.log(error);
  10. });
  11. },

2、Article.vue

  1. getInfo() {
  2. this.$http.get('/blog/queryBlogArticleById?id=' + this.id )
  3. .then(response => (
  4. this.info = response.data,
  5. this.title = this.info.title
  6. )).catch(function (error) { // 请求失败处理
  7. console.log(error);
  8. });
  9. },
  10. selectBlog() {
  11. this.page = 1;
  12. this.rows = 10;
  13. let startTime = (new Date(((this.value1+"").split(",")[0]))).getTime();
  14. let endTime = (new Date(((this.value1+"").split(",")[1]))).getTime();
  15. this.startBlogTime = startTime;
  16. this.endBlogTime = endTime;
  17. this.getInfo();
  18. },
  19. like(){
  20. this.$http.get('blog/blogLikeId?id=' + this.id );
  21. this.getInfo();
  22. },

四、实现登录功能

1、创建ConsumerService

  1. package cn.itbluebox.springbootcsdn.service.Impl;
  2. import cn.itbluebox.springbootcsdn.domain.Consumer;
  3. import cn.itbluebox.springbootcsdn.enums.ExceptionEnum;
  4. import cn.itbluebox.springbootcsdn.exception.BlException;
  5. import cn.itbluebox.springbootcsdn.mapper.ConsumerMapper;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8. import org.springframework.transaction.annotation.Propagation;
  9. import org.springframework.transaction.annotation.Transactional;
  10. @Service
  11. @Transactional(propagation = Propagation.REQUIRED)
  12. public class ConsumerService {
  13. @Autowired
  14. private ConsumerMapper consumerMapper;
  15. public Boolean checkData(String data, Integer type) {
  16. Consumer consumer = new Consumer();
  17. //判断数据类型
  18. switch (type) {
  19. case 1:
  20. consumer.setEmail(data);
  21. break;
  22. case 2:
  23. consumer.setPhone(Long.parseLong(data));
  24. break;
  25. default:
  26. return null;
  27. }
  28. return consumerMapper.selectCount(consumer) == 0;
  29. }
  30. public Consumer queryUser(String email, String password) {
  31. // 查询
  32. Consumer consumer = new Consumer();
  33. consumer.setEmail(email);
  34. consumer.setPassword(password);
  35. Consumer consumer1 = this.consumerMapper.selectOne(consumer);
  36. // 校验用户名
  37. if (consumer1 == null) {
  38. return null;
  39. }
  40. // 用户名密码都正确
  41. return consumer1;
  42. }
  43. public String saveConsumer(Consumer consumer) {
  44. int insert = consumerMapper.insert(consumer);
  45. if (insert != 1) {
  46. throw new BlException(ExceptionEnum.CONSUMER_SAVE_ERROR);
  47. }
  48. return insert + "";
  49. }
  50. public Consumer queryConsumerById(Long id) {
  51. Consumer consumer = new Consumer();
  52. consumer.setId(id);
  53. Consumer consumer1 = consumerMapper.selectOne(consumer);
  54. consumer1.setPassword("");
  55. return consumer1;
  56. }
  57. }

2、创建AuthService

  1. package cn.itbluebox.springbootcsdn.properties;
  2. import cn.itbluebox.springbootcsdn.utils.RsaUtils;
  3. import lombok.Data;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.boot.context.properties.ConfigurationProperties;
  6. import javax.annotation.PostConstruct;
  7. import java.io.File;
  8. import java.security.PrivateKey;
  9. import java.security.PublicKey;
  10. @ConfigurationProperties(prefix = "sc.jwt")
  11. @Data
  12. @Slf4j
  13. public class JwtProperties {
  14. private String secret; // 密钥
  15. private String pubKeyPath;// 公钥
  16. private String priKeyPath;// 私钥
  17. private int expire;// token过期时间
  18. private PublicKey publicKey; // 公钥
  19. private PrivateKey privateKey; // 私钥
  20. private String cookieName;
  21. private Integer cookieMaxAge;
  22. // private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);
  23. /**
  24. * @PostContruct:在构造方法执行之后执行该方法
  25. */
  26. @PostConstruct
  27. public void init(){
  28. try {
  29. File pubKey = new File(pubKeyPath);
  30. File priKey = new File(priKeyPath);
  31. if (!pubKey.exists() || !priKey.exists()) {
  32. // 生成公钥和私钥
  33. RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
  34. }
  35. // 获取公钥和私钥
  36. this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
  37. this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
  38. } catch (Exception e) {
  39. log.error("初始化公钥和私钥失败!", e);
  40. throw new RuntimeException();
  41. }
  42. }
  43. }

3、创建AuthController

  1. package cn.itbluebox.springbootcsdn.web;
  2. import cn.itbluebox.springbootcsdn.enums.ExceptionEnum;
  3. import cn.itbluebox.springbootcsdn.exception.BlException;
  4. import cn.itbluebox.springbootcsdn.properties.JwtProperties;
  5. import cn.itbluebox.springbootcsdn.service.Impl.AuthService;
  6. import cn.itbluebox.springbootcsdn.utils.CookieUtils;
  7. import cn.itbluebox.springbootcsdn.utils.JwtUtils;
  8. import cn.itbluebox.springbootcsdn.utils.UserInfo;
  9. import lombok.extern.slf4j.Slf4j;
  10. import org.apache.commons.lang3.StringUtils;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.boot.context.properties.EnableConfigurationProperties;
  13. import org.springframework.http.HttpStatus;
  14. import org.springframework.http.ResponseEntity;
  15. import org.springframework.web.bind.annotation.CookieValue;
  16. import org.springframework.web.bind.annotation.GetMapping;
  17. import org.springframework.web.bind.annotation.RequestParam;
  18. import org.springframework.web.bind.annotation.RestController;
  19. import javax.servlet.http.Cookie;
  20. import javax.servlet.http.HttpServletRequest;
  21. import javax.servlet.http.HttpServletResponse;
  22. @RestController
  23. @EnableConfigurationProperties(JwtProperties.class)
  24. @Slf4j
  25. public class AuthController {
  26. @Autowired
  27. private AuthService authService;
  28. @Autowired
  29. private JwtProperties prop;
  30. /**
  31. * 登录授权
  32. *
  33. * @return
  34. */
  35. @GetMapping("accredit")
  36. public ResponseEntity<Cookie> authentication(
  37. @RequestParam("email") String email,
  38. @RequestParam("password") String password,
  39. HttpServletRequest request,
  40. HttpServletResponse response) {
  41. // 登录校验
  42. System.out.println(" 登录校验 登录校验 登录校验 登录校验");
  43. String token = authService.authentication(email, password);
  44. if (StringUtils.isBlank(token)) {
  45. log.info("用户授权失败");
  46. return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
  47. }
  48. Cookie cookie = CookieUtils.setGetCookie(request, response, prop.getCookieName(), token, prop.getCookieMaxAge(), true);
  49. return ResponseEntity.ok(cookie);
  50. }
  51. @GetMapping("verify")
  52. public ResponseEntity<UserInfo> verify(
  53. @CookieValue("SC_TOKEN") String token,
  54. HttpServletRequest request,
  55. HttpServletResponse response
  56. ) {
  57. //解析token
  58. System.out.println("解析token解析token解析token解析token解析token");
  59. try {
  60. UserInfo userInfo = JwtUtils.getUserInfo(prop.getPublicKey(), token);
  61. //刷新token,重新生成token
  62. String newToken = JwtUtils.generateToken(userInfo, prop.getPrivateKey(), prop.getExpire());
  63. //写回cookie
  64. CookieUtils.setCookie(request, response, prop.getCookieName(), newToken, prop.getCookieMaxAge(), true);
  65. //返回用户信息
  66. return ResponseEntity.ok(userInfo);
  67. } catch (Exception e) {
  68. //token以过期,或者token篡改
  69. throw new BlException(ExceptionEnum.UN_AUTHORIZED);
  70. }
  71. }
  72. }

5、创建Login.vue

  1. <template>
  2. <div>
  3. <el-card class="box-card" style="width:30%;margin: auto;height: 550px;margin-top: 100px">
  4. <div slot="header" class="clearfix">
  5. <span>登录博客</span>
  6. </div>
  7. <div>
  8. <el-input v-model="email" placeholder="邮箱" style="margin-top: 50px"></el-input>
  9. <el-input v-model="password" placeholder="密码" style="margin-top: 50px"></el-input>
  10. <el-button type="primary" @click="login" style="margin-top: 80px">登录</el-button>
  11. </div>
  12. <div style="float: right">
  13. <el-button @click="register" style="margin-top: 80px">注册账号</el-button>
  14. </div>
  15. </el-card>
  16. </div>
  17. </template>
  18. <script>
  19. export default {
  20. name: "Login",
  21. data() {
  22. return {
  23. email: "",
  24. password: "",
  25. users: {
  26. id: "",
  27. name: "",
  28. image: "",
  29. email: "",
  30. }
  31. }
  32. },
  33. created() {//编写构造函数
  34. this.$http.get("/verify/")
  35. .then((res) => {
  36. this.$router.push({path: "/"})
  37. this.$message.success("已经登录成功请执行其他操作!");
  38. }).catch(() => {
  39. });
  40. },
  41. methods: {
  42. login() {
  43. this.$http.get("/accredit?email=" + this.email + "&password=" + this.password)
  44. .then((res) => {
  45. console.log(res.data.value);
  46. this.$http.get("/verify/")
  47. .then(({data}) => {
  48. this.users = data;
  49. sessionStorage.setItem('userId',this.users.id);
  50. });
  51. this.$message.success("登录成功!");
  52. this.$router.push("/");
  53. }).catch(() => {
  54. this.$message.error("登录失败!");
  55. });
  56. },
  57. register() {
  58. this.$router.push("/Register");
  59. },
  60. },
  61. watch: {
  62. page: function () {
  63. this.getInfo();
  64. }
  65. }
  66. }
  67. </script>
  68. <style scoped>
  69. </style>

6、设置访问路径

  1. import Vue from 'vue'
  2. import Router from 'vue-router'
  3. import HelloWorld from '@/components/HelloWorld'
  4. import Article from '@/components/Article'
  5. import Write from '@/components/Write'
  6. import Login from '@/components/Login'
  7. Vue.use(Router)
  8. export default new Router({
  9. routes: [
  10. {
  11. path: '/',
  12. name: 'HelloWorld',
  13. component: HelloWorld
  14. },
  15. {
  16. path: '/Article',
  17. name: 'Article',
  18. component: Article
  19. },
  20. {
  21. path: '/Write',
  22. name: 'Write',
  23. component: Write
  24. },
  25. {
  26. path: '/Login',
  27. name: 'Login',
  28. component: Login
  29. },
  30. ]
  31. })

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

五、实现发布文章的功能

1、在HelloWorld.vue 节目添加跳转写文章的功能

  1. <el-button @click="goToWrite">写文章</el-button>

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

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

没有登录跳转回登录页面

  1. created() {//编写构造函数
  2. this.$http.get("verify/")
  3. .then((res) => {
  4. }).catch(() => {
  5. this.$router.push({path: "/Login"})
  6. this.$message.error("没有登录请登录后发布文章!");
  7. });
  8. },

3、实现文章保存功能

(1)修改Blog实体类用于接收参数

  1. package cn.itbluebox.springbootcsdn.domain;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. import javax.persistence.Table;
  6. import javax.persistence.Transient;
  7. import java.util.Date;
  8. @Data
  9. @NoArgsConstructor
  10. @AllArgsConstructor
  11. @Table(name = "blog")
  12. public class Blog {
  13. private Long id; //文章id
  14. private String title; //文章标题
  15. private String abstract_text; //文章内容
  16. private String thumbnail; //缩略图
  17. private Date create_time; //创建时间
  18. private Long like_count; //点赞数量
  19. private Long view_count; //浏览量
  20. private Long consumer_id; //用户ID
  21. private String type_id; //类型
  22. private Long blog_article_id; //博客文章ID
  23. @Transient
  24. private String context;
  25. @Transient
  26. private Date last_update_time; //更新时间
  27. @Transient
  28. private Character is_original;
  29. @Transient //Transient声明当前字段不是数据对应的字段
  30. private Long[] typeId;
  31. }
(2)在BlogController当中创建保存的接口

  1. @PostMapping("save")
  2. public ResponseEntity<String> saveBlogging(
  3. @RequestBody Blog blog,
  4. @CookieValue("SC_TOKEN") String token,
  5. HttpServletRequest request, HttpServletResponse response
  6. ){
  7. UserInfo userInfo = JwtUtils.getUserInfo(prop.getPublicKey(), token);
  8. //刷新token,重新生成token
  9. String newToken = JwtUtils.generateToken(userInfo, prop.getPrivateKey(), prop.getExpire());
  10. //写回cookie
  11. CookieUtils.setCookie(request, response, prop.getCookieName(), newToken, prop.getCookieMaxAge(), true);
  12. //返回用户信息
  13. blog.setConsumer_id(userInfo.getId());
  14. String blog_code = blogService.saveBlogging(blog);
  15. return ResponseEntity.ok(blog_code);
  16. }
(3)在blogService和对应实现类当中创建对应的方法

  1. String saveBlogging(Blog blog);

实现类当中的方法

(4)实现BlogServiceImpl和对应的Mapper
  1. ```java
  2. @Transactional
  3. @Override
  4. public String saveBlogging(Blog blog) {
  5. //先插入博客的文章部分
  6. long l = new IdWorker(new Random().nextInt(10), 1).nextId();
  7. String ls = (l + "");
  8. ls = ls.substring(5, ls.length());
  9. BlogArticle blogArticle = new BlogArticle();
  10. blogArticle.setId(Long.parseLong(ls));
  11. blogArticle.setContext(blog.getContext());
  12. blogArticle.setLast_update_time(new Date());
  13. blogArticle.setIs_original(blog.getIs_original());
  14. //插入博客文章的代码
  15. int insert2 = blogArticleMapper.insertSql(blogArticle);
  16. if (insert2 != 1) {
  17. throw new BlException(ExceptionEnum.BLOG_SAVE_ERROR);
  18. }
  19. //插入博客
  20. blog.setCreate_time(new Date());
  21. blog.setLike_count(1L);
  22. blog.setView_count(1L);
  23. blog.setBlog_article_id(blogArticle.getId());
  24. int insert1 = blogMapper.insert(blog);
  25. if (insert1 != 1) {
  26. throw new BlException(ExceptionEnum.BLOG_SAVE_ERROR);
  27. }
  28. return "success";
  29. }

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

运行测试

六、实现文章搜索

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

  1. <el-row >
  2. <el-col :span="16" style="padding-left: 200px;padding-right: 200px;">
  3. <div>
  4. <el-input v-model="title" placeholder="请输入内容"></el-input>
  5. </div>
  6. </el-col>
  7. <el-col :span="8">
  8. <div>
  9. <el-button type="primary" round @click="getInfo()" style="margin-left: -550px;" >搜索</el-button>
  10. </div>
  11. </el-col>
  12. </el-row>

输入内容

七、项目源代码

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

相关文章

最新文章

更多