1. servlet redirection forward and redirect:
There are two ways to use servlet redirection, one is forward and the other is redirect. Forward is a server internal redirect, and the client does not know where the server redirects your current request, and the URL of the address bar remains the same as the URL you visited earlier. Redirect is the client redirect, the server will return your current request, and then give a status to you, tell you should go to re-request another URL, specifically, the Address bar URL becomes a new URL.
2. Modelandview Redirect:
Using spring MVC is typically used to return a view using Modelandview. Modelandview is also a two-way redirection in support of Servlets. For example, 404 pages we generally use redirect redirection, like the following code is redirect redirection:
public ModelAndView getPage404MV() {
ModelAndView mv = new ModelAndView("redirect:/404.htm");
return mv;
}
To use forward redirection, just change the redirect to Forward, and the special Modelandview uses forward redirection by default.
1. Requirements background
Requirement: The spring MVC Framework controller jumps between the controllers and needs to be redirected. There are several situations: without parameter jump, with the parameter splicing URL form jump, with parameters do not join parameters jump, the page can also be displayed.
I thought it was a simple thing, and personally think that the more commonly used one way, 100 degrees all have, these are not problems, but 100 degrees unexpectedly to my surprise, a bunch of not I want results. Helpless Ah, write a comparison of their own all for the later 100 degrees, ha haha ... It's not all that's written. People have given me the impetus to write this blog.
2. Workaround
There is definitely a solution to the demand, a solution, explain the spring of the jump way a lot of, I just say some self-think good, common, spring-loaded some classes and methods.
(1) I have a controller in the background to jump to another controller, why there is such a requirement, is the case. I have a list page, and then I will do a new operation, added in the background after the completion of I want to jump to the list page, do not need to pass parameters, List page default query all.
Mode one: Use Modelandview ReturnNew Modelandview ("Redirect:/tolist");
This way you can redirect to ToList.
Way two: returnString Return"redirect:/toList";
Other ways: There are many other ways, there is no introduction, such as response and so on. This is a redirect without parameters.
(2) The second situation, the list page has query criteria, after jumping my query conditions can not be discarded, so that you need to take parameters, with parameters can be spliced URL
Way one: Manually stitching the URL yourself New Modelandview ("Redirect:/tolist?" Param1= "+value1+"¶m2=" +value2);
There is a drawback, that is, the Chinese language may have garbled problems.
Way two: With Redirectattributes, this is found to be a more useful class
Here with its AddAttribute method, this actually redirects past after you look at the URL, is it automatically spell your URL for you.
How to use:
Attr.addattribute ("Param", value); Return"Redirect:/namespace/tocontroller";
This parameter can be obtained by obtaining parameters in the Tocontroller method, which is then passed to the page. The URL of the past is still the same as the way.
(3) with Parameters not stitching URL page can also get value (this is the focus)
In general, I estimate redirection to all the ways that you want to do this:
@RequestMapping ("/save") PublicString Save (@ModelAttribute ("Form") Bean form,redirectattributes attr) throws Exception { String code = service.save (form); if (code.equals ( "name", Form.getname ());
Attr.addflashattribute ( "success", "add success!"); return "Redirect:/index";
} else{
Attr.addattribute ( "ProjectName", Form.getprojectname ());
Attr.addattribute ( "enviroment", Form.getenviroment ());
Attr.addflashattribute ( "msg", "Add Error!" The error code is: "+rsp.getcode ( ). GetCode () +return "Redirect:/maintenance/toaddconfigcenter";
}
}
@RequestMapping ("/index")
public String save(@ModelAttribute("form") Bean form,RedirectAttributes attr) throws Exception { return "redirect:/main/list";}
Page value No, I said it, directly with the EL expression can be obtained, the principle here is placed in the session, the session will jump to the page immediately after removing the object. So when you refresh, the value will be lost.
3. Summary
The bottom or two kinds of jumps, just spring and then the package, so there are many different ways to jump, you can also seal one, you can use the most primitive response, there is no problem. All right, here we go.
In fact, there is nothing, but knowing this is very simple. I did n’t understand it before. Now I understand it and share it with everyone. Leave me a message if you have any questions.
The Addflashattribute method in spring MVC3
Url:http://www.software8.co/wzjs/java/2943.html
Remember in spring MVC2, when you save Pojo to the database, to return to the success of the page, if you want to bring a bit of information,
then this:
Java code:
// The third parameter (UserModel user) defaults to the binding object @RequestMapping (value = "/ user / save", method = RequestMethod.POST)
public ModelAndView saveUser (HttpServletRequest request, HttpServletResponse response, UserModel user) throws Exception {
ModelAndView mv = new ModelAndView ("/ user / save / result"); // The default is forward mode
// ModelAndView mv = new ModelAndView ("redirect: / user / save / result"); // redirect mode
mv.addObject ("message", "Save user successfully!");
return mv;
}
And after spring MVC 3.1, you can do this
Java code:
@RequestMapping (value = "/ user / save", method = RequestMethod.POST)
public ModelAndView saveUser (UserModel user, RedirectAttributes redirectAttributes) throws Exception {
redirectAttributes.addFlashAttribute ("message", "Save user successfully!"); // With addFlashAttribute, the parameters will not appear in the url address bar
return "redirect: / user / save / result";
}
For a slightly more complete example, the first is a form that fills in some information:
Java code:
<form:form id="MyForm" action="Saveuserdetails.action" method="POST" commandname= "user" >
<form:input type = "text" Name= "firstName" Path= " FirstName "/>
<form:input type= "text" Name= "lastName" Path= " LastName "/>
<form:input type= "text" Name= "email" path= "email"/ >
<input type= "submit" Value= "submit" >
</form:form>
In the controller, you can do this:
Java code:
@RequestMapping (Value= "FirstName", User.getfirstname ());
Redirectattributes.addflashattribute ( "LastName", User.getlastname ()) return "redirect:success.html";
}
Success. HTML:
<div>
in our Database.</h1> </div><br>
However, if F5, you will find that the parameters are missing, because the flash scope is actually only supported redirect, so you can judge:
Java code:
@RequestMapping (value = "/ success.html", method = RequestMethod.GET)
public String successView (HttpServletRequest request) {
Map <String,?> Map = RequestContextUtils.getInputFlashMap (request);
if (map! = null)
return "success";
else return "redirect: someOtherView"; // Give other prompt information
How does spring MVC request forwarding and redirection?
Url:http://blog.sina.com.cn/s/blog_9cd9dc7101016abw.html
Look down:
Because this part of the content is simple, the area is over.
1. Request Forwarding:
(1) Return to Modelandview:
@RequestMapping (value= "/model", Method=requestmethod.get)
Public Modelandview Testforward (Modelandview model, @RequestParam (value= "id", defaultvalue= "1", Required=false) Long ID) {
User u = getbaseservice (). Get (User.class, id);
Model.addobject ("User", u);
Model.setviewname ("forward:index.jsp");
return model;
}
As the above code, if the return Modelandview can be labeled as red, add forward can, if you want to redirect, you can replace the forward to redirect can achieve the purpose.
(2) Return string
@RequestMapping (value= "/forward", Method=requestmethod.get)
Public String Testforward () {
return "forward:/index.action";}
As in the red part of the code.
2. Request Redirection
For request forwarding can be divided into: 1. With parameters 2. Without parameters
(1) with parameters:
Java Code Collection Code
@RequestMapping(value="/redirect",method=RequestMethod.GET) public String testRedirect(RedirectAttributes attr){
attr.addAttribute("a", "a");
attr.addFlashAttribute("b", "b"); return "redirect:/index.action";
}
With parameters can be passed using the Redirectattributes parameter:
Note: 1. Use the addAttribute method of RedirectAttributes to pass parameters will follow the URL, as the above code is http: /index.action? A = a 2. Use addFlashAttribute will not follow the URL, the parameter value will be temporarily saved in session, after the redirect url gets this parameter, remove it from the session. The redirect here must be the method mapping path, jsp is invalid. You will find that b will only appear once in the jsp page after redirection, and b will never appear after refreshing. This verifies that as mentioned above, b will be removed from the session after being accessed. For repeated submissions, you can use this to complete. In addition, if you use RedirectAttributes as a parameter, but did not redirect? In this case, the RedirectAttributes parameter will not be passed in. The model corresponding to forward is passed by default. The official recommendation is:
P:ignoredefaultmodelonredirect= "true"/>
Set the Ignoredefaultmodelonredirect property under Requestmappinghandleradapter, which will improve efficiency and avoid unnecessary retrieval.
(2) No parameters
@RequestMapping (value= "/redirect", Method=requestmethod.get)
Public String Testredirect () {
return "Redirect:/index.action";
}
Reprint: http://blog.cangzhitao.com/post/java/ModelAndView-redirect-forward.htm
http://blog.csdn.net/jackpk/article/details/19121777
Spring MVC uses Modelandview.setviewname ("Forward:*.action") to send redirects