Spring MVC - pass model between controllers - spring-mvc

I have created a controller that does some business logic and creates a model. If I pass this model directly to view by returning ModelAndView with view name and model - everything working great. But now I want to display results at another page. So I use "redirect:" prefix to redirect to another controller, but the model is lost.
What Im missing?
Regards,
Oleksandr

you can use the forward: prefix which ultimately does a RequestDispatcher.forward()
insted of The redirect: prefix.

Option 1 :
You might put the model in session and get it back in the controller and nullify it in session.
Option 2 :
You said, you are having two controllers, first one would retrieve the user input and do some business logic and redirect to other one. My suggestion is to move the business logic which is placed in both controllers to a class and have only one controller which would return the model and view to the user.

During redirect: request is sent using GET method with parameters appended to the url. You can right a new method in the controller to receive the request parameters with #RequestParameter annotation.
While redirecting the request simple add all the parameters as string
e.g ModelAndView mv = new ModelAndView();
mv.setViewName(redirect:/your/url);
mv.addObject("param1", string_param);
.
.
.
This way you can redirect successfully.

Since the redirect: prefix runs another controller, you will lose whatever you had in the ModelAndView in the previous controller. Perhaps the business logic controller should not be a controller at all -- maybe you should just make it a regular class, and have the results controller call it. Then the results controller could save the data to the model.

i would not use #SessionAttributes as it may change in future releases of spring. I would stick with the old fashioned way that Oleksandr showed you above
somehow an old post but maybe someone else will find it usefull

Related

What's the right way to call an action from a different controller in ASP.Net MVC 6

I'm getting a
No route matches the supplied values
while trying to return a RedirectToAction("Action", "Controller"). The method signature says "actionName" and "ControllerName". I'm assuming actionName is the method name in the Controller, Am I correct? For ControllerName I'm using the Controller File Name without the Controller Sufix. Ex.:
return RedirectToAction("Index", "WebApp")
where Index is a method of WebAppController and the command is being issued from a method of AnotherController
Both the caller controller and the called one are on the same Controllers directory on the same application.
I'm cofused because in this ASP.net MVC application there is also Route attributes and Action attributes where you can put names on methods, different than the real method name. In my case I have no Route["Name"] nor [httpXXX("route", Name="dasdasdas")] configured for the methods involved in my attempt.
I have been reading MS docs and some examples but It appears I'm doing the thing right but for strange reasons it's not working. I even tried using Redirect("Controller/Action") and with it the problem vanishes but the new problem is this way of redirect doesn't support passing data parameters to the target route.
At this point I'm not working with Action links in Views, different from Form related ones.
I would really appreciate if at least anyone can give me a hint about where can I find info.
The right way to call an action from a different controller is the one I was using:
return RedirectToAction("AnActionMethodName", "AControllerWithoutControllerSufix"[, object values]);
My problem, after several hour spent was that I added two useMvc calls in the Startup.Configure(...)method:
app.UseMvc();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=MyApp}/{action=Index}/{id?}");
});
This was due to copy + paste of code. It was obviously confusing the MVC component in charge of attending the redirection part, as the right way I supose is tho use only one. (I'm newbie on .Net Platform and its frameworks)
Anyway I leave this as a reminder about the risks and consequences of copying and pasting code. At some point something weird can happen to your app and the cause can be a simple copy + paste error.

Spring MVC retain error meesage after redirect

I have a jsp with 2 input boxes that searches on 2 different scenarios. So , i have two different Get requests mapping to /search1 and /search2 but have created only one POJO for this.
As soon as user submits a search, I check if there is any results for that, and if not i add error message in model and "redirect:"(redirection because if i simply return a page and now make a new search the url will be /search1/search2) to the same basic page.
But everytime i load the page the error message persists.
Any workaround for this? how do i display the messaeg only on search.
Use Flash Attributes.
http://viralpatel.net/blogs/spring-mvc-flash-attribute-example/
Add RedirectAttributes parameter to your controller's handler method.
then redirectAttributes.addFlashAttribute("modelAttributeName", "value");
then redirect
The controller handler that you redirect to should have "modelAttributeName" model attribute available to it.
Essentially your a putting a value into session which is removed as soon as it is read on the next request.
Another solution would be
you can use request parameter to pass message id and write utility to read message from properties file using message id in the get request of redirected controller.
Controller 1
return "redirect:your_redirection_url?messageId=1";
Controller 2 (where redirected)
if (messageid != null && !(messageid.equals(""))) { MessageUtility.addMessage(Integer.parseInt(messageid), model, locale); }

Symfony2 dynamically select controller based on query result

I'm trying to create an extendible cms. I have URLs in my database like "/menu-item/content" for each of these urls there is an action specified in format "AcmeDemoBundle:Default:index".
I would like to resolve this action and call the appropriate controller based on the matched URL.
My main goal is to call the controller stored in the db directly. Before i used a method when i put a route in the end of the routings which matched all urls associate a controller with it that found out the target controller from the db, than used Controller::forward() to get the expected results. The main problem with this approach is that i need to create an unnecessary subrequest for each page load. The other problem is passing post variables to this new subrequest.
So far i've tried to listen on kernel.request event and modify $request->attributes to contain the matching _controller value, but it seems like it has no effect.
Any advice in the subject is appreciated.
I think you mixed up the forward and redirect calls. Redirect performs 301 or 302 redirects (permanent and temporary respectfully), which creates the subrequest, as you call it. Forward performs internal call (same request) to the new action. As for your second problem, as forward is an internal call within the same request, everything global stays the same (including POST variables). In my opinion, using forward might be a good solution for you (if you don't have any other low-level requirements or if you want to be even more flexible than the usual MVC operation allows).
Hope this helps.

MVC4 - Relationship between a View and a Controller

I'm having difficulty grasping the concept of MVC within .NET. I'm creating a basic Blog application, mainly to gain insight and skills with MVC. I just don't quite get some of it. The part I am currently unclear about is the relationship between a Controller and View. It would clear the matter up if someone would answer me this.
I have a View called TestA which corresponds to my Controller ControllerTestA. Now I've added the following inside the ControllerTestA.
public ActionResult TestA (){ //do something }
Now I need to know if all my postbacks in whatever form from view TestA will have to go through my TestA Controller method. So essentially I could have different postback with different parameters for different reasons. Some in use with one postback and others in use for another. Is that how it is done?
Would love some assistance here.
You are missing a crucial part of the relationship here, which is routing. You are speaking in terms of WebForms using terms like Postback; don't do that because you'll end up confusing yourself.
The best way to think about MVC is in Requests and Responses.
Let's look at how a request (high level) happens in an MVC application.
Request
Request hits the server with a url ex. /hello/world
That url is used to match any entries in your route table
When a match is found, that route defines basic values like what controller and action should be called.
The controller is created, and that action is called with the route values and other request properties (querystring, session, etc...).
Response
We are now in the controller action, run the code you need to fulfill the request
Pass the data to the View
The view is determined by convention and your ViewEngine
The view is then rendered and written to the response.
The request/response is finished.
Note
This whole process is determined by the route, and the relationship between the controller and view are trivial. Where the form is posted to is determined by you in the view by using helper methods that determine what route to hit in the next request/response flow.
Some Helper Methods.
#Url.Action("index", "home");
#Html.ActionLink("index", "home")
#using (Html.BeginForm("create", "home")) { }
To sum it all up, the relationship between the controller action and view is really facilitate by your routes. Once you have a grasp of how to create them, then you will better understand how to manage the interaction of your application. Hope that helps. :)
There is no such thing as "Postback" in MVC. In contrast to WebForms, a view only renders HTML to be sent to the browser. As soon as any type of request is issued by the browser, it goes to the controller, not to the view.
As for the relationships:
If you define a TestAController (note: Not "ControllerTestA"), it serves the "/TestA/*" URL's. If you have a method TestA in there it will serve "/TestA/TestA".
If your method returns View(someModel) it will look for a view named TestA.cshtml/TestA.aspx, named like your method, within a folder Views\TestA (named like your controller, without the "Controller" suffix)
The view will render the HTML based on the someModel passed by the controller.
Within the view you may call other URL's or post data to some. This closes the circle.
As for the parameters or overloads, there are some restrictions:
You can define overloads for GET vs. POST vs. PUT vs. DELETE. You will need to annotate the methods with the according attributes though.
However you cannot define multiple overloads of the same method name for POSTs with different sets of parameters. You will need to make your POST method signature such that parameters can or cannot be sent to the server:
Example:
public ActionResult TestA(
string someOptionalParameter, int? someOtherOptionalParam)
{
if (string.IsNullOrEmpty(someOptionalParameter)) { ... }
if (someOtherOptionalParam == null) { ... }
}
The model-mapper will set your parameters to null if they are not posted to the server.
Like Khalid already mentioned - you should not mix up the concepts of MVC and WebForms. They are very different. MVC has no such thing as a "view state" which could be posted to the server. It has no WebForm-like lifecycle for the ASPX (or CSHTML) pages.
If you have a form in a view, then that form has a url to which it will post to. This URL is in the Html.BeginForm method in your view.
The form will then be posted to the appropriate controller methond in the approoriate controller
So if BeginForm starts like this:
using (Html.BeginForm("AddProduct", "Product"
Then the action method "AddProduct" in the controller Product (ProductController is the class name) will be called.

Spring MVC 3.1 - Model Attribute lost

I have a quick question on scope of ModelAttributes.
Dev. Env: Spring MVC 3.1/Java 6/JSP w/JSTL for Views
In my controller, I add an attribute to the model via
model.addAttribute(“appForResubmission”, appForResubmission);
In the JSP(served out in response to a GET request) I read it’s contents as:
${appForResubmission.appId}
— works fine and the data is shown on JSP as expected.
Upon submission of the JSP, in the same controller in a different method(in response to a PUT request), I try to read the attributes from the Model for any changes and I am doing this as
#ModelAttribute(“appForResubmission”) Application app
in the method signature.
However, all I get is a new Application object when I try to interrogate the object for data. Spring’s documentation says this kind of instantiation of a new object happens when the requested attribute does not exist in the Model.
What would cause the attribute to be lost? Any ideas? I am suspecting it is a scope issue someplace but I am not sure where the problem could be.
Any pointers you could provide is greatly appreciated?
Thank you,
M. Reddy
The scope of a modelattribute is the request, internally it is just equivalent to HttpSerletRequest.setAttribute("model", model).
If you want the model to be available in a different controller you probably have two options, one is to reconstruct it, based on what you submit to the controller or using your persistent source. The second option is for specific model attributes to be added to the session using #SessionAttribute({'modelname'}), but just be careful that you have to call SessionStatus.complete to remove the model added to the session later.

Resources