Friday, December 27, 2024
Google search engine
HomeLanguagesJavaSpring MVC – Basic Example using JSTL

Spring MVC – Basic Example using JSTL

JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web pages. They can now simply use a tag related to the task that they need to implement on a JSP page.

To read more in-depth about JSTL refer to this article: JSP Standard Tag Library

So in this article, we are going to discuss a basic spring MVC project where we are going to see the issue without using the JSTL and how JSTL solves the issue. 

Example Project

Basically, we are going to develop a simple form like the below image and we are going to display the data that are entered by the user on the next page. 

 

Here we have used Spring MVC – Form Text Field and Spring MVC – Form Checkbox. So we are going to store the values of Skills inside a String array and we are going to display the data with and without JSTL. Please create the project on your own machine to understand the example in more detail. 

Setup the Project

We are going to use Spring Tool Suite 4 IDE for this project. Please refer to this article to install STS on your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? Go to your STS IDE then create a new maven project, File > New > Maven Project, and choose the following archetype as shown in the below image as follows:  

 

Add the following maven dependencies and plugin to your pom.xml file. 

<!-- 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>

<!-- plugin -->
<build>
    <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>

Below is the complete code for the pom.xml file after adding these dependencies.

File: pom.xml 

XML




    <modelVersion>4.0.0</modelVersion>
    <groupId>com.neveropen</groupId>
    <artifactId>simple-calculator</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>simple-calculator Maven Webapp</name>
    <url>http://maven.apache.org</url>
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.18</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </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>
</project>


Configuring Dispatcher Servlet

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

 

Note: Please refer to the green color box files. Other files are not present in this project. 

So at first create an src/main/java folder and inside this folder create a class named CalculatorAppIntilizer and put it inside the com.neveropen.calculator.config package and extends the AbstractAnnotationConfigDispatcherServletInitializer class. Refer to the below image.

 

And whenever you are extending this class, it has some pre abstract methods that we need to provide the implementation. Now inside this class, we have to just write two lines of code to Configure the Dispatcher Servlet. Before that, we have to create another class for the Spring configuration file. So, go to the src/main/java folder and inside this folder create a class named CalculatorAppConfig and put it inside the com.neveropen.calculator.config package. Below is the code for the CalculatorAppConfig.java file.

File: CalculatorAppConfig.java

Java




package com.neveropen.calculator.config;
  
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
  
@Configuration
@ComponentScan(basePackages = "com.neveropen.calculator.controllers")
public class CalculatorAppConfig {
  
}


And below is the complete code for the CalculatorAppIntilizer.java file. Comments are added inside the code to understand the code in more detail.

File: CalculatorAppIntilizer.java

Java




package com.neveropen.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;
    }
  
}


Setup ViewResolver

Spring MVC is a Web MVC Framework for building web applications. In generic all MVC frameworks provide a way of working with views. Spring does that via the ViewResolvers, which enables you to render models in the browser without tying the implementation to specific view technology. Read more here: ViewResolver in Spring MVC. So for setting up ViewResolver go to the CalculatorAppConfig.java file and write down the code as follows

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

And below is the updated code for the CalculatorAppConfig.java file after writing the code for setting up the ViewResolver. 

File: Updated CalculatorAppConfig.java

Java




package com.neveropen.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.neveropen.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;
    }
  
}


Create DTO

At first, we have to create a DTO class. So go to the src/main/java folder and inside this folder create a class named JSTLDemoDto and put it inside the com.neveropen.calculator.dto package. Below is the code for the JSTLDemoDto.java file. 

File: JSTLDemoDto.java

Java




package com.neveropen.calculator.dto;
  
public class JSTLDemoDto {
  
    private String name;
    
      // Here we have taken the 
      // skills data in Array of String
    private String[] skills;
  
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String[] getSkills() {
        return skills;
    }
  
    public void setSkills(String[] skills) {
        this.skills = skills;
    }
  
}


Create Controller 

Go to the src/main/java folder and inside this folder create a class named JSTLController and put it inside the com.neveropen.calculator.controllers package. Below is the code for the JSTLController.java file.

