Spring重定向指南

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

<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>

现在我们可以通过按 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 请求的重定向。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值