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() {
...
}
Related
I have a DAO java class that has a method called getTableFromDatabase(), it queries the MySQL and return resultTable, a hashmap of data. I want to use this hashmap and print the content in my jsp page using Spring MVC, how should I do this?
I know that I can use JSTL to print a table, my problem is how to pass this table from DAO to jsp page.
Thanks !
In spring mvc you have to return a ModelAndView class and this class will carry corresponding jsp file and parameters will be passed to jsp.
For example
In your controller request handler method you will return an instance of ModelAndView
#RequestMapping(...)
public ModelAndView handle(){
ModelAndView ret = new ModelAndView("view name");
ret.addAttribute("x","value");
}
in your jsp you can access to x via ${x} syntax.
Spring mvc document reference:
public ModelAndView addObject(Object attributeValue) Add an attribute
to the model using parameter name generation. Parameters:
attributeValue - the object to add to the model (never null) See Also:
ModelMap.addAttribute(Object), getModelMap()
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/ModelAndView.html
I have created two test methods in my MVC Controller class. In the first method the Model is being passed as an argument and in the second one I instantiate it directly. In both methods I add a single attribute to the Model instance:
#RequestMapping("/test-modelParam")
public String testMethod1(Model model) {
model.addAttribute("testname", "testvalue");
return "/testview";
}
#RequestMapping("/test-modelInstantiatedExplicitly")
public ModelAndView testMethod2() {
ModelAndView mav = new ModelAndView("/testview");
mav.addObject("testname", "testvalue");
return mav;
}
The View gets populated correctly in both cases.
Is there any difference between the two approaches? If so, Where is it preferred to use one over the other?
In the end there is no difference everything will end up in a ModelAndView eventually.
When using the Model or ModelMap as a method argument it will get pre-populated with some values
Path Variables
Result of any #ModelAttribute annotated methods
Any #SessionAttributes available to the controller
In short it is the pre-populated model made available to the method.
The Model is always created and is merged with the one you add/create with a ModelAndView.
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 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 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.