Spring重定向指南
admin
2024-03-24 18:44:04
0

1. 概述

本教程将重点介绍如何在 Spring 中实现重定向,并将讨论每种策略背后的原因。

2. 为什么要重定向?

让我们首先考虑为什么我们可能需要在 Spring 应用程序中进行重定向的原因。

当然,有很多可能的例子和原因。例如,我们可能需要 POST 表单数据,解决双重提交问题,或者只是将执行流委托给另一个控制器方法。

这里有一个快速的旁注:典型的 Post/重定向/Get 模式不能充分解决双重提交问题,并且在初始提交完成之前刷新页面等问题仍可能导致双重提交。

3. 使用重定向视图重定向

让我们从这个简单的方法开始,直接来看一个例子

@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 将触发 HttpServletResponse.sendRedirect(),它将执行实际的重定向。

请注意,这里我们如何将重定向属性注入到方法中。该框架将完成繁重的工作,并允许我们与这些属性进行交互。

我们正在添加模型属性属性,该属性将作为 HTTP 查询参数公开。模型必须仅包含对象 — 通常是字符串或可转换为字符串的对象。

现在让我们在一个简单的 curl 命令的帮助下测试我们的重定向

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

这是我们的结果:

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

4. 使用前缀重定向重定向:

由于几个原因,以前的方法 - 使用RedirectView - 是次优的。

首先,我们现在与Spring API耦合,因为我们直接在代码中使用RedirectView

其次,我们现在需要从一开始就知道,在实现该控制器操作时,结果将始终是重定向,但情况可能并非总是如此。

更好的选择是使用前缀重定向:。重定向视图名称与任何其他逻辑视图名称一样注入到控制器中。控制器甚至不知道正在发生重定向。

如下所示:

@Controller
@RequestMapping("/")
public class RedirectController {@GetMapping("/redirectWithRedirectPrefix")public ModelAndView redirectWithUsingRedirectPrefix(ModelMap model) {model.addAttribute("attribute", "redirectWithRedirectPrefix");return new ModelAndView("redirect:/redirectedUrl", model);}
}

当返回带有前缀 redirect: 的视图名称时,UrlBasedViewResolver(及其所有子类)会将此识别为需要发生重定向的特殊指示。视图名称的其余部分将用作重定向 URL。

一个快速但重要的注意事项是,当我们在这里使用这个逻辑视图名称 - redirect:/redirectedUrl - 我们正在相对于当前的 Servlet 上下文进行重定向。

我们可以使用诸如重定向之类的名称:http://localhost:8080/spring-redirect-and-forward/redirectedUrl,如果我们需要重定向到绝对URL。

所以,现在当我们执行 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. 向前转发前缀:

现在让我们看看如何做一些稍微不同的事情:前锋。

在编写代码之前,让我们快速、高层次地概述转发与重定向的语义

  • 重定向将在位置标头中使用 302 和新 URL 进行响应;然后,浏览器/客户端将对新 URL 发出另一个请求。
  • 转发完全发生在服务器端。Servlet 容器将相同的请求转发到目标 URL;网址不会在浏览器中更改。

现在让我们看一下代码:

@Controller
@RequestMapping("/")
public class RedirectController {@GetMapping("/forwardWithForwardPrefix")public ModelAndView redirectWithUsingForwardPrefix(ModelMap model) {model.addAttribute("attribute", "forwardWithForwardPrefix");return new ModelAndView("forward:/redirectedUrl", model);}
}

重定向:相同,forward: 前缀将由 UrlBasedViewResolver 及其子类解析。在内部,这将创建一个 InternalResourceView,该视图对新视图执行 RequestDispatcher.forward()。

当我们使用 curl 执行命令时

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

总结一下,与我们在重定向解决方案中遇到的两个请求相比,在这种情况下,我们只有一个请求从浏览器/客户端传出到服务器端。当然,之前由重定向添加的属性也丢失了。

6. 具有重定向属性的属性

接下来,让我们仔细看看在重定向中传递属性,充分利用 RedirectProperties 的框架:

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

如前所述,我们可以直接在方法中注入属性对象,这使得这种机制非常易于使用。

另请注意,我们还添加了 flash 属性。这是一个不会进入 URL 的属性。

有了这种属性,我们以后只能在重定向的最终目标方法中使用 @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

这样,使用 RedirectAttributes 而不是 ModelMap 使我们能够只在重定向操作中涉及的两个方法之间共享某些属性

7. 没有前缀的替代配置

现在让我们探索另一种配置:不使用前缀的重定向。

为了实现这一点,我们需要使用 org.springframework.web.servlet.view.XmlViewResolver

/WEB-INF/spring-views.xml

这代替了我们在先前配置中使用的org.springframework.web.servlet.view.InternalResourceViewResolver



我们还需要在配置中定义一个 RedirectView bean:



现在我们可以通过按 id 引用这个新 bean 来触发重定向

@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

这是我们的结果:

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

8. 重定向 HTTP POST 请求

对于银行付款等用例,我们可能需要重定向 HTTP POST 请求。根据返回的 HTTP 状态代码,POST 请求可以重定向到 HTTP GET 或 POST。

