springboot之restful風格


步驟一:restful風格是什么?

  我們知道在做web開發的過程中,method常用的值是get和post。可事實上,method值還可以是put和delete等等其他值。

  既然method值如此豐富,那么就可以考慮使用同一個url,但是約定不同的method來實施不同的業務,這就是restful的基本考慮。

  CRUD是最常見的操作,在使用restful風格之前,通常的增加的方法是這樣的:

/addCategory?name=xxx

  可以使用了restful風格之后,增加就變成了:

/category

  CRUD如下表所示,URL就都使用一樣的 "/category",區別只是在於method不同,服務器根據method的不同來判斷瀏覽器期望做的業務行為

步驟二:基於前面的知識點

  接下來我們就把基於springboot jpa的curd和分頁,修改為Restful風格。

步驟三:修改listCategory.jsp

  listCategory.jsp 做了如下修改
  1. 增加
    1.1 action修改為"category"
    1.2 增加如下filed, 雖然這個form的method是post, 但是spingboot看到這個_method的值是put后,會把其修改為put.

   <input type="hidden" name="_method" value="PUT">

  2. 刪除
    2.1 url修改為category/id
    2.2 點擊超鏈后,會使用form提交,並且提交_method的值為delete,以達到和增加類似的效果

      $(function(){                     
           $(".delete").click(function(){
               var href=$(this).attr("href");
               $("#formdelete").attr("action",href).submit();
               return false;
           })
       }) 

  3. 獲取
    3.1 url修改為了/category/id

  4. 在最開始增加了jquery.min.js的引入

 <script type="text/javascript" src="js/jquery.min.js"></script>

  listCategory.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  
<script type="text/javascript" src="js/jquery.min.js"></script>

    <script type="text/javascript">
       /*將post method 改變為delete*/
      $(function(){                     
           $(".delete").click(function(){
               var href=$(this).attr("href");
               $("#formdelete").attr("action",href).submit();
               return false;
           })
       }) 
   </script>   

<div style="width:500px;margin:20px auto;text-align: center">
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>編輯</td>
            <td>刪除</td>
        </tr>
        <c:forEach items="${page.content}" var="c" varStatus="st">
            <tr>
                <td>${c.id}</td>
                <td>${c.name}</td>
                <td><a href="category/${c.id}">編輯</a></td>
                <td><a class="delete" href="category/${c.id}">刪除</a></td>
            </tr>
        </c:forEach>
        
    </table>
    <br>
    <div>
            <a href="?start=0">[首  頁]</a>
            <a href="?start=${page.number-1}">[上一頁]</a>
            <a href="?start=${page.number+1}">[下一頁]</a>
            <a href="?start=${page.totalPages-1}">[末  頁]</a>
    </div>
    <br>
    <form action="category" method="post">
        <input type="hidden" name="_method" value="PUT">
   添加分類:
name: <input name="name"> <br> <button type="submit">提交</button> </form> <form id="formdelete" action="" method="POST" > <input type="hidden" name="_method" value="DELETE"> </form> </div>

步驟四:修改editCategory.jsp

  action修改為了 category/id

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8" isELIgnored="false"%>
 
<div style="margin:0px auto; width:500px">
 
<form action="../category/${c.id}" method="post">
name: <input name="name" value="${c.name}"> <br>
<button type="submit">提交</button>
 
</form>
</div>

步驟五:修改CategoryController

  CRUD的RequestMapping都修改為了/category,以前用的注解叫做@RequestMapper,現在分別叫做 GetMapper, PutMapper, PostMapper 和 DeleteMapper 用於表示接受對應的Method

package cn.xdf.springboot.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.xdf.springboot.dao.CategoryDao;
import cn.xdf.springboot.pojo.Category;
 
@Controller
public class CategoryController {
    @Autowired CategoryDao categoryDao;
    
    @GetMapping("/category")     //查詢所有
    public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
        start = start<0?0:start;
        
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = new PageRequest(start, size, sort);
        Page<Category> page =categoryDao.findAll(pageable);
        
        m.addAttribute("page", page);
        
        return "listCategory";
    }

    @PutMapping("/category")       //增加
    public String addCategory(Category c) throws Exception {
        categoryDao.save(c);
        return "redirect:/category";
    }
    @DeleteMapping("/category/{id}")   //刪除
    public String deleteCategory(Category c) throws Exception {
        categoryDao.delete(c);
        return "redirect:/category";
    }
  @PostMapping("/category/{id}")    //修改保存
    public String updateCategory(Category c) throws Exception {
        categoryDao.save(c);
        return "redirect:/category";
    }
    @GetMapping("/category/{id}")      //修改查詢
    public String addCategory(@PathVariable("id") int id,Model m) throws Exception {
        Category c= categoryDao.getOne(id);
        m.addAttribute("c", c);
        return "editCategory";
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM