Spring重定向的示例分析

這篇文章主要介紹了Spring重定向的示例分析,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

成都創(chuàng)新互聯(lián)服務(wù)項(xiàng)目包括金水網(wǎng)站建設(shè)、金水網(wǎng)站制作、金水網(wǎng)頁制作以及金水網(wǎng)絡(luò)營(yíng)銷策劃等。多年來,我們專注于互聯(lián)網(wǎng)行業(yè),利用自身積累的技術(shù)優(yōu)勢(shì)、行業(yè)經(jīng)驗(yàn)、深度合作伙伴關(guān)系等,向廣大中小型企業(yè)、政府機(jī)構(gòu)等提供互聯(lián)網(wǎng)行業(yè)的解決方案,金水網(wǎng)站推廣取得了明顯的社會(huì)效益與經(jīng)濟(jì)效益。目前,我們服務(wù)的客戶以成都為中心已經(jīng)輻射到金水省份的部分城市,未來相信會(huì)繼續(xù)擴(kuò)大服務(wù)區(qū)域并繼續(xù)獲得客戶的支持與信任!

1. 概述

本文將重點(diǎn)介紹在 Spring 中實(shí)現(xiàn)重定向(Redirect),并將討論每個(gè)策略背后的原因。

2. 為什么要重定向?

讓我們先來考慮在 Spring 應(yīng)用程序中為什么您可能需要做一個(gè)重定向的原因。

當(dāng)然有很多可能的例子和原因。 一個(gè)簡(jiǎn)單的可能是 POST 表單數(shù)據(jù),圍繞雙重提交問題,或者只是將執(zhí)行流委托給另一個(gè)控制器方法。

附注一點(diǎn),典型的 Post / Redirect / Get 模式并不能充分解決雙重提交問題 - 在初始提交完成之前刷新頁面的問題可能仍然會(huì)導(dǎo)致雙重提交。

3、使用  RedirectView 重定向

我們從這個(gè)簡(jiǎn)單的方法開始 - 直接來一個(gè)例子:

@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 會(huì)觸發(fā) HttpServletResponse.sendRedirect() - 這將執(zhí)行實(shí)際的重定向。

注意這里我們是如何注入重定向?qū)傩缘椒椒ɡ锩娴?- 由框架完成這部分繁重的工作,讓我們能夠與這些屬性交互。

我們添加 attribute 到模型RedirectAttributes中 - 將其作為 HTTP 查詢參數(shù)(Query parameter)暴露。 該模型包含的對(duì)象 - 通常是字符串或可以被轉(zhuǎn)換成字符串的對(duì)象。

現(xiàn)在讓我們來測(cè)試我們的重定向功能 - 用一個(gè)簡(jiǎn)單的 curl 命令來幫助實(shí)現(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)行重定向

前面一個(gè)方法使用RedirectView,因?yàn)橐恍┰蛩⒉皇亲顑?yōu)的。

首先,我們現(xiàn)在是耦合于Spring API的,因?yàn)槲覀冊(cè)谖覀兊拇a里直接地使用RedirectView。

其次,我們需要從一開始就知道,當(dāng)實(shí)現(xiàn)控制器操作的時(shí)候,它的結(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:一起返回的時(shí)候,UrlBasedViewResolver類(以及它的所有子類)會(huì)將其識(shí)別為一個(gè)需要進(jìn)行重定向的特殊指示。視圖名稱剩下的部分會(huì)被當(dāng)作重定向URL。

這里有一個(gè)地方需要注意——當(dāng)我們?cè)谶@里使用redirect:/redirectedUrl邏輯視圖的時(shí)候,我們正在做一個(gè)跟當(dāng)前Servlet上下文相關(guān)的重定向。

如果需要重定向到一個(gè)絕對(duì)URL,我們可以使用像這樣的名稱:redirect: http://localhost:8080/spring-redirect/redirectedUrl。

所以現(xiàn)在,當(dāng)我們執(zhí)行curl命令:

curl -i http://localhost:8080/spring-rest/redirectWithRedirectPrefix

我們會(huì)立刻得到一個(gè)重定向:

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)在看看如何做一些略有不同的事——一個(gè)轉(zhuǎn)發(fā)。

