Spring MVC Model View Controller example
This example isn't going to explain all of the details, but shows how you create a model and pass that information from the controller to the view.
First a bit of the controller. In this bit of code, we create the object myModel and store a couple of variables in it: now and products. Then we return the new ModelAndview.
The first argument hello is the view which presents you with hello.jsp. The second argument sets the object name that will be used in the the hello.jsp (more on that below). The third argument is the actual model object created that stores various variables ... etc.
String now = (new Date()).toString();
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("now", now);
myModel.put("products", this.productManager.getProducts());
return new ModelAndView("hello", "model", myModel);
}
Below is hello.jsp. From the model above, you can see that you access now and products by using the <c /> tag. So ${model.now} contains the current date/time and ${model.products} is an array which is extracted with the <c:forEach /> tag.
<html>
<head><title><fmt:message key="title" /></title></head>
<body>
<h1><fmt:message key="heading" /></h1>
<p><fmt:message key="greeting" /> <c:out value="${model.now}" /></p>
<h3>Products</h3>
<c:forEach items="${model.products}" var="prod">
<c:out value="${prod.description}" /> <em>$<c:out value="${prod.price}" /></em><br /><br />
</c:forEach>
</body>
</html>
References
[Click to add or edit comments])
Please prepend comments below including a date