一、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. 【MINA】粘包断包处理

    1.先解释下什么叫粘包和断包 粘包 就是数据以字节的形式在网络中传输,一个数据包的字节可能经过多次的读取粘合才能形成一个完整的数据包 断包 一次读取的内容可能包含了两个或多个数据包的内容,那么我们必须 ...

  2. 通用安全字符串输入,彻底替换server.htmlencode

    Function HTMLEncode(Str) If Isnull(Str) Then HTMLEncode = "" Exit Function End If Str = Re ...

  3. Cordova+angularjs+ionic+vs2015开发(二)

    欢迎加群学习:457351423 这里有4000多部学习视频,涵盖各种技术,有需要的欢迎进群学习! 一.创建空白Cordova应用 打开VS,选择[新建项目],选择其它语言JavaScript或者Ty ...

  4. .bak文件在英文版的sqlserver2014如何生成和恢复

    生成bak备份文件 1.选择数据库 2.右击选择task 3.选择backup 4.

  5. iOS对textField进行字符长度限制的办法

    在项目开发过程中,遇到这么一个需求,编辑标签时,输入的最大长度需要限制为24个字节. 查阅了一些材料,并参考了之前项目的相关处理办法,今天在这里总结一下解决方案. 1.写一个截取字符串的方法,将超长的 ...

  6. 解决自定义BackItem与Pop Gesture冲突的问题

    在做项目的时候遇到的这个问题, 一开始项目要求自定义导航栏返回按钮,结果发生了没法手势返回的问题,以为是需要添加拖拽手势呢,结果折腾了一下午没有实现想要的效果.接着一直百度问题,才发现跑偏了,犯了一个 ...

  7. tomcat安装不成功-提示找不到JAVA虚拟机

    今天重装tomcate,但是总是提示找不到java虚拟机,但是我明明装了jre和jdk,太烦人了 后来搜了各种方法,终于找到了解决方法,现在和大家分享下 到提示找java虚拟机那一步的时候,选择到jr ...

  8. HDU 4768 Flyer(二分法)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4768 题目大意:每组数据有n行输入,每行有三个数A.B.C,A<=B且小于2^32,从A到B每隔 ...

  9. 393. UTF-8 Validation

    393. UTF-8 Validation 这个题很明确,刚开始我以为只能是一个utf,长度大于5的都判断为false,后来才明白题意. 有个小trick,就是长度大于1的时候,判断第一个数字开始1的 ...

  10. const char*、char*、char* const、char[]、string的区别

    1.const char* p: p is a pointer to const char(char const* p 一样)   意思就是不能通过p指针来修改p指向的内容(但是内容可以修改). 2. ...