Spring MVC Iterating List on JSP using JSTL (original) (raw)

JSP Standard Tag Library (JSTL) provides a collection of tags that simplify JSP development by eliminating the need to write Java code directly inside JSP pages. One of the most commonly used JSTL tags is <c:forEach>, which is used to iterate over collections such as List, Set, Array, and Map.

In Spring MVC applications, controllers often send collections of data to JSP pages. JSTL makes it easy to display those collections dynamically without using scriptlets.

Syntax of JSTL forEach Tag

**Syntax 1: Iterate Collection

<c:forEach var="item" items="${collection}">
${item}

**Syntax 2: Iterate with begin, end and step

<c:forEach var="num" begin="1" end="10" step="2">
${num}

Steps to Implement Iterating List on JSP using JSTL in Spring MVC

Follow these steps to create a Spring MVC application that passes a List from the controller to a JSP page and displays its elements using the JSTL <c:forEach> tag.

Step 1: Create a Maven Project

Enter the following details:

Click Finish.

Step 2: Add Required Dependencies

Add Spring MVC, Servlet API, and JSTL dependencies to the pom.xml file.

XML `

4.0.0 com.geeksforgeeks simple-calculator war 0.0.1-SNAPSHOT simple-calculator Maven Webapp http://maven.apache.org

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
  
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.18</version>
    </dependency>
  
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
    
    <dependency>
        <groupId>jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
</dependencies>

<build>
    <finalName>simple-calculator</finalName>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>

`

Before moving into the coding part let's have a look at the file structure in the below image.

Step 3: Configure Dispatcher Servlet( CalculatorAppIntilizer.java)

Registers and configures the Spring DispatcherServlet, acting as the front controller for handling all incoming requests.

Java `

package com.geeksforgeeks.calculator.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class CalculatorAppIntilizer extends AbstractAnnotationConfigDispatcherServletInitializer {

@Override
protected Class<?>[] getRootConfigClasses() {
    // TODO Auto-generated method stub
    return null;
}

// Registering the Spring config file
@Override
protected Class<?>[] getServletConfigClasses() {
    Class aClass[] = { CalculatorAppConfig.class };
    return aClass;
}

// Add mapping url
@Override
protected String[] getServletMappings() {
    String arr[] = { "/geeksforgeeks.org/*" };
    return arr;
}

}

`

Step 4: Configure View Resolver(CalculatorAppConfig.java)

Configure InternalResourceViewResolver to resolve JSP pages.

Java `

package com.geeksforgeeks.calculator.config;

import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.ViewResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver;

@EnableWebMvc @Configuration @ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers") public class CalculatorAppConfig {

// setup ViewResolver
@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/view/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

}

`

Step 5: Create Controller Class(Jstldemocontroller.java)

Create a controller that prepares a List of skills and sends it to the JSP page.

Java `

package com.geeksforgeeks.calculator.controllers;

import java.util.ArrayList; import java.util.List;

import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;

@Controller public class Jstldemocontroller {

@RequestMapping("/jstldemo")
public ModelAndView showHomePage() {

    // Create the List of Skills
    List<String> skills = new ArrayList<String>();
    skills.add("Data Science");
    skills.add("Data Structure");
    skills.add("Javascript");
    skills.add("Python");
    skills.add("SQL");

    // Using ModelAndView
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("jstl-demo-page");
    modelAndView.addObject("skillList", skills);

    return modelAndView;

}

}

`

Step 6: Create JSP Page

This JSP page displays the List received from the controller and uses the JSTL <c:forEach> tag to iterate and render each skill individually on the browser.

HTML `

<%@ taglib uri="http://www.oracle.com/technetwork/java/index.html" prefix="c"%>

List Without Iteration :

${skillList}

List With Iteration :

`

Step 7: Run the Application

After that use the following URL to run your controller

http://localhost:8080/simple-calculator/geeksforgeeks.org/jstldemo

**Output:

So on the output screen, you can see both the list with and without Iteration.