一、redirect为什么会丢数据?

when a handler method completes, any model data specified in the method is copied into the request as request attributes, and the request is forwarded to the view for rendering. Because it’s the same request that’s handled by both

the controller method and the view, the request attributes survive the forward.But as illustrated in figure 7.1, when a controller method results in a redirect, the original request ends and a new HTTP GET request begins. Any model data carried in the original request dies with the request. The new request is devoid of any model data in its attributes and has to figure it out on its own.Clearly, the model isn’t going to help you carry data across a redirect. But there are
a couple of options to get the data from the redirecting method to the redirect handling method:
 Passing data as path variables and/or query parameters using URL templates
 Sending data in flash attributes

二、拼url字符串

return "redirect:/spitter/" + spitter.getUsername();

三、用model和占位符

在方法中加上model参数,model中的数据能匹配占位符的就作为path参数,否则会作为query参数,如

 @RequestMapping(value = "/register", method = POST)
public String processRegistration(
Spitter spitter, Model model) {
spitterRepository.save(spitter);
model.addAttribute("username", spitter.getUsername());
model.addAttribute("spitterId", spitter.getId());
return "redirect:/spitter/{username}";
}

占位符会编码,把直接拼接字符串安全些,Because it’s filled into the placeholder in the URL template instead of concatenated

into the redirect String , any unsafe characters in the username property are escaped.This is safer than allowing the user to type in whatever they want for the username and then appending it to the path.

因为id匹配不到占位符,假设 username attribute is habuma and the spitterId attribute is 42 , then the resulting redirect path will be /spitter/habuma?spitterId=42

三、用flash attributes->RedirectAttributes

1.需求:

Let’s say that instead of sending a username or ID in the redirect, you want to send the actual Spitter object. If you send just the ID , then the method that handles the redirect has to turn around and look up the Spitter from the database. But before the redirect, you already have the Spitter object in hand. Why not send it to the redirect-handling method to display?

2.

RedirectAttributes是model的子接口,工作原理是用session,Before the redirect takes place, all flash attributes are copied into the session. After the redirect, the flash attributes stored in the session are moved out of the session and into the model. The method that handles the redirect request can then access the Spitter from the model, just like any other model object. Figure 7.2 illustrates how this works.

3.代码实现

 @RequestMapping(value = "/register", method = POST)
public String processRegistration(
Spitter spitter, RedirectAttributes model) {
spitterRepository.save(spitter);
model.addAttribute("username", spitter.getUsername());
model.addFlashAttribute("spitter", spitter);
return "redirect:/spitter/{username}";
}
 @RequestMapping(value = "/{username}", method = GET)
public String showSpitterProfile(
@PathVariable String username, Model model) {
if (!model.containsAttribute("spitter")) {
model.addAttribute(
spitterRepository.findByUsername(username));
}
return "profile";
}

SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-006- 如何保持重定向的request数据(用model、占位符、RedirectAttributes、model.addFlashAttribute("spitter", spitter);)的更多相关文章

  1. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-005- 异常处理@ResponseStatus、@ExceptionHandler、@ControllerAdvice

    No matter what happens, good or bad, the outcome of a servlet request is a servlet response. If an e ...

  2. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-003- 上传文件multipart,配置StandardServletMultipartResolver、CommonsMultipartResolver

    一.什么是multipart The Spittr application calls for file uploads in two places. When a new user register ...

  3. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener

    一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...

  4. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-004- 处理上传文件

    一.用 MultipartFile 1.在html中设置<form enctype="multipart/form-data">及<input type=&quo ...

  5. SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-001- DispatcherServlet的高级配置(ServletRegistration.Dynamic、WebApplicationInitializer)

    一. 1.如想在DispatcherServlet在Servlet容器中注册后自定义一些操作,如开启文件上传功能,则可重写通过AbstractAnnotationConfigDispatcherSer ...

  6. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-004-以query parameters的形式给action传参数(@RequestParam、defaultValue)

    一. 1.Spring MVC provides several ways that a client can pass data into a controller’s handler method ...

  7. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-007-表单验证@Valid、Error

    一. Starting with Spring 3.0, Spring supports the Java Validation API in Spring MVC . No extra config ...

  8. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-005-以path parameters的形式给action传参数(value=“{}”、@PathVariable)

    一 1.以path parameters的形式给action传参数 @Test public void testSpittle() throws Exception { Spittle expecte ...

  9. SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model

    一.RequestMapping 1.可以写在方法上或类上,且值可以是数组 package spittr.web; import static org.springframework.web.bind ...

随机推荐

  1. ASP.NET MVC 4应用程序文件夹

    App_Start It has configuration classes to reduce clutter code in the Global.asax 它包含了配置类来减少在Global.a ...

  2. 第22条:理解NSCopying协议

    如果想自定义类支持拷贝操作,那就要实现NSCopying协议(而不是复写copy方法)或 NSMutableCopying的协议. 不可变版本的拷贝: NSCopying协议,该协议只有一个方法: - ...

  3. C语言 宏/macor/#define/

    C语言 宏/macor/#define 高级技巧 1.在进行调试的时候,需要进行打印/PRINT,可以通过define进行自定义.例如,自己最常用的DEBUG_PRINT() #define DEBU ...

  4. CAF(C++ actor framework)使用随笔(send sync_send)(二)

    a). 发完就忘, 就像上面anon_send 以及send #include <iostream> #include "caf/all.hpp" #include & ...

  5. Linux网络服务器epoll模型的socket通讯的实现(一)

    准备写一个网络游戏的服务器的通讯模块,参考网上看到的一些代码,在linux下面实现一个多线程的epoll模型的socket通讯的代码,以下是第一部分多线程的切换代码: 1 #include <s ...

  6. PHP学习笔记——上传文件到服务端的文件夹下

    环境 开发包:appserv-win32-2.5.10 服务器:Apache2.2 数据库:phpMyAdmin 语言:php5,java 平台:windows 10 需求 编写一个PHP脚本页面,可 ...

  7. Web前端新人笔记之jquery选择符

    jquery利用了CSS选择符的能力,让我们能够在DOM中快捷而轻松的获取元素或元素集合.本章将介绍以下内容: 1.网页中的元素结构: 2.如何通过CSS选择符在页面中查找元素: 3.扩展jquery ...

  8. 关于$.fn

    今天看一篇文章,里面的一段代码出现了$.fn,第一次见到这样的写法,于是跑去问度娘...代码如下: $.fn.scrollUnique = function() { return $(this).ea ...

  9. gulp-less学习教程

    过程安装nodejs -> 全局安装gulp -> 项目安装gulp以及gulp插件 -> 配置gulpfile.js -> 运行任务node.npm安装 自己搜全局安装gul ...

  10. 纯原生js移动端城市选择插件

    接着上一篇纯js移动端日期选择插件,话说今天同事又来咨询省市县联动的效果在移动端中如何实现,还是老样子,百度上一搜,诶~又全是基于jquery.zepto的,更加可恨的是大多数都是PC版的,三个sel ...