File: JSTLController.java file

Java




package com.neveropen.calculator.controllers;
  
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
  
import com.neveropen.calculator.dto.JSTLDemoDto;
  
@Controller
public class JSTLController {
  
    @RequestMapping("/jstl")
    public String showRegistrationPage(@ModelAttribute("jstldemo") JSTLDemoDto jstlDemoDto) {
        return "jstl-demo";
    }
      
    @RequestMapping("/display-data")
    public String displayData(@ModelAttribute("jstldemo") JSTLDemoDto jstlDemoDto) {
        return "display-data";
    }
  
}


Reference article: Spring MVC @ModelAttribute Annotation with Example  

Create View

Now we have to create a view named “jstl-demo” inside the WEB-INF/view folder with the .jsp extension. So go to the src > main > webapp > WEB-INF and create a folder view and inside that folder create a jsp file named jstl-demo. So below is the code for the jstl-demo.jsp file. 

File: jstl-demo.jsp

HTML




<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
</head>
<body>
  
    <h1 align="center">JSTL Basic Example</h1>
  
    <form:form action="display-data" method="get" modelAttribute="jstldemo">
  
        <div align="center">
  
            <!-- A Simple Input Field -->
            <label>Name : </label>
            <form:input path="name" />
  
            <br />
              
            <!-- CheckBox Field -->
            <label>Skills : </label>
            Java : <form:checkbox path="skills" value="java"/>
            Python : <form:checkbox path="skills" value="python"/>
            C++ : <form:checkbox path="skills" value="cpp"/>
            DSA : <form:checkbox path="skills" value="dsa"/>
            Spring : <form:checkbox path="skills" value="spring"/>
              
            <br />
              
            <!-- Button Field -->
            <input type="submit" value="Display Data">
      
        </div>
      
    </form:form>
</body>
</html>


Similarly, create another view named “display-data” to display the data. So below is the code for the display-data.jsp file. 

File: display-data.jsp

HTML




<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
</head>
<body>
  
    <h1 align="center">JSTL Basic Example</h1>
      
    <h2>The details entered by the user are :</h2>
        Name:         ${jstldemo.name}     <br/>
        Skills:     ${jstldemo.skills} 
  
</body>
</html>


Now let’s run and test our application. 

Run Your Application

To run our Spring MVC Application right-click on your project > Run As > Run on Server. And run your application as shown in the below image as depicted below as follows:  

 

After that use the following URL to run your controller

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

Output:

 

And now click on the Display Data button to display the data that are entered by the user. 

 

But in the Skills what type of data we are getting!! 

Entry of JSTL 

So here in the skills, we are getting the reference of the String Array. So whenever we are trying to get the skills it’s giving us the reference instead of the content. For example, in this project, we have selected Java, DSA, and Spring and they are getting stored inside the “String[] skills” array (go to the JSTLDemoDto.java file). Right now we have the array object and in that object, there are 3 values (Java, DSA, and Spring) and we have to iterate the array and get those values. And here JSTL comes into the picture. So we can do it by making the following changes to our project. 

Step 1: 

Add the below dependency to your pom.xml file. 

XML




<dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>


Step 2:

Add the JSTL tags in the JSP files (Here display-data.jsp file).

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

Step 3: 

Write down the following for loop to iterate the Array.

<c:forEach var="skill" items="${jstldemo.skills}">
    ${skill}
</c:forEach>

Below is the complete code for the display-data.jsp file. 

File: Updated display-data.jsp

HTML




<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
</head>
<body>
  
    <h1 align="center">JSTL Basic Example</h1>
      
    <h2>The details entered by the user are :</h2>
        Name:         ${jstldemo.name}     <br/>
        Skills:      
          
            <c:forEach var="skill" items="${jstldemo.skills}">
                ${skill}
            </c:forEach>     
  
</body>
</html>


Yes, we are done!! Now let’s re-run our application again and see what we got on the display page. 

 

Yes, this time we got the content. So this one is the basic real-world use case of JSTL in the Spring MVC application. 

RELATED ARTICLES

Most Popular

Recent Comments