阿里騰訊都在用的Restful編碼風格

Restful 風格的介紹

Restful 一種軟件架構風格設計風格,而不是標準,只是提供了一組設計原則和約束條件。它主要用於客戶端和服務器交互類的軟件。基於這個風格設計的軟件可以更簡潔更有層次,更易於實現緩存等機制。

REST(英文:Representational State Transfer,簡稱REST)描述了一個架構樣式的網絡系統,比如 web 應用程序。它首次出現在 2000 年 Roy Fielding 的博士論文中,他是 HTTP 規範的主要編寫者之一。在目前主流的三種Web服務交互方案中,REST相比於SOAP(Simple Object Access protocol,簡單對象訪問協議)以及XML-RPC更加簡單明瞭,無論是對URL的處理還是對Payload的編碼,REST都傾向於用更加簡單輕量的方法設計和實現。值得注意的是REST並沒有一個明確的標準,而更像是一種設計的風格。

看總結簡單明瞭

Restful是一種設計風格。對於我們Web開發人員來說。就是使用一個url地址表示一個唯一的資源。然後把原來的請求參數加入到請求資源地址中。然後原來請求的增,刪,改,查操作。改爲使用HTTP協議中請求方式GET、POST、PUT、DELETE表示

使用Restful風格,這裏需要明確一下幾點

1. 就是把傳統的請求參數加入到請求地址是什麼樣子?

傳統的方式是:
		比如:http://ip:port/工程名/資源名?請求參數
		舉例:http://127.0.0.1:8080/springmvc/user?action=delete&id=1
Restful風格是:
		比如:http://ip:port/工程名/資源名/請求參數/請求參數
		舉例:http://127.0.0.1:8080/springmvc/user/1

2. Restful風格中請求方式GET、POST、PUT、DELETE分別表示查、增、改、刪。

  請求操作

  請求方式   操作內容
  GET 請求      對應      查詢
  http://ip:port/工程名/user/1   HTTP 請求 GET

  表示要查詢id爲1的用戶

  http://ip:port/工程名/user   HTTP 請求 GET

  表示查詢全部的用戶

  POST 請求              

  對應   添加
  http://ip:port/工程名/user   HTTP 請求 POST

  表示要添加一個用戶

  PUT 請求                 

  對應   修改
  http://ip:port/工程名/user/1   HTTP 請求 PUT   表示要修改id爲1的用戶信息

  DELETE 請求

  對應      刪除
  http://ip:port/工程名/user/1   HTTP 請求 DELETE   表示要刪除id爲1的用戶信息

