一、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. 【转】prototype扩展的JavaScript常用函数库

    Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> ...

  2. php里ezpdo orm框架初探

    http://jackyrong.iteye.com/blog/238930 http://www.oschina.net/project/tag/126/orm?sort=view&lang ...

  3. java后台正则验证

    public static boolean checkPhone(String phone) { Pattern pattern = Pattern.compile("^[1][3-8]+\ ...

  4. eclipse项目文件编码格式和项目不一致的修改方法

    eclipse导入了一个项目,并把其属性设置成了UTF-8,但是打开里面的文档之后,发现还是乱码,看了下属性,发现文档竟然还是GBK的编码 于是就百度了下,发现了解决方法,现在和大家分享下,希望能帮到 ...

  5. Git的安装以及注册账号等操作

    1.安装Git-2.5.1-64-bit.exe  一直下一步直至完成 2.注册github账号 官网地址:https://github.com/github 3.找到一个按钮“New Reposit ...

  6. java Springmvc ajax上传

    ajax上传方式相对于普通的form上传方式要便捷,在更多的时候都会使用ajax (简单的小示例) 1.要先去下载一个 jquery.ajaxfileupload.js(基于jquery.js上的js ...

  7. QT5新手上路(2)发布exe文件

    QT编程教程在网上有很多,但写完代码以后如何打包成可执行exe文件却少有提及,本文主要介绍这一部分:1.首先确认自己建的工程在debug模式下运行无误.2.在release模式下运行一遍.(如何更改成 ...

  8. mysql时间与日期函数

    返回日期相关的 Now() || CURRENT_TIMESTAMP();返回当前时间 to_days(date) 返回日期date是西元0年至今多少天(不计算1582年以前) 转换为天数 date是 ...

  9. Java_log4j

      Log4j是Apache的一个开放源代码项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台.文件.GUI组件,甚至是套接口服务器.事件记录器等:我们也可以控制每一条日志的输出格式: ...

  10. ubuntu的syslog为空,停止写入解决方法

    修改syslog权限: chown syslog:adm syslog