Spring MVC and List Example
By:Roy.LiuLast updated:2019-08-18
In this tutorial, we show you how to print the List values via JSTL c:forEach tag.
P.S This web project is using Spring MVC frameworks v3.2
1. Project Structure
Review the project directory structure, a standard Maven project.
2. Project Dependencies
Add Spring and JSTL libraries.
pom.xml
<properties> <spring.version>3.2.2.RELEASE</spring.version> <jstl.version>1.2</jstl.version> </properties> <dependencies> <!-- jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- Spring Core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> </dependencies>
3. Spring Controller
A Spring controller to return a List.
MainController.java
package com.mkyong.web.controller; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller public class MainController { @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView getdata() { List<String> list = getList(); //return back to index.jsp ModelAndView model = new ModelAndView("index"); model.addObject("lists", list); return model; private List<String> getList() { List<String> list = new ArrayList<String>(); list.add("List A"); list.add("List B"); list.add("List C"); list.add("List D"); list.add("List 1"); list.add("List 2"); list.add("List 3"); return list;
4. JSP Page
To print the returned List from controller, uses JSTL c:forEach tag.
index.jsp
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <html> <body> <h2>Spring MVC and List Example</h2> <c:if test="${not empty lists}"> <ul> <c:forEach var="listValue" items="${lists}"> <li>${listValue}</li> </c:forEach> </ul> </c:if> </body> </html>
Output – http://localhost:8080/SpringMvcExample/
5. Download Source Code
Download – SpringMVC-Lists-Example (11 KB)
References
From:一号门
Previous:Spring MVC @ExceptionHandler Example
COMMENTS