SpringMVC中如何發送GET請求、POST請求、PUT請求、DELETE請求。

 我們知道發起 GET 請求和 POST 請求,只需要在表單的 form 標籤中,設置 method ="get" 就是GET請求。

 設置 form 標籤的method="post"。就會發起 POST 請求。而 PUT 請求和 DELETE 請求。

 

  1. 要有 post 請求的 form 標籤
  2. 在 form 表單中,添加一個額外的隱藏域 _method ="PUT" _method = "DELETE"
  3. web.xml中配置一個Filter過濾器org.springframework.web.filter.HiddenHttpMethodFilter(注意,這個Filter一定要在處理亂碼的Filter後面 

簡單代碼實現

1. RestController.java

package com.spring.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 *  Restful風格的 Controller
 * Created by YongXin Xue on 2020/05/12 9:55
 */
@Controller
public class RestController {

    ///// restful風格中請求方式GET、POST、PUT、DELETE分別表示查、增、改、刪。

    /**
     * @PathVariable 路徑參數獲取
     * value = "/queryUserById/{id}" 中的 {id} 表示路徑參數 ,表示一個可變的值。 {id} 裏面的 id 是變量的名稱
     * 
     * @PathVariable("id") Integer id 表示把指定 id 的路徑參數值,賦給方法參數id。
     *  [ 也可以設置多個值 ] 如下 : Integer id; String name; 
     */
    @RequestMapping(value = "/queryUserById/{id}/{name}", method = RequestMethod.GET)
    public ModelAndView queryUserById(@PathVariable("id") Integer id,
                                      @PathVariable("name") String name){
        System.out.println(" 查詢一條用戶記錄信息!! " + id + name);
        // redirect 到 index.jsp 頁面
        return new ModelAndView("/index.jsp");
    }

    @RequestMapping(value = "/queryUserList", method = RequestMethod.GET)
    public ModelAndView queryUserList() {
        System.out.println(" 查詢全部用戶記錄信息!! ");
        // redirect 到 index.jsp 頁面
        return new ModelAndView("redirect:/index.jsp");
    }

    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    public ModelAndView saveUser() {
        System.out.println(" 保存用戶記錄信息!! ");
        // redirect 到 index.jsp 頁面
        return new ModelAndView("redirect:/index.jsp");
    }

    @RequestMapping(value = "/updateUser/1", method = RequestMethod.PUT)
    public ModelAndView updateUser() {
        System.out.println(" 更新用戶記錄信息!! ");
        // redirect 到 index.jsp 頁面
        return new ModelAndView("/index.jsp");
    }

    @RequestMapping(value = "/deleteUserById/1", method = RequestMethod.DELETE)
    public ModelAndView deleteUserById() {
        System.out.println(" 刪除用戶記錄信息!! ");
        // redirect 到 index.jsp 頁面
        return new ModelAndView("redirect:/index.jsp");
    }
}

2. spring-mcv.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 包掃描 -->
    <context:component-scan base-package="com.spring.mvc"/>

</beans>

3. web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    
    <!-- 配置前端控制器 -->
    <servlet>
        <servlet-name>DispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!-- 配置 SpringMVC 的容器配置文件路徑 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 中配置 Restful 的 Filter 過濾器用來識別 PUT 和 DELETE 請求 -->
    <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

4. index.jsp

<%--
  Created by YongXin Xue on 2020/05/12 9:52 
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>Restful 風格</title>
  </head>
  <body>
      <h2>Restful ADN CRUD</h2>
      <h3><a href="${pageContext.request.contextPath}/queryUserById/290/lance">查詢一條用戶記錄</a></h3>
      <h3><a href="${pageContext.request.contextPath}/queryUserList">查詢全部用戶記錄</a></h3>

      <form action="${pageContext.request.contextPath}/saveUser" method="post">
          <input type="submit" value="保存用戶">
      </form>

      <%--
            如何發送 PUT請求,和 DELETE 請求
                1. 首先要有一個 post 請求的表單
                2. 要有一個隱藏域
                    <input type="hidden" name="_method" value="PUT">
                    <input type="hidden" name="_method" value="DELETE">
                3. 在 web.xml 中配置 Restful 的 Filter 過濾器用來識別 PUT 和 DELETE 請求
       --%>
      <form action="${pageContext.request.contextPath}/updateUser/1" method="post">
          <input type="hidden" name="_method" value="PUT">
          <input type="submit" value="更新用戶">
      </form>
      <form action="${pageContext.request.contextPath}/deleteUserById/1" method="post">
          <input type="hidden" name="_method" value="DELETE">
          <input type="submit" value="刪除用戶">
      </form>

  </body>
</html>

 

需要注意Restful風格在高版本Tomcat 中無法轉發到jsp頁面

1. Spring MVC 底層默認用的是請求轉發.而在Tomcat8之後的一些高版本,使用restful風格訪問然後轉發到jsp頁面。就會有如下的錯誤提示:

2. 解決方法一 [ 在 jsp 頁面 page 標籤中加 isErrorPage="true" ] : 

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

3. 解決方法二 [ 使用重定向 ]

 

如果文章對你有幫助記得點贊 + 關注哦! QQ交流羣:1101584918,歡迎大家加入。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章