从今天开始记录每天写后端代码的记录
今天主要解决了以下几个问题
- 选择了editor.md作为文本编辑器
- 完善了上传图片功能
- 创建了Article表
- 实现了将博客写入数据库的功能
1. Article表
我的想法是先设计简单的表,后面再加功能实现,表内容如下
article | CREATE TABLE `article` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`authorId` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`content` longtext NOT NULL,
`publishDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updateDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`likes` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
包含id,用户id,标题,内容,发布时间,更新时间,点赞数
2. editor.md上传图片功能
下载源码,放入自己的static目录下,我的目录如下所示
新建一个editArticle.html,需要引入相关文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>EditArticle</title>
<link rel="stylesheet" href="plug/editor.md-master/css/editormd.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="plug/editor.md-master/editormd.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/popper.min.js"></script>
<link href="css/bootstrap.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="input-group mb-3">
<input type="text" class="form-control" id="articleTitle" placeholder="articleTitle" aria-label="articleTitle" aria-describedby="button-addon2">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button" id="button-addon2">发布文章</button>
</div>
</div>
</div>
<div id="layout" class="editor">
<div id="test-editormd">
<textarea></textarea>
</div>
</div>
<script>
var testEditor;
testEditor = editormd("test-editormd", {
width: "100%",
height: 640,
syncScrolling: "single",
path: "/plug/editor.md-master/lib/", //你的path路径(原资源文件中lib包在我们项目中所放的位置),这儿要注意
theme: "dark",//工具栏主题
previewTheme: "dark",//预览主题
editorTheme: "pastel-on-dark",//编辑主题
saveHTMLToTextarea: true,
emoji: false,
taskList: true,
tocm: true, // Using [TOCM]
tex: true, // 开启科学公式TeX语言支持,默认关闭
flowChart: true, // 开启流程图支持,默认关闭
sequenceDiagram: true, // 开启时序/序列图支持,默认关闭,
toolbarIcons : function() { //自定义工具栏
return editormd.toolbarModes['full']; // full, simple, mini
},
imageUpload : true,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "/article/uploadImage",//注意你后端的上传图片服务地址
});
$(document).ready(function () {
$("#button-addon2").click(function () {
console.log(testEditor.getMarkdown());
$.post("/article/createArticle",
{
userId:10000,
articleTitle:$("#articleTitle").val(),
articleContent:testEditor.getMarkdown()
},
function (data, status) {
console.log(data);
//$('#receiverShow').text(data.output)
//$('#exampleModalCenter').modal(exampleModalCenter)
// alert("数据:" + data.output + "\n状态:" + status);
});
});
});
</script>
</body>
</html>
需要注意的点是
path: "/plug/editor.md-master/lib/", //你的path路径(原资源文件中lib包在我们项目中所放的位置)
这个路径要写对,就是你的editor.md源码的lib路径
然后就是imageUploadURL就是你后端上传的地址
然后写一个controller,我写的如下所示
@Value("${file.uploadPath}")
private String uploadFilePath;
@RequestMapping(value = "/article/uploadImage")
public @ResponseBody Map<String,String> getArticleImage(@RequestParam(value = "editormd-image-file",required = true)MultipartFile file, HttpServletRequest request, HttpServletResponse response){
String trueFileName=file.getOriginalFilename();
String suffix=trueFileName.substring(trueFileName.lastIndexOf("."));
String fileName=System.currentTimeMillis()+"_"+ (new Random().nextInt(89999)+10000)+suffix;
String path=uploadFilePath;
System.out.println(path);
File target=new File(path,fileName);
Map<String,String> map=new HashMap<>();
try{
file.transferTo(target);
map.put("success","1");
map.put("message","upload success");
} catch (IOException e) {
map.put("success","0");
map.put("message","upload failed");
e.printStackTrace();
}
map.put("url","/source/img/"+fileName);
return map;
}
以上代码是比较简单的,唯一的问题就是需要定义路径
为了能够通过浏览器访问上传的图片,我再application.properties中定义了几个路径
file.uploadPath=D:\\program\\java\\NevergetmeWeb\\NeverGetMeWeb\\src\\main\\resources\\static\\source\\img\\
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,\
classpath:/static/,classpath:/public/,file:${file.uploadPath}
当然我之前已经写好了Article类
Article.class
import lombok.Data;
import java.io.Serializable;
@Data
public class Article implements Serializable {
private static final long serialVersionUID = 2L;
private int id;//主键
private int authorId;
private User author;
private String title;//标题
private String content;//内容
private String publishDate;//发表日期
private String updateDate;//更新日期
private int likes;//喜欢数
public Article(int id,User user,String title,String content,String publishDate,String updateDate,int likes){
this(id,user,title,publishDate,updateDate,likes);
this.content=content;
}
public Article(int id,User user,String title,String publishDate,String updateDate,int likes){
this.id=id;
this.author=user;
this.title=title;
this.publishDate=publishDate;
this.updateDate=updateDate;
this.likes=likes;
}
public Article(int authorId,String title,String content){
this.title=title;
this.authorId=authorId;
this.content=content;
}
}
ArticleService接口
import com.nevergetme.nevergetmeweb.bean.Article;
import java.util.List;
public interface ArticleService {
public List<Article> findAllArticle();
public List<Article> findUserArticle(int userid);
public Article getArticleById(int id);
public int createNewArticle(Article article);
}
以及ArticleServerImpl
import com.nevergetme.nevergetmeweb.bean.Article;
import com.nevergetme.nevergetmeweb.mapper.ArticleMapper;
import com.nevergetme.nevergetmeweb.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ArticleServerImpl implements ArticleService {
@Autowired
private ArticleMapper articleMapper;
@Override
public List<Article> findAllArticle() {
List<Article> articles=articleMapper.getAllArticle();
return articles;
}
@Override
public List<Article> findUserArticle(int userid) {
return articleMapper.getUserArticle(userid);
}
@Override
public Article getArticleById(int id) {
return articleMapper.getArticleById(id);
}
@Override
public int createNewArticle(Article article) {
return articleMapper.createNewArticle(article);
}
}
MyBatis的ArticlesMapper.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.nevergetme.nevergetmeweb.mapper.ArticleMapper">
<resultMap id="articleReusltMap" type="com.nevergetme.nevergetmeweb.bean.Article">
<id column="id" property="id"/>
<result column="title" property="title"/>
<result column="content" property="content"/>
<result column="publishDate" property="publishDate"/>
<result column="updateDate" property="updateDate"/>
<result column="likes" property="likes"/>
<association property="author" column="author" javaType="com.nevergetme.nevergetmeweb.bean.User">
<id property="id" column="user_id"/>
<result property="username" column="username"/>
</association>
</resultMap>
<select id="getAllArticle" resultType="com.nevergetme.nevergetmeweb.bean.Article">
select * from article
</select>
<select id="getUserArticle" parameterType="java.lang.Integer" resultType="com.nevergetme.nevergetmeweb.bean.Article">
select * from article where authorId=#{userid}
</select>
<select id="getArticleById" parameterType="java.lang.Integer" resultMap="articleReusltMap">
select article.id,article.title,article.content,article.publishDate,article.updateDate,article.likes,
user.id as user_id,user.username
from article left join user on article.authorId=user.id where article.id=#{id}
</select>
<insert id="createNewArticle" parameterType="com.nevergetme.nevergetmeweb.bean.Article" useGeneratedKeys="true" keyProperty="id">
insert into article(authorId,title,content) values(#{authorId},#{title},#{content})
</insert>
</mapper>
效果图
返回值
这样就初步实现了创建博客功能