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
Related
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
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 have a doubt about Model behavior in Spring MVC.
I have a controller class with to handler methods, say:
#RequestMapping(value = "/result", method = RequestMethod.GET)
public String getExportResults(#RequestParam("token") String token,
Model model) {
// ...
model.addAttribute("task", myObject);
// ...
}
#RequestMapping(value = "/file", method = RequestMethod.GET)
public void getFile(Model model, HttpServletResponse response)
// can't find "task" attribute...
}
When I put the "task" attribute into model, in my getExportResults I expect to find it into model argument of getFile method, but when I try to get it, "task" is null.
Am I wrong? Maybe model behaviour is not clear to me...
Your expectations are wrong. Putting something in the model makes it available for the current request only. The goal of adding something into the model is to make it available for the view, in order to generate the HTML page.
Model is initialized with every request, each request creates a new model object. The model you are adding your task object is not the same model object you get in getFile method.
If those are 2 different request, which seems like, you may want to put the task object into session and retrieve it from there.
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() {
...
}