在看代碼之前,我們先來看一下對(duì)轉(zhuǎn)發(fā)與重定向的語義的快速、高層概括:

  • 重定向?qū)⒁园?02響應(yīng)碼和Location頭的新URL進(jìn)行響應(yīng);然后瀏覽器/客戶端將再次向新的URL發(fā)出請(qǐng)求

  • 轉(zhuǎn)發(fā)完全在服務(wù)器端發(fā)生; Servlet容器將相同的請(qǐng)求轉(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)建一個(gè)InternalResourceView,它為新視圖執(zhí)行一個(gè)RequestDispatcher.forward()操作。

當(dāng)我們用curl執(zhí)行該命令時(shí):

curl -I http://localhost:8080/spring-rest/forwardWithForwardPrefix

我們會(huì)得到HTTP 405 (不允許的方法):

HTTP/1.1 405 Method Not Allowed
Server: Apache-Coyote/1.1
Allow: GET
Content-Type: text/html;charset=utf-8

與我們?cè)谥囟ㄏ蚪鉀Q方案中的兩個(gè)請(qǐng)求相比,在這種情況下,我們只有一個(gè)請(qǐng)求從瀏覽器/客戶端發(fā)送到服務(wù)器端。當(dāng)然,以前由重定向添加的屬性也不需要了。

6. 包含RedirectAttributes的屬性

接下來 - 讓我們看看在一個(gè)重定向中傳遞屬性 - 充分利用框架中的RedirectAttribures:

@GetMapping("/redirectWithRedirectAttributes")
public RedirectView redirectWithRedirectAttributes(RedirectAttributes attributes) {
 
  attributes.addFlashAttribute("flashAttribute", "redirectWithRedirectAttributes");
  attributes.addAttribute("attribute", "redirectWithRedirectAttributes");
  return new RedirectView("redirectedUrl");
}

如前所述,我們可以直接在方法中插入屬性對(duì)象 - 這使得該機(jī)制非常容易使用。

還要注意,我們也添加一個(gè)Flash屬性 - 這是一個(gè)不會(huì)被添加到URL中的屬性。我們可以通過這種屬性來實(shí)現(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測(cè)試該功能:

curl -i http://localhost:8080/spring-rest/redirectWithRedirectAttributes

我們將會(huì)被重定向到新的位置:

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)在讓我們探索另一種配置——沒有前綴的重定向。

為了實(shí)現(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>

代替我們?cè)谥芭渲美锸褂玫膐rg.springframework.web.servlet.view.InternalResourceViewResolver:

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
</bean>

我們還需要在配置里面定義一個(gè)RedirectView bean:

<bean id="RedirectedUrl" class="org.springframework.web.servlet.view.RedirectView">
  <property name="url" value="redirectedUrl" />
</bean>

現(xiàn)在我們可以通過id來引用這個(gè)新的bean來觸發(fā)重定向:

@Controller
@RequestMapping("/")
public class RedirectController {
   
  @GetMapping("/redirectWithXMLConfig")
  public ModelAndView redirectWithUsingXMLConfig(ModelMap model) {
    model.addAttribute("attribute", "redirectWithXMLConfig");
    return new ModelAndView("RedirectedUrl", model);
  }
}

為了測(cè)試它,我們?cè)俅问褂胏url命令:

curl -i http://localhost:8080/spring-rest/redirectWithRedirectView

結(jié)果會(huì)是:

HTTP/1.1 302 Found
Server: Apache-Coyote/1.1
Location: 
 http://localhost:8080/spring-rest/redirectedUrl?attribute=redirectWithRedirectView

8. 重定向HTTP POST請(qǐng)求 Request

對(duì)于類似銀行付款這樣的用例,我們可能需要重定向HTTP POST請(qǐng)求。根據(jù)返回的HTTP狀態(tài)碼,POST請(qǐng)求可以重定向到HTTP GET或POST上。

根據(jù)HTTP 1.1協(xié)議參考,狀態(tài)碼301(永久移除)和302(已找到)允許請(qǐng)求方法從POST更改為GET。該規(guī)范還定義了不允許將請(qǐng)求方法從POST更改為GET的相關(guān)的307(臨時(shí)重定向)和308(永久重定向)狀態(tài)碼。
現(xiàn)在,我們來看看將post請(qǐng)求重定向到另一個(gè)post請(qǐng)求的代碼:

@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命令來測(cè)試下重定向的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"}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“Spring重定向的示例分析”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來學(xué)習(xí)!

分享名稱:Spring重定向的示例分析
網(wǎng)站地址:http://muchs.cn/article12/gdecgc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、、網(wǎng)站導(dǎo)航、小程序開發(fā)Google、定制開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站建設(shè)