SpringBoot系列教程web篇之重定向

原文地址: SpringBoot系列教程web篇之重定向

前面介紹了spring web篇數據返回的幾種常用姿勢,當我們在相應一個http請求時,除了直接返回數據之外,還有另一種常見的case -> 重定向;

比如我們在逛淘寶,沒有登錄就點擊購買時,會跳轉到登錄界面,這其實就是一個重定向。本文主要介紹對於後端而言,可以怎樣支持302重定向

<!-- more -->

I. 環境搭建

首先得搭建一個web應用纔有可能繼續後續的測試,藉助SpringBoot搭建一個web應用屬於比較簡單的活;

創建一個maven項目,pom文件如下

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.7</version>
    <relativePath/> <!-- lookup parent from update -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.45</version>
    </dependency>
</dependencies>

<build>
    <pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </pluginManagement>
</build>
<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

依然是一般的流程,pom依賴搞定之後,寫一個程序入口

/**
 * Created by @author yihui in 15:26 19/9/13.
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

II. 302重定向

1. 返回redirect

這種case通常適用於返回視圖的接口,在返回的字符串前面添加redirect:方式來告訴Spring框架,需要做302重定向處理

@Controller
@RequestMapping(path = "redirect")
public class RedirectRest {

    @ResponseBody
    @GetMapping(path = "index")
    public String index(HttpServletRequest request) {
        return "重定向訪問! " + JSON.toJSONString(request.getParameterMap());
    }

    @GetMapping(path = "r1")
    public String r1() {
        return "redirect:/redirect/index?base=r1";
    }
}

上面給出了一個簡單的demo,當我們訪問/redirect/r1時,會重定向到請求/redirect/index?base=r1,實際測試結果如下

注意上面的截圖,我們實際訪問的連接是 http://127.0.0.1:8080/redirect/index?base=r1,在瀏覽器中的表現則是請求url變成了http://127.0.0.1:8080/redirect/index?base=r1;通過控制檯查看到的返回頭狀態碼是302

說明

  • 使用這種方式的前提是不能在接口上添加@ResponseBody註解,否則返回的字符串被當成普通字符串處理直接返回,並不會實現重定向

2. HttpServletResponse重定向

前面一篇說到SpringMVC返回數據的時候,介紹到可以直接通過HttpServletResponse往輸出流中寫數據的方式,來返回結果;我們這裏也是利用它,來實現重定向

@ResponseBody
@GetMapping(path = "r2")
public void r2(HttpServletResponse response) throws IOException {
    response.sendRedirect("/redirect/index?base=r2");
}

從上面的demo中,也可以看出這個的使用方式很簡單了,直接調用javax.servlet.http.HttpServletResponse#sendRedirect,並傳入需要重定向的url即可

3. 小結

這裏主要介紹了兩種常見的後端重定向方式,都比較簡單,這兩種方式也有自己的適用場景(當然並不絕對)

  • 在返回視圖的前面加上redirect的方式,更加適用於視圖的跳轉,從一個網頁跳轉到另一個網頁
  • HttpServletResponse#sendRedirec的方式更加靈活,可以在後端接收一次http請求生命週期中的任何一個階段來使用,比如有以下幾種常見的場景

    • 某個接口要求登錄時,在攔截器層針對所有未登錄的請求,重定向到登錄頁面
    • 全局異常處理中,如果出現服務器異常,重定向到定製的500頁面
    • 不支持的請求,重定向到404頁面

II. 其他

0. 項目

a. 系列博文

b. 項目源碼

1. 一灰灰Blog

盡信書則不如,以上內容,純屬一家之言,因個人能力有限,難免有疏漏和錯誤之處,如發現bug或者有更好的建議,歡迎批評指正,不吝感激

下面一灰灰的個人博客,記錄所有學習和工作中的博文,歡迎大家前去逛逛

一灰灰blog

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