写文章

1.添加pom依赖

com.alibaba
fastjson
1.2.56

2.数据库表和entity无需修改

3.mapper
•ArticleMapper,新增文章方法,增加@Options注解,返回自增主键
@Insert("INSERT INTO t_article (u_id,title,content,create_time) VALUES (#{uId},#{title},#{content},#{createTime}) ")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
void insertArticle(Article article);

•ImgMapper,新增图片接口
@Insert("INSERT INTO t_img(a_id,img_url) VALUES (#{aId},#{imgUrl})")
void insertImg(Img img);

4.service
•ArticleService接口增加方法

void insertArticle(Article article);
•ImgServie接口增加方法

void insertImg(Img img);
•接口实现及单元测试省略

  1. controller
    •ArticleController
    @PostMapping("/add")
    public ResponseResult postArticle(@RequestParam("uId") int uId,
    @RequestParam("title") String title,
    @RequestParam("content") String content) {
    Article article = new Article();
    article.setUId(uId);
    article.setTitle(title);
    article.setContent(content);
    article.setCreateTime(new Date());
    articleService.insertArticle(article);
    //新增文章后,将获取到的自增主键返回给客户端,用于图片地址的写入
    return ResponseResult.success(article.getId());
    }

•新建ImgController,注入ImgService,编写如下方法
@PostMapping("/add")
public ResponseResult addImg(@RequestParam("aId") int aId,
@RequestParam("imgs") String imgs) {
//调用FastJson的序列化工具,将前端传过来的图片数组字符串反序列化为Java的List对象
List imgList = JSONArray.parseArray(imgs, String.class);
//遍历图片List,创建Img对象写入数据库
for (String imgUrl:imgList) {
Img img = new Img();
img.setAId(aId);
img.setImgUrl(imgUrl);
imgService.insertImg(img);
}
return ResponseResult.success();
}

6.swagger测试

7.前端
•注意:在首页点击“写文章”按钮,要判定登录状态,如果没登录,跳转到登录页面;如果已经登录,跳转到写文章页面
•write.vue