SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-006- 如何保持重定向的request数据(用model、占位符、RedirectAttributes、model.addFlashAttribute("spitter", spitter);)
一、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);)的更多相关文章
- 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 ...
- 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 ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-002- 在xml中引用Java配置文件,声明DispatcherServlet、ContextLoaderListener
一.所有声明都用xml 1. <?xml version="1.0" encoding="UTF-8"?> <web-app version= ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-004- 处理上传文件
一.用 MultipartFile 1.在html中设置<form enctype="multipart/form-data">及<input type=&quo ...
- SPRING IN ACTION 第4版笔记-第七章Advanced Spring MVC-001- DispatcherServlet的高级配置(ServletRegistration.Dynamic、WebApplicationInitializer)
一. 1.如想在DispatcherServlet在Servlet容器中注册后自定义一些操作,如开启文件上传功能,则可重写通过AbstractAnnotationConfigDispatcherSer ...
- 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 ...
- 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 ...
- 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 ...
- SPRING IN ACTION 第4版笔记-第五章BUILDING SPRING WEB APPLICATIONS-002-Controller的requestMapping、model
一.RequestMapping 1.可以写在方法上或类上,且值可以是数组 package spittr.web; import static org.springframework.web.bind ...
随机推荐
- FCKEditor的用法与下载
以下是我初次使用FCKEditor的方法,都是来自网上,但网上都不完整,现在我整理下: 1:下载FCKEditor 下载下来后解压到你网站的目录,最好就放在根目录下,文件夹名字就用FCKEditor: ...
- lookup:ID列
对lookup列对应的ID列的引用的写法 if (item["NavType_x003a_ID"].ToString() == type["ID"].ToStr ...
- vs2010打开vs2012的sln文件
1.找到**.sln文件,然后选择用记事本打开. 2.最前面找到“Microsoft Visual Studio Solution File, Format Version 12.00 # Visu ...
- Android沉浸式状态栏实现
Step1:状态栏与导航栏半透明化 方法一:继承主题特定主题 在Android API 19以上可以使用****.TranslucentDecor***有关的主题,自带相应半透明效果 例如: < ...
- 【转】代码高处走 从VC6到VC9移植代码问题说明
首先可以直接用Visual Studio 2008的打开VC6的工作区文件和项目文件(dsw和dsp),并将其升级为VS2008的解决方案格式和项目格式(sln和vcproj),VC9的编译器相对于V ...
- UICollectionView的简单使用
ChildModel.h #import <Foundation/Foundation.h> @interface ChildModel : NSObject @property (non ...
- iso和Android的验证码输入框
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 利用绝对定位与margin实现元素居中
例: 要让一个width:100px ; height: 100px;的div,相对body居中. div{ width:100px; height:100px; border: 1px solid ...
- dorado基本事件样例
var info = self.get("returnValue"); view.set("#labelProduct.text","产品:" ...
- sgu 107 987654321 problem
其实挺水的,因为两个数平方,只有固定的后面几位数会影响到最后结果的后面几位数.也就是说,如果想在平方之后尾数为987654321,那么就有固定的几个尾数在平方后会是这个数,打个表,发现 10^8 内 ...