淺談Spring 重定向指南
1. 概述
本文將重點(diǎn)介紹在 Spring 中實現(xiàn)重定向(Redirect),并將討論每個策略背后的原因。
2. 為什么要重定向?
讓我們先來考慮在 Spring 應(yīng)用程序中為什么您可能需要做一個重定向的原因。
當(dāng)然有很多可能的例子和原因。 一個簡單的可能是 POST 表單數(shù)據(jù),圍繞雙重提交問題,或者只是將執(zhí)行流委托給另一個控制器方法。
附注一點(diǎn),典型的 Post / Redirect / Get 模式并不能充分解決雙重提交問題 - 在初始提交完成之前刷新頁面的問題可能仍然會導(dǎo)致雙重提交。
3、使用 RedirectView 重定向
我們從這個簡單的方法開始 - 直接來一個例子:
@Controller
@RequestMapping("/")
public class RedirectController {
@GetMapping("/redirectWithRedirectView")
public RedirectView redirectWithUsingRedirectView(RedirectAttributes attributes) {
attributes.addFlashAttribute("flashAttribute", "redirectWithRedirectView");
attributes.addAttribute("attribute", "redirectWithRedirectView");
return new RedirectView("redirectedUrl");
}
}
在背后,RedirectView 會觸發(fā) HttpServletResponse.sendRedirect() - 這將執(zhí)行實際的重定向。
注意這里我們是如何注入重定向?qū)傩缘椒椒ɡ锩娴?- 由框架完成這部分繁重的工作,讓我們能夠與這些屬性交互。
我們添加 attribute 到模型RedirectAttributes中 - 將其作為 HTTP 查詢參數(shù)(Query parameter)暴露。 該模型包含的對象 - 通常是字符串或可以被轉(zhuǎn)換成字符串的對象。
現(xiàn)在讓我們來測試我們的重定向功能 - 用一個簡單的 curl 命令來幫助實現(xiàn):
curl -i http://localhost:8080/spring-rest/redirectWithRedirectView
結(jié)果將是:
HTTP/1.1 302 Found Server: Apache-Coyote/1.1 Location: http://localhost:8080/spring-rest/redirectedUrl?attribute=redirectWithRedirectView
4. 使用redirect:前綴進(jìn)行重定向
前面一個方法使用RedirectView,因為一些原因它并不是最優(yōu)的。
首先,我們現(xiàn)在是耦合于Spring API的,因為我們在我們的代碼里直接地使用RedirectView。
其次,我們需要從一開始就知道,當(dāng)實現(xiàn)控制器操作的時候,它的結(jié)果將總是重定向的,但情況并非總是如此。
更好的選擇是使用redirect:前綴——重定向視圖名稱像其它邏輯視圖名稱一樣被注入到控制器中??刂破魃踔敛恢乐囟ㄏ蛘诎l(fā)生。
它看起來像是這樣的:
@Controller
@RequestMapping("/")
public class RedirectController {
@GetMapping("/redirectWithRedirectPrefix")
public ModelAndView redirectWithUsingRedirectPrefix(ModelMap model) {
model.addAttribute("attribute", "redirectWithRedirectPrefix");
return new ModelAndView("redirect:/redirectedUrl", model);
}
}
當(dāng)視圖名稱跟redirect:一起返回的時候,UrlBasedViewResolver類(以及它的所有子類)會將其識別為一個需要進(jìn)行重定向的特殊指示。視圖名稱剩下的部分會被當(dāng)作重定向URL。
這里有一個地方需要注意——當(dāng)我們在這里使用redirect:/redirectedUrl邏輯視圖的時候,我們正在做一個跟當(dāng)前Servlet上下文相關(guān)的重定向。
如果需要重定向到一個絕對URL,我們可以使用像這樣的名稱:redirect: http://localhost:8080/spring-redirect/redirectedUrl。
所以現(xiàn)在,當(dāng)我們執(zhí)行curl命令:
curl -i http://localhost:8080/spring-rest/redirectWithRedirectPrefix
我們會立刻得到一個重定向:
HTTP/1.1 302 Found Server: Apache-Coyote/1.1 Location: http://localhost:8080/spring-rest/redirectedUrl?attribute=redirectWithRedirectPrefix
5. 使用forward前綴轉(zhuǎn)發(fā):
我們現(xiàn)在看看如何做一些略有不同的事——一個轉(zhuǎn)發(fā)。
在看代碼之前,我們先來看一下對轉(zhuǎn)發(fā)與重定向的語義的快速、高層概括:
- 重定向?qū)⒁园?02響應(yīng)碼和Location頭的新URL進(jìn)行響應(yīng);然后瀏覽器/客戶端將再次向新的URL發(fā)出請求
- 轉(zhuǎn)發(fā)完全在服務(wù)器端發(fā)生; Servlet容器將相同的請求轉(zhuǎn)發(fā)到目標(biāo)URL;瀏覽器中的URL無須改變
現(xiàn)在我們來看看代碼:
@Controller
@RequestMapping("/")
public class RedirectController {
@GetMapping("/forwardWithForwardPrefix")
public ModelAndView redirectWithUsingForwardPrefix(ModelMap model) {
model.addAttribute("attribute", "forwardWithForwardPrefix");
return new ModelAndView("forward:/redirectedUrl", model);
}
}
與redirect:一樣,forward:前綴將由UrlBasedViewResolver及其子類解析。在內(nèi)部,這將創(chuàng)建一個InternalResourceView,它為新視圖執(zhí)行一個RequestDispatcher.forward()操作。
當(dāng)我們用curl執(zhí)行該命令時:
curl -I http://localhost:8080/spring-rest/forwardWithForwardPrefix
我們會得到HTTP 405 (不允許的方法):
HTTP/1.1 405 Method Not Allowed Server: Apache-Coyote/1.1 Allow: GET Content-Type: text/html;charset=utf-8
與我們在重定向解決方案中的兩個請求相比,在這種情況下,我們只有一個請求從瀏覽器/客戶端發(fā)送到服務(wù)器端。當(dāng)然,以前由重定向添加的屬性也不需要了。
6. 包含RedirectAttributes的屬性
接下來 - 讓我們看看在一個重定向中傳遞屬性 - 充分利用框架中的RedirectAttribures:
@GetMapping("/redirectWithRedirectAttributes")
public RedirectView redirectWithRedirectAttributes(RedirectAttributes attributes) {
attributes.addFlashAttribute("flashAttribute", "redirectWithRedirectAttributes");
attributes.addAttribute("attribute", "redirectWithRedirectAttributes");
return new RedirectView("redirectedUrl");
}
如前所述,我們可以直接在方法中插入屬性對象 - 這使得該機(jī)制非常容易使用。
還要注意,我們也添加一個Flash屬性 - 這是一個不會被添加到URL中的屬性。我們可以通過這種屬性來實現(xiàn)——我們稍后可以在重定向的最終目標(biāo)的方法中使用@ModelAttribute(“flashAttribute”)來訪問flash屬性:
@GetMapping("/redirectedUrl")
public ModelAndView redirection(
ModelMap model,
@ModelAttribute("flashAttribute") Object flashAttribute) {
model.addAttribute("redirectionAttribute", flashAttribute);
return new ModelAndView("redirection", model);
}
因此,圓滿完工——如果你需要使用curl測試該功能:
curl -i http://localhost:8080/spring-rest/redirectWithRedirectAttributes
我們將會被重定向到新的位置:
HTTP/1.1 302 Found Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=4B70D8FADA2FD6C22E73312C2B57E381; Path=/spring-rest/; HttpOnly Location: http://localhost:8080/spring-rest/redirectedUrl; jsessionid=4B70D8FADA2FD6C22E73312C2B57E381?attribute=redirectWithRedirectAttributes
這樣,使用RedirectAttribures代替ModelMap,賦予我們僅在重定向操作中涉及的兩種方法之間共享一些屬性的能力。
7. 沒有前綴的另一種配置
現(xiàn)在讓我們探索另一種配置——沒有前綴的重定向。
為了實現(xiàn)這一點(diǎn),我們需要使用org.springframework.web.servlet.view.XmlViewResolver:
<bean class="org.springframework.web.servlet.view.XmlViewResolver">
<property name="location">
<value>/WEB-INF/spring-views.xml</value>
</property>
<property name="order" value="0" />
</bean>
代替我們在之前配置里使用的org.springframework.web.servlet.view.InternalResourceViewResolver:
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> </bean>
我們還需要在配置里面定義一個RedirectView bean:
<bean id="RedirectedUrl" class="org.springframework.web.servlet.view.RedirectView"> <property name="url" value="redirectedUrl" /> </bean>
現(xiàn)在我們可以通過id來引用這個新的bean來觸發(fā)重定向:
@Controller
@RequestMapping("/")
public class RedirectController {
@GetMapping("/redirectWithXMLConfig")
public ModelAndView redirectWithUsingXMLConfig(ModelMap model) {
model.addAttribute("attribute", "redirectWithXMLConfig");
return new ModelAndView("RedirectedUrl", model);
}
}
為了測試它,我們再次使用curl命令:
curl -i http://localhost:8080/spring-rest/redirectWithRedirectView
結(jié)果會是:
HTTP/1.1 302 Found Server: Apache-Coyote/1.1 Location: http://localhost:8080/spring-rest/redirectedUrl?attribute=redirectWithRedirectView
8. 重定向HTTP POST請求 Request
對于類似銀行付款這樣的用例,我們可能需要重定向HTTP POST請求。根據(jù)返回的HTTP狀態(tài)碼,POST請求可以重定向到HTTP GET或POST上。
根據(jù)HTTP 1.1協(xié)議參考,狀態(tài)碼301(永久移除)和302(已找到)允許請求方法從POST更改為GET。該規(guī)范還定義了不允許將請求方法從POST更改為GET的相關(guān)的307(臨時重定向)和308(永久重定向)狀態(tài)碼。
現(xiàn)在,我們來看看將post請求重定向到另一個post請求的代碼:
@PostMapping("/redirectPostToPost")
public ModelAndView redirectPostToPost(HttpServletRequest request) {
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
return new ModelAndView("redirect:/redirectedPostToPost");
}
@PostMapping("/redirectedPostToPost")
public ModelAndView redirectedPostToPost() {
return new ModelAndView("redirection");
}
現(xiàn)在,讓我們使用curl命令來測試下重定向的POST:
curl -L --verbose -X POST http://localhost:8080/spring-rest/redirectPostToPost
我們正在被重定向到目標(biāo)地址:
> POST /redirectedPostToPost HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.49.0
> Accept: */*
>
< HTTP/1.1 200
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Tue, 08 Aug 2017 07:33:00 GMT
{"id":1,"content":"redirect completed"}
9. 結(jié)論
本文介紹了在Spring中實現(xiàn)重定向的三種不同方法,在執(zhí)行這些重定向時如何處理/傳遞屬性以及如何處理HTTP POST請求的重定向。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
解決SpringBoot項目在啟動后自動關(guān)閉的問題
今天搭建了一個SpringBoot項目,但是在啟動之后就自行關(guān)閉了,下面通過本文給大家介紹SpringBoot項目在啟動后自動關(guān)閉問題及解決方法,需要的朋友可以參考下2023-08-08
Spring Boot中@ConditionalOnProperty的使用方法
這篇文章主要給大家介紹了關(guān)于Spring Boot中@ConditionalOnProperty的使用方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Java?Timer與TimerTask類使程序計時執(zhí)行
這篇文章主要介紹了Java定時器中的Timer和TimerTask的原理。Timer主要用于Java線程里指定時間或周期運(yùn)行任務(wù),它是線程安全的,但不提供實時性(real-time)保證。接下來就跟隨小編一起深入了解Timer和TimerTask吧2022-02-02
Java.lang.NullPointerException的錯誤解決
Java中NullPointerException是一種常見的運(yùn)行時異常,通常發(fā)生在嘗試調(diào)用null對象的方法或訪問其屬性時,具有一定的參考價值,感興趣的可以了解一下2024-09-09
Spring事務(wù)傳播中嵌套調(diào)用實現(xiàn)方法詳細(xì)介紹
Spring事務(wù)的本質(zhì)就是對數(shù)據(jù)庫事務(wù)的支持,沒有數(shù)據(jù)庫事務(wù),Spring是無法提供事務(wù)功能的。Spring只提供統(tǒng)一的事務(wù)管理接口,具體實現(xiàn)都是由數(shù)據(jù)庫自己實現(xiàn)的,Spring會在事務(wù)開始時,根據(jù)當(dāng)前設(shè)置的隔離級別,調(diào)整數(shù)據(jù)庫的隔離級別,由此保持一致2022-11-11

