Passing data from mvc controller to JSP


GitHub: https://github.com/SylkeWay/synthful

Note that the following maven dependency has been included in the pom, which will make the exercise in this page possible.
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>
Getting back to the request handler "anotherHandleRequest( ... )" in the DurianGroveMVController, notice the two high-lighted lines in the code.
@RequestMapping(value = "/h2g2j", method = {RequestMethod.GET,RequestMethod.POST})
public String anotherHandleRequest(ModelMap model,
    @RequestParam("who") String who,
    @RequestParam("street") String street,
    @RequestParam("zip") int zip)
throws Exception {
    Address addr = zipMap.get(zip);
    String city = addr != null ? addr.city : "Walla Walla";
    String state = addr != null ? addr.state.name() : "ZZ";
    String where = String.format("%s, %s, %s %05d", street, city, state, zip);
    model.addAttribute("who", who);
    model.addAttribute("where", where);
    model.addAttribute("what", season);

    logger.info("anotherHandleRequest: {},{},{} ", who, where, season);
    return "Cello";
}
The objects mapped into the ModelMap object can be retrieved by the JSP as ${} variables.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Cello Tremello</title>
</head>
<body>
<h2>Cello Tremello</h2>
${who} lives in ${where} in ${what} .
</body>
</html>

Starting with the URL
http://localhost:8080/durian/v/h1
which is routed by
DurianMVController.handleRequestJoyfully
to get its contents from
/WEB-INF/views/Hello.jsp
which contains a form that invokes
http://localhost:8080/durian/v/duriangrove/h2g2j
which is routed by
DurianGroveMVController.anotherHandleRequest
to gets its contents from
/WEB-INF/views/Cello.jsp
which gets its model objects from
DurianGroveMVController.anotherHandleRequest
which results in the web page displaying

Cello Tremello

Annie Walker lives in 123 Main St, Hampden, MA 01001 in Spring .

No comments:

Post a Comment