SpringMVC passes parameters to the redirected page

RedirectAttributes pass parameters to the redirected page

There are two ways for the servlet container to jump on the page, forward and redirect. When forward, the jump on the server side is applied, and the same request is applied. The redirect is that the server tells the browser to ask the browser to re-request a new address by responding with 301 and the corresponding new address. The first request and the second request do not use the same request. So in this case, you cannot pass parameters directly to the new page through request. SpringMVC uses forward request by default. If you need to use redirect to jump to a new page, you can use a redirect:prefix. The parameters added to the Model during the forward request can be passed to the new page, and redirect:when jumping to the new page, the original type of attributes and the original type of Collection/Array contained in the current Model will be automatically used as query parameters by default. pass on. For example, for the processor mapping below, if we request /redirect/abcit, it will automatically jump to it /abc, and the query parameters will be attached ?a=1&b=2&c=1&c=2&c=3, so the browser will automatically request it /abc?a=1&b=2&c=1&c=2&c=3.

@RequestMapping("/redirect/{target}")
public String redirectTo(@PathVariable("target") String redirectTo, Map<String, Object> model) {
    model.put("a", "1");
    model.put("b", 2);
    model.put("c", Arrays.asList(1, 2, 3));
    return "redirect:/" + redirectTo;
}

For complex objects, query parameters cannot be automatically passed. At this time, we can use RedirectAttributes, which is a special Model. It is defined as follows:

public  interface  RedirectAttributes  extends  Model {

	@Override
	RedirectAttributes addAttribute(String attributeName, Object attributeValue);

	@Override
	RedirectAttributes addAttribute(Object attributeValue);

	@Override
	RedirectAttributes addAllAttributes(Collection<?> attributeValues);

	@Override
	RedirectAttributes mergeAttributes(Map<String, ?> attributes);

	/**
	 * Add the given flash attribute.
	 * @param attributeName the attribute name; never {@code null}
	 * @param attributeValue the attribute value; may be {@code null}
*/RedirectAttributesaddFlashAttribute(StringattributeName, ObjectattributeValue);	 
	   

	/**
	 * Add the given flash storage using a
	 * {@link org.springframework.core.Conventions#getVariableName generated name}.
	 * @param attributeValue the flash attribute value; never {@code null}
*/RedirectAttributesaddFlashAttribute(ObjectattributeValue);	 
	  

	/**
	 * Return the attributes candidate for flash storage or an empty Map.
*/Map<String, ?>getFlashAttributes();	 
	 
}

Attributes added by methods such as addAttribute inherited from Model will be lost during redirection or passed as query parameters. The attributes added by addFlashAttribute can be automatically passed to the Model of the new page, and it will be placed in a FlashMap internally to distinguish input and output. Managed by FlashMapManager, the default implementation is Session-based implementation, namely SessionFlashMapManager. When redirect needs to pass parameters to the new page, we can declare a parameter of type RedirectAttributes for the handler method as follows, and then add the parameters to be passed through addFlashAttribute. In the following example, the parameters key1 and key2 passed by addAttribute will be passed as query parameters, and modelAttr1, modelAttr2 and listAttr passed by addFlashAttribute will be passed through FlashMap.

@RequestMapping("/src")
public String index(RedirectAttributes redirectAttributes) {
    
    /** 
     * The content in addAttribute will be passed as the query parameter of the redirect URL, that is, it will be passed in the form of 
     * /redirectattributes/target?key1=value1 & key2=value2, 
     * where the value is passed in the form of String, When it is added, it will be converted to String, and if there is no corresponding converter support inside, 
     * will throw an exception. For details, please refer to the corresponding implementation in RedirectAttributesModelMap 
*/ 
    redirectAttributes . addAttribute( " key1 " , " value1 " )     
        .addAttribute("key2", "value2");
    
    /** 
     * The content in addFlashAttribute will be stored in the Session and will be invalid after a page jump. 
*/ 
    redirectAttributes . addFlashAttribute( " modelAttr1 " , " modelAttr1Value1 " )     
        .addFlashAttribute("modelAttr2", "modelAttr1Value2")
        .addFlashAttribute("listAttr", Arrays.asList(1, 2, 3));
    
    return "redirect:/redirectattributes/target";
}

In addition to passing parameters through RedirectAttributes, we can also directly obtain the FlashMap whose role is output and pass it by adding attributes to it. In fact, when using RedirectAttributes, the bottom layer is also passed through the FlashMap whose role is Output. Examples are as follows.

@RequestMapping("/src")
public String index(HttpServletRequest request) {
    
    FlashMap flashMap = RequestContextUtils.getOutputFlashMap(request);
    flashMap.put("abc", 111);
    return "redirect:/redirectattributes/target";
}

After the redirection, the parameters passed through FlashMap will be automatically sent to the Model, so we can get the corresponding parameters from the Model. If it is on the page, we can get it directly from the request. If it is in the Controller method, it can be obtained by using @ModelAttribute on the method parameter, or you can directly define the method parameter of the Model or Map type, and then obtain it from the Model or Map. In the following example, the method parameter modelAttr1 is to obtain the parameter modelAttr1 from the Model, and the method body also defines the parameter modelAttr1 to be obtained from the model parameter.

@RequestMapping ( " /target " )
 public  String target( @ModelAttribute ( " modelAttr1 " ) String modelAttr1, @RequestParam ( " key1 " ) String key1, Map< String , Object > model) {
     // Get the modelAttr1 passed by FlashMap The value of 
    Object attr1 = model . get( " modelAttr1 " );
     return  "redirect_attributes_target";
}

We can also get this information directly from the FlashMap of the Input role. In fact, the bottom layer is also the parameters passed by the redirect obtained from the FlashMap, and then throw them into the Model. An example is as follows:

@RequestMapping("/target")
public String target(HttpServletRequest request) {
    Map<String, ?> map = RequestContextUtils.getInputFlashMap(request);
    Object attr1 = map.get("modelAttr1");
    return "redirect_attributes_target";
}

It should be noted that the parameters passed by redirect only exist in the session for a while, and will be cleared from the session after the request reaches the redirected page.

(This article is written based on Spring 4.1.0)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326069893&siteId=291194637