更多文章接口(findAll, update, delete)

之前已經(jīng)完成了添加文章和查詢的接口,接下來繼續(xù)實(shí)現(xiàn)以下接口

  1. 查詢所有
  2. 更新
  3. 刪除

Controller 層

在 postApi.java里面添加

    @GetMapping("")
    public List<Post> all() {
        return postService.all();
    }

    /**
     *  更新文章,需要登錄
     * @param post  需要修改的內(nèi)容
     * @param id    文章 id
     * @param currentUser  當(dāng)前用戶
     * @return 更新之后的文章
     */
    @LoginRequired
    @PutMapping("/{id}")
    public Post update(@RequestBody Post post, @PathVariable int id, @CurrentUser User currentUser) {
        post.setId(id);
        return postService.update(post, currentUser);
    }

    /**
     * 刪除文章,需要登錄
     * @param id 文章 id
     * @param currentUser 當(dāng)前登錄用戶
     * @return 提示信息
     */
    @LoginRequired
    @DeleteMapping("/{id}")
    public Object delete(@PathVariable int id, @CurrentUser User currentUser) {
        postService.delete(id, currentUser);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", "刪除成功");
        return jsonObject;
    }

在這段代碼里面,使用了 @LoginRequired 注解保護(hù)更新和刪除接口(使用自定義注解實(shí)現(xiàn)登錄攔截)。同樣使用了 @CurrentUser 注解來注入當(dāng)前登錄用戶(通過自定義注解獲取當(dāng)前用戶)。
delete 方法請(qǐng)求成功之后返回 { "message": "刪除成功" },和之前寫的請(qǐng)求錯(cuò)誤時(shí)返回的格式一樣。為了避免將來使用我們接口的人感到迷惑,將接口請(qǐng)求錯(cuò)誤時(shí)的響應(yīng)修改為 { "error": "error message" } 的形式:將 GlobalExceptionHandler.java 、AuthenticationApi.java、PostApi.java、UserApi.java 這幾個(gè)文件里面 jsonObject.put("message", "......"); 修改為 jsonObject.put("error", "......");

Service 層

在 postService.java 里面添加

    public List<Post> all() {
        return postMapper.all();
    }

    public Post update(Post post, User currentUser) {
        checkNotNull(post.getId(), "id不能為空");
        checkOwner(post.getId(), currentUser);
        postMapper.update(post);
        return findById(post.getId());
    }

    private void checkOwner(Integer id, User currentUser) {
        Post post = findById(id);
        if (!post.getAuthorId().equals(currentUser.getId())) {
            throw new RuntimeException("不能刪除或修改別人的文章");
        }
    }

    public void delete(int id, User currentUser) {
        checkOwner(id, currentUser);
        postMapper.delete(id);
    }

只有作者才可以更新自己的文章,所以添加一個(gè) checkOwner 的私有方法。
update 方法里面使用了 Google GuavacheckNotNull 方法,當(dāng)前也可以自己寫 if 語句判空,但 Guava 提供很多功能,能幫助我們編寫出更優(yōu)雅的代碼。
在 pom.xml 中添加 guava 的依賴

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>

更多Guava 相關(guān)的的知識(shí)可以看看使用Guava編寫優(yōu)雅代碼
checkNotNull是 Guava Preconditions 類里面的一個(gè)靜態(tài)方法,需要靜態(tài)導(dǎo)入

import static com.google.common.base.Preconditions.checkNotNull;

mapper

首先將 postMapperfindOne 拆成下面這種形式,select-post 那段 SQL 就可以在 all 方法中復(fù)用了

   <select id="findOne" resultMap="PostResultMap">
      <include refid="select-post" />
      <where>
          <if test="id!=null">
             AND post.id=#{id}
          </if>
      </where>
    </select>

    <select id="all" resultMap="PostResultMap">
      <include refid="select-post" />
    </select>

    <sql id="select-post" >
        SELECT
            post.id,
            post.author_id ,
            post.title ,
            post.content ,
            post.create_time ,
            post.update_time,
            <!-- 作者信息,password 不需要就不查了 -->
            `user`.id as author__id,
            `user`.`name` as author__name
        FROM post
        LEFT JOIN `user` ON `user`.id=post.author_id
    </sql>
    <select id="all" resultMap="PostResultMap">
      <include refid="select-post" />
    </select>

    <update id="update">
      UPDATE post
         <set>
             <if test="title!=null">
                 title=#{title},
             </if>
             <if test="content!=null">
                 content=#{content},
             </if>
         </set>
      where post.id=#{id}
    </update>

    <delete id="delete">
      DELETE FROM post WHERE post.id=#{id}
    </delete>

測試

啟動(dòng)項(xiàng)目,使用 postman 測試一下三個(gè)接口

  1. GET api/post
  2. UPDATE api/post/{id}
  3. DELETE api/post/{id}

查看項(xiàng)目完整代碼

項(xiàng)目地址: https://github.com/hyrijk/spring-boot-blog
克隆項(xiàng)目到本地

git clone https://github.com/hyrijk/spring-boot-blog.git

checkout 到當(dāng)前版本

git checkout 3594fc7eb5dddeec52ad5bddeedc06678178b5bd

完。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,915評(píng)論 18 139
  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,242評(píng)論 25 708
  • 在短暫的十八年生命里,印象中,許久許久以前認(rèn)識(shí)一個(gè)叫雪的姑娘。后來不知怎么就走散了,都走向了遠(yuǎn)方的遠(yuǎn)方。 開始...
    逗霸君閱讀 420評(píng)論 0 6
  • 有段時(shí)間生活感覺到迷茫,不知道自己到底需要干什么,結(jié)婚兩年,被家人各種催要小孩,工作并不是我所企盼的那樣,老爸生病...
    女漢子阿雅閱讀 114評(píng)論 0 0
  • 結(jié)構(gòu)化思維三層次模型包括理解、重構(gòu)、呈現(xiàn)三個(gè)模塊,在“重構(gòu)”這個(gè)層面,作業(yè)中問題有:第一,沒有結(jié)論或沒有結(jié)論先...
    無憂俠閱讀 262評(píng)論 0 0