Springboot-如何开发restful风格的项目

Restful 风格是什么

在做 Web 开发的过程中,method 常用的值是 get 和 post. 可事实上,method 值还可以是 put 和 delete 等等其他值。
既然 method 值如此丰富,那么就可以考虑使用同一个 url,但是约定不同的 method 来实施不同的业务,这就是 Restful 的基本考虑。
CRUD 是最常见的操作,在使用 Restful 风格之前,通常的增加做法是这样的:

/addCategory?name=xxx

可是使用了Restful风格之后,增加就变成了:

/categories

CRUD 如下表所示,URL 就都使用一样的 "/categories",区别只是在于 method 不同,服务器根据 method 的不同来判断浏览器期望做的业务行为:

传统风格 Restful风格
url method url method
增加 /addCategory?name=xxx POST /categories POST
删除 /deleteCategory?id=123 GET /categories/123 DELETE
修改 /updateCategory?id=123&name=yyy POST /categories/123 PUT
获取 /getCategory?id=123 GET /categories/123 GET
查询 /listCategory GET /categories GET

步骤 1 : 可运行项目

首先下载一个简单的可运行项目作为演示 -> 网盘链接https://newryan.lanzous.com/ic40gna
下载后解压,比如解压到 E:\project\springboot 目录下

步骤 2 : listCategory.jsp

listCategory.jsp 做了如下修改

  1. 增加
    1.1 action 修改为 "categories"

  2. 删除
    2.1 url 修改为 categories/id
    2.2 点击超链后,会使用 form 提交,并且提交 _method 的值为 delete,以达到和增加类似的效果

$(function(){                    
     $(".delete").click(function(){
         var href=$(this).attr("href");
         $("#formdelete").attr("action",href).submit();
         return false;
     })
 })
  1. 获取
    3.1 url 修改为了 /categories/id

  2. 在最开始增加了 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 align="center">
 
</div>
 
<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="categories/${c.id}">编辑</a></td>
                <td><a class="delete" href="categories/${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="categories" method="post">
    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>

步骤 3 : editCategory.jsp

action 修改为了 categories/id
注意:form 下增加 filed, 虽然这个 form 的 method 是 post, 但是 springmvc 看到这个 _method 的值是 put 后,会把其修改为 put.

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

完整 editCategory.jsp:

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

步骤 4 : CategoryController

CRUD 的 RequestMapping 都修改为了 /categories,以前用的注解叫做 @RequestMapper,现在分别叫做 GetMapper, PutMapper, PostMapper 和 DeleteMapper 用于表示接受对应的 Method

package com.ryan.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 com.ryan.springboot.dao.CategoryDAO;
import com.ryan.springboot.pojo.Category;
  
@Controller
public class CategoryController {
    @Autowired CategoryDAO categoryDAO;
     
    @GetMapping("/categories")
    public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0") int start,@RequestParam(value = "size", defaultValue = "6") 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";
    }
 
    @PostMapping("/categories")
    public String addCategory(Category c) throws Exception {
        categoryDAO.save(c);
        return "redirect:/categories";
    }
    @DeleteMapping("/categories/{id}")
    public String deleteCategory(Category c) throws Exception {
        categoryDAO.delete(c);
        return "redirect:/categories";
    }
    @PutMapping("/categories/{id}")
    public String updateCategory(Category c) throws Exception {
        categoryDAO.save(c);
        return "redirect:/categories";
    }
    @GetMapping("/categories/{id}")
    public String getCategory(@PathVariable("id") int id,Model m) throws Exception {
        Category c= categoryDAO.getOne(id);
        m.addAttribute("c", c);
        return "editCategory";
    }
}

步骤 5 : 测试

访问测试地址:

http://127.0.0.1:8080/categories

: 启动方式是 Springboot 特有的,直接运行类:com.ryan.springboot.Application 的主方法。
看到如图所示的效果

更多关于 Springboot-restful 详细内容,点击学习: https://how2j.cn/k/springboot/springboot-restful/1653.html?p=139689

猜你喜欢

转载自www.cnblogs.com/newRyan/p/12807839.html