i need to pass an object into a page that i'm going to redirect
#RequestMapping(value = "/createNewQuest",method={ RequestMethod.GET, RequestMethod.POST })
public ModelAndView createNewQuest(Quest quest,ModelAndView mav) {
questService.addQuest(quest);
mav.addObject("quest", quest);
mav.setViewName("redirect:/control/displayQuest");
return mav;
}
my controller class seems like this but displayQuest page not getting the quest object?
any help wil be greatly appreciabl..
Spring added Flash Attributes to handle this scenario:
Annotated controllers typically do not need to work with FlashMap
directly. Instead an #RequestMapping method can accept an argument of
type RedirectAttributes and use it to add flash attributes for a
redirect scenario. Flash attributes added via RedirectAttributes are
automatically propagated to the "output" FlashMap. Similarly after the
redirect attributes from the "input" FlashMap are automatically added
to the Model of the controller serving the target URL.
Example
#RequestMapping(value = "/createNewQuest",method={ RequestMethod.GET, RequestMethod.POST })
public ModelAndView createNewQuest(#ModelAttribute("quest") Quest quest,
BindingResult binding, ModelAndView mav,
final RedirectAttributes redirectAttributes) {
questService.addQuest(quest);
redirectAttributes.addFlashAttribute("quest", quest);
mav.setViewName("redirect:/control/displayQuest");
return mav;
}
if you are using spring form tag , then your form tag should look like below
<form:form name="yourformname" id="formid" commandName="quest">
then you controller model object "quest" will be mapped to spring form tag commandName variable, later you can access the variable
Related
I use Spring MVC, I have controller with a method:
#RequestMapping(value = "/listReader", method = RequestMethod.POST)
public #ResponseBody
List<Reader> getListReader(ModelMap model) {
return libraryService.getAllReaders();
}
But I do not know:
How can use list (that I get from method getListReader by #ResponseBody) in JSP?
How can I get list in JSP?
How do to display a list in JSP-page?
How do to get the list from #ResponseBody in JSP?
Give an example, please.
You can't. #ResponseBody is basically telling Spring: take the object I (method) return and use any serializer you have that supports it and write it directly to the body of the HTTP response. There's no JSP involved here.
Instead you should add the list to the model and return the String view name of your JSP.
#RequestMapping(value = "/listReader", method = RequestMethod.POST)
public String getListReader(ModelMap model) {
model.addAttribute("someKey", libraryService.getAllReaders());
return "my-jsp";
}
then you can use EL in the JSP to retrieve it
<h3>${someKey}</h3>
Use JSTL to iterate over it.
#RequestMapping(value = "/listReader", method = RequestMethod.POST)
That defines an Endpoint.
I would suggest using RequestMethod.GET than RequestMethod.POST, since you want something from the server not POSTING something to the server.
On the other Hand, if you want to use that information on a JSP, there are two ways:
1) Some view could consume that information via a http-GET-Request like $.get in jQuery or ajax. After you got the data, you can insert it in your HTML
2) Instead of using ajax you could display it directly on the page.
Then, you have to put your List into a Model, which you can acces on your JSP with Expression Language. Then you have to remove the #ResponseBody and return an according view instead.
I have been using the following code:
#RequestMapping(value="/myUrl", method=RequestMethod.GET)
public ModelAndView myRequestHandler(
HttpServletRequest request, HttpServletResponse response,
#ModelAttribute(value="paramName") #ValidMyModelForm form)
// automatically populates form setters from form:form in JSP view
{
}
Reading the answers at the following link I am starting to doubt that my usage of ModelAttribute is not correct here.
What is #ModelAttribute in Spring MVC?
Am I using it the right way? It seems to work but want to make sure I am not doing anything wrong.
The form object is added to model in a separate method using code that looks like:
modelAndView.addObject("formName", new MyModelForm());
In the JSP view I have a the forms name added as the commandName="formName".
This signature also should have worked perfectly for you:
public ModelAndView myRequestHandler(#Valid MyModelForm form)
here Spring MVC will ensure that a MyModelForm instance is created and bound based on what is submitted from your form.
Now, what does additional #ModelAttribute bring you:
First the simple case:
public ModelAndView myRequestHandler(#ModelAttribute("paramName") #Valid MyModelForm form)
Assuming you do not have any other method with #ModelAttribute, what the above will do is look for a model by name paramName, which is not likely to be present because of the assumption, then an instance of MyModelForm will be created and bound just like before, with one addition that you now have a model object with name paramName available that you can use in your view:
paramName.myformValue etc..
So in essence:
public ModelAndView myRequestHandler(#ModelAttribute("paramName") #Valid MyModelForm form)
is equivalent to:
public ModelAndView myRequestHandler(#Valid MyModelForm form, Model model) {
...
model.addAttribute("paramName", form)
}
Secondly, if you had a method annotated with #ModelAttribute which preloads say part of your MyModelForm:
#ModelAttribute("paramName");
public MyModelForm loadModel(int id) {
MyModelForm fromDB = loadFromDB(id);
}
Now, the advantage of your method signature:
public ModelAndView myRequestHandler(#ModelAttribute("paramName") #Valid MyModelForm form)
will be that the model that you have pre-populated from your DB, will be enhanced with what is submitted in the form.
I think the original question was confusing.
I have a HashMap that needs to be a Collection from a database that I'd like to send to a view via a Spring Controller. I don't want to put this HashMap in the model.addAttribute() because the Spring Model object returns a Map and my JSP needs the collection to be a Collection<Object>. If I set my HashMap.values() in a request.setAttribute, how do I go about dispatching that request variable to the view if my method is returning a String?
#RequestMapping(method = RequestMethod.GET)
public String home(Locale locale, Model model, HttpServletRequest request) {
model.addAttribute("surveys", mySurveys); //this is a map and I need a Collection<Object>
//So I'd like to do this, but how do I get to the "evaluations" object in a view if I'm not dispatching it (like below)??
request.setAttribute("evaluations", mySurveys);
//RequestDispatcher rd = request.getRequestDispatcher("pathToResource");
//rd.forward(request, response);
return "home";
}
EDIT: The Spring Tag library cannot be used for this particular usecase.
Thanks.
If mySurveys is a Map, then perhaps you can put mySurveys.values() into the ModelMap instead of mySurveys (Also, are you intending to use a ModelMap instead of a Model?)
In the code below, surveys would be a Collection of Objects and would be accessible in the jsp via ${surveys}
#RequestMapping(method = RequestMethod.GET)
public String home(ModelMap modelMap, HttpServletRequest request) {
Map<String,Object> mySurveys = getMySurveys();
modelMap.addAttribute("surveys", mySurveys.values());
return "home";
}
I think you're confused as to what ModelMap is.
You can annotate whatever variable you want to access in the view by #ModelAttribute and Spring will automatically instantiate it, and add it to the ModelMap. In the view, you can use it like:
<form:form modelattribute="myAttribute">
<form:input path="fieldInAttribute">
</form:form>
Hope this answers your question
I'm looking for a way to access a BindingResult from within the view (in my case a JSP page).
I have the following controller method:
#RequestMapping(value="/register/accept.html",method=RequestMethod.POST)
public ModelAndView doRegisterAccept(
#Valid #ModelAttribute("registrationData") RegistrationData registrationData,
BindingResult bindingResult
) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("bindingResultXXX", bindingResult);
modelAndView.setViewName("users/registration/register");
return modelAndView;
}
When executing this, the RegistrationData get's populated and the errors are stored in the BindingResult. So far, so good. However, I do have to add the BindingResult manually into the ModelAndView for it to become visible within the View.
Is there a way to automatically add the BindingResult into the model? I already tried adjusting the method signature to
public ModelAndView doRegisterAccept(
#Valid #ModelAttribute("registrationData") RegistrationData registrationData,
#ModelAttribute("bindingResult") BindingResult bindingResult
) {
where I was hoping - as any other parameter - the BindingResult would get added into the model under the key bindingResultbut unfortunately that's not working.
So, any ideas?
Addition
I just found that the results indeed get published using the key
org.springframework.validation.BindingResult.<NAME_OF_MODEL_ATTRIBUTE>
so I suppose just adding it under the plain name is not encouraged by the Spring guys?!
You have to add "errors" tag in your form view, as described here : http://static.springsource.org/spring/docs/3.0.5.RELEASE/reference/view.html#view-jsp-formtaglib-errorstag.
Then in your Controller, you just put a test :
if(bindingResult.hasErrors()) {
... display your form page again
(and "errors" tags will be populated by validation messages corresponding to each field) ...
}
else {
... here, you know that your RegistrationData is valid so you can treat it (save it I guess) ...
}
I am using spring mvc with Annotations, see the following snippet
#RequestMapping(value = "/configuration/", method = RequestMethod.GET)
public MyModel viewConfiguration() {
The problem I am having accessing the 'MyModel' class in my JSP.
How can I do this, without using the ModelAndView object?
This shorthand syntax means that MyModel becomes a model attribute named myModel (i.e. class name with the first letter decapitalized).
View name is inferred from the URL.
See also:
15.3.2.3 Supported handler method arguments and return types
15.10.3 The View - RequestToViewNameTranslator
You could set MyModel as a request attribute to be accessed in your JSP. I'm curious, why don't you want to use ModelAndView? After all, it does what you want to do here, which displays the view and provides a container to hold your objects you want to reference in your view.
By the way, if this is an Ajax call, you will need to add #ResponseBody to the API so that your javascript can read the response in the callback function:-
#RequestMapping(value = "/configuration/", method = RequestMethod.GET)
public #ResponseBody MyModel viewConfiguration() {
...
}