Spring MVC controller Jump redirect pass-through parameter

Source: Internet
Author: User

url:http://zghbwjl.blog.163.com/blog/static/12033667220137795252845/

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
return new Modelandview ("Redirect:/tolist");
This way you can redirect to ToList.
Mode two: return string
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+" &param2= "+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 do not splice URL page can also get the value (the focus is this)
In general, I estimate redirection to all the ways that you want to do this:

@RequestMapping ("/save")
Public String Save (@ModelAttribute ("form") Bean form,redirectattributes attr)
Throws Exception {


String code = service.save (form);
if (Code.equals ("000")) {
Attr.addflashattribute ("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!" error code is: "+rsp.getcode (). GetCode () +", Error: "+rsp.getcode (). GetName ());
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 know this is very simple, did not understand before, now understand, and everyone to share. Give me a message if you have any questions.

The Addflashattribute method in spring MvC3 url:http://www.software8.co/wzjs/java/2943.html remember that in spring MVC2, when you save Pojo to the database, To return to the Success page, if you want to bring a bit of information at this time, do this: Java code:
    1. The third parameter (Usermodel user) defaults to the bound object
    2. @RequestMapping (value = "/user/save", method = Requestmethod.post)
    3. Public Modelandview Saveuser (httpservletrequest request, HttpServletResponse Response,usermodel user) throws Exception {
    4. Modelandview mv = new Modelandview ("/user/save/result");//default to Forward mode
    5. Modelandview mv = new Modelandview ("Redirect:/user/save/result");//redirect mode
    6. Mv.addobject ("message", "Save user success!") ");
    7. return MV;
    8. }
And after spring MVC 3.1, you can do this Java code:
    1. @RequestMapping (value = "/user/save", method = Requestmethod.post)
    2. Public Modelandview saveuser (usermodel user, redirectattributes redirectattributes) throws Exception {
    3. Redirectattributes.addflashattribute ("message", "Save user success!") ");//Use Addflashattribute, the parameter does not appear in the URL address bar
    4. return "Redirect:/user/save/result";
    5. }
For a slightly more complete example, the first is a form that fills in some information: Java code:
    1. <form:form id= "MyForm" action= "saveuserdetails.action" method= "POST" commandname= "User" >
    2. <form:input type= "text" name= "FirstName" path= "FirstName"/>
    3. <form:input type= "text" name= "LastName" path= "LastName"/>
    4. <form:input type= "text" name= "email" path= "email"/>
    5. <input type= "Submit" value= "Submit" >
    6. </form:form>
In the controller, you can do this: Java code:
  1. @RequestMapping (value= "/saveuserdetails.action", Method=requestmethod.post)
  2. Public String greetingsaction (@Validated User user,redirectattributesredirectattributes) {
  3. Someuserdetailsservice.save (user);
  4. Redirectattributes.addflashattribute ("FirstName", User.getfirstname ());
  5. Redirectattributes.addflashattribute ("LastName", User.getlastname ())
  6. return "redirect:success.html";
  7. }
  8. Success.html:
  9. <div>
  10. </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:
    1. @RequestMapping (value= "/success.html", Method=requestmethod.get)
    2. Public String Successview (HttpServletRequest request) {
    3. map<string,?> map = requestcontextutils.getinputflashmap (request);
    4. if (map!=null)
    5. Return "Success";
    6. else return "Redirect:someotherview"; Give other Tips

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
    1. @RequestMapping (value= "/redirect", Method=requestmethod.get)
    2. Public String Testredirect (redirectattributes attr) {
    3. Attr.addattribute ("A", "a");
    4. Attr.addflashattribute ("B", "B");
    5. return "Redirect:/index.action";
    6. }

With parameters can be passed using the Redirectattributes parameter:

Note: 1. Passing parameters using Redirectattributes's AddAttribute method is followed by the URL, as the above code is HTTP:/INDEX.ACTION?A=A

2. Using Addflashattribute will not follow the URL, the value of the parameter will be temporarily saved to the session, the redirect URL to get the parameter is removed from the session, where the redirect must be a method mapping path, JSP invalid. You will find that B will only appear once in the JSP page after redirect, and B will no longer appear after the refresh, which verifies that B is removed from the session when it is accessed. This can be done with duplicate submissions.

Also, if Redirectattributes is used as a parameter, but not redirect? In this case, the Redirectattributes parameter is not passed in the past, the default forward corresponding model, the official recommendations are:


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";
}

Spring MVC controller Jump redirect pass-through parameter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.