根据 HTTP 1.1 协议参考,状态代码 301(永久移动)和 302(已找到)允许将请求方法从 POST 更改为 GET。该规范还定义了相应的 307(临时重定向)和 308(永久重定向)状态代码,这些代码不允许将请求方法从 POST 更改为 GET。

让我们看一下将 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");
}

现在我们将使用 curl 命令测试 POST 的重定向

curl -L --verbose -X POST http://localhost:8080/spring-rest/redirectPostToPost

我们被重定向到目标位置:

> 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. 使用参数转发

现在,让我们考虑一个场景,我们希望将一些参数发送到另一个带有正向前缀的 RequestMapping

在这种情况下,我们可以使用 HttpServletRequest 在调用之间传入参数。

下面是一个 forwardWithParams 的方法,它需要将 param1 和 param2 发送到另一个映射 forwardedWithParams

@RequestMapping(value="/forwardWithParams", method = RequestMethod.GET)
public ModelAndView forwardWithParams(HttpServletRequest request) {request.setAttribute("param1", "one");request.setAttribute("param2", "two");return new ModelAndView("forward:/forwardedWithParams");
}

事实上,映射 forwardedWithParams 可以存在于一个全新的控制器中,而不必位于同一个控制器中:

@RequestMapping(value="/forwardWithParams", method = RequestMethod.GET)
@Controller
@RequestMapping("/")
public class RedirectParamController {@RequestMapping(value = "/forwardedWithParams", method = RequestMethod.GET)public RedirectView forwardedWithParams(final RedirectAttributes redirectAttributes, HttpServletRequest request) {redirectAttributes.addAttribute("param1", request.getAttribute("param1"));redirectAttributes.addAttribute("param2", request.getAttribute("param2"));redirectAttributes.addAttribute("attribute", "forwardedWithParams");return new RedirectView("redirectedUrl");}
}

为了说明这一点,让我们尝试一下这个 curl 命令:

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

结果如下:

HTTP/1.1 302 Found
Date: Fri, 19 Feb 2021 05:37:14 GMT
Content-Language: en-IN
Location: http://localhost:8080/spring-rest/redirectedUrl?param1=one¶m2=two&attribute=forwardedWithParams
Content-Length: 0

正如我们所看到的,param1 和 param2 从第一个控制器移动到第二个控制器。最后,它们出现在转发WithParams指向的名为redirectedUrl的重定向中。

10. 结论

本文说明了在 Spring 中实现重定向的三种不同方法,如何在执行这些重定向时处理/传递属性以及如何处理 HTTP POST 请求的重定向。

相关内容

热门资讯

linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
C++ 机房预约系统(六):学... 8、 学生模块 8.1 学生子菜单、登录和注销 实现步骤: 在Student.cpp的...
A.机器学习入门算法(三):基... 机器学习算法(三):K近邻(k-nearest neigh...
数字温湿度传感器DHT11模块... 模块实例https://blog.csdn.net/qq_38393591/article/deta...
有限元三角形单元的等效节点力 文章目录前言一、重新复习一下有限元三角形单元的理论1、三角形单元的形函数(Nÿ...
Redis 所有支持的数据结构... Redis 是一种开源的基于键值对存储的 NoSQL 数据库,支持多种数据结构。以下是...
win下pytorch安装—c... 安装目录一、cuda安装1.1、cuda版本选择1.2、下载安装二、cudnn安装三、pytorch...
MySQL基础-多表查询 文章目录MySQL基础-多表查询一、案例及引入1、基础概念2、笛卡尔积的理解二、多表查询的分类1、等...
keil调试专题篇 调试的前提是需要连接调试器比如STLINK。 然后点击菜单或者快捷图标均可进入调试模式。 如果前面...
MATLAB | 全网最详细网... 一篇超超超长,超超超全面网络图绘制教程,本篇基本能讲清楚所有绘制要点&#...
IHome主页 - 让你的浏览... 随着互联网的发展,人们越来越离不开浏览器了。每天上班、学习、娱乐,浏览器...
TCP 协议 一、TCP 协议概念 TCP即传输控制协议(Transmission Control ...
营业执照的经营范围有哪些 营业执照的经营范围有哪些 经营范围是指企业可以从事的生产经营与服务项目,是进行公司注册...
C++ 可变体(variant... 一、可变体(variant) 基础用法 Union的问题: 无法知道当前使用的类型是什...
血压计语音芯片,电子医疗设备声... 语音电子血压计是带有语音提示功能的电子血压计,测量前至测量结果全程语音播报࿰...
MySQL OCP888题解0... 文章目录1、原题1.1、英文原题1.2、答案2、题目解析2.1、题干解析2.2、选项解析3、知识点3...
【2023-Pytorch-检... (肆十二想说的一些话)Yolo这个系列我们已经更新了大概一年的时间,现在基本的流程也走走通了,包含数...
实战项目:保险行业用户分类 这里写目录标题1、项目介绍1.1 行业背景1.2 数据介绍2、代码实现导入数据探索数据处理列标签名异...
记录--我在前端干工地(thr... 这里给大家分享我在网上总结出来的一些知识,希望对大家有所帮助 前段时间接触了Th...
43 openEuler搭建A... 文章目录43 openEuler搭建Apache服务器-配置文件说明和管理模块43.1 配置文件说明...