一、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. java scoket (UDP通信模型)简易聊天室

    import java.net.DatagramPacket; import java.net.DatagramSocket; /** * 接收线程 * * @author xiaoduc * */ ...

  2. Spring AOP (Spring 3.x 企业应用开发实战读书笔记第六章)

    从面相对象编程到面相切面编程,是一种代码组织方式的进化. 每一代的代码组织方式,其实是为了解决当时面对的问题.比如写编译器和写操作系统的时候的年代当然要pop,比如写界面的时候当然要oop,因为界面这 ...

  3. SecureCRT 7 注册码

    Name: Sherrill Ray Company:  空 Serial Number:03-40-084141 License Key: ABWGUE ZPPZ6X XHTN2S 1N7PER A ...

  4. jquery slideDown slideUp 对于table无效

    jquery slideDown slideUp 对于table无效,需要在table外面套一层div才可以使用

  5. WinForm程序中两份mdf文件问题的解决

    在项目中用程序中嵌入mdf文件的方式来进行SQLServer数据库开发非常方便,用来发布开源项目等很方便,点击就可以运行,免部署,特别是在教学中用起来更加方便,老师不用先将数据库文件detach再发给 ...

  6. php连接Access数据库的三种方法

    http://www.php100.com/html/webkaifa/PHP/PHPyingyong/2009/1115/3524.html 虽然不是一个类但先放这儿吧 最近想把一个asp的网站改成 ...

  7. 第三篇、CSS样式简介

    <!--1.行内样式 <p style="background-color:red;font-size:20px"> --> <!--2.页内样式 & ...

  8. IOS-用动画组制作花瓣掉落效果(另附iOS动画图表)

    重要的两个方法:1.动画的数组:animations 2.启动的时间 beginTime 注意:动画组设置了持续时间(duration)可能会导致动画组里面的持续时间不管用 代码如下: #import ...

  9. Eclipse修改java代码后自动重启Tomcat解决办法

    今天甚是郁闷,项目马上要上线了,早上刚到公司打开MyEclipse 10.07提示过期提示,这对于用惯了破解软件的帝国用户的我原本以为小菜一碟. 于是到网上到处找破解软件,不用多长时间,Ok 破解成功 ...

  10. ASCII Table/ASCII表

    ASCII Table/ASCII表 参考: 1.Table of ASCII Characters