4.1 C
New York
Saturday, February 3, 2024

Spring MVC – Fundamental Instance utilizing JSTL

Share To Your Friends

[ad_1]

JSP Customary Tag Library (JSTL) is a set of tags that can be utilized for implementing some frequent operations equivalent to looping, conditional formatting, and others. JSTL goals to offer a simple technique to preserve SP pages The usage of tags outlined in JSTL has Simplified the duty of the designers to create Net pages. They’ll now merely use a tag associated to the duty that they should implement on a JSP web page.

To learn extra in-depth about JSTL consult with this text: JSP Customary Tag Library

So on this article, we’re going to focus on a fundamental spring MVC venture the place we’re going to see the difficulty with out utilizing the JSTL and the way JSTL solves the difficulty. 

Instance Venture

Mainly, we’re going to develop a easy kind just like the beneath picture and we’re going to show the information which might be entered by the consumer on the following web page. 

 

Right here we have now used Spring MVC – Type Textual content Discipline and Spring MVC – Type Checkbox. So we’re going to retailer the values of Abilities inside a String array and we’re going to show the information with and with out JSTL. Please create the venture by yourself machine to grasp the instance in additional element. 

Setup the Venture

We’re going to use Spring Device Suite 4 IDE for this venture. Please consult with this text to put in STS in your native machine How you can Obtain and Set up Spring Device Suite (Spring Instruments 4 for Eclipse) IDE? Go to your STS IDE then create a brand new maven venture, File > New > Maven Venture, and select the next archetype as proven within the beneath picture as follows:  

 

Add the next 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>
    <model>5.3.18</model>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <model>4.0.1</model>
    <scope>offered</scope>
</dependency>

<!-- plugin -->
<construct>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <model>2.6</model>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</construct>

Under is the whole code for the pom.xml file after including these dependencies.

File: pom.xml 

XML

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.geeksforgeeks</groupId>

    <artifactId>simple-calculator</artifactId>

    <packaging>warfare</packaging>

    <model>0.0.1-SNAPSHOT</model>

    <identify>simple-calculator Maven Webapp</identify>

    

    <dependencies>

        <dependency>

            <groupId>junit</groupId>

            <artifactId>junit</artifactId>

            <model>3.8.1</model>

            <scope>take a look at</scope>

        </dependency>

        

        <dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-webmvc</artifactId>

            <model>5.3.18</model>

        </dependency>

        

        <dependency>

            <groupId>javax.servlet</groupId>

            <artifactId>javax.servlet-api</artifactId>

            <model>4.0.1</model>

            <scope>offered</scope>

        </dependency>

    </dependencies>

    

    <construct>

        <finalName>simple-calculator</finalName>

        <plugins>

            <plugin>

                <groupId>org.apache.maven.plugins</groupId>

                <artifactId>maven-war-plugin</artifactId>

                <model>2.6</model>

                <configuration>

                    <failOnMissingWebXml>false</failOnMissingWebXml>

                </configuration>

            </plugin>

        </plugins>

    </construct>

</venture>

Configuring Dispatcher Servlet

Earlier than shifting into the coding half let’s take a look on the file construction within the beneath picture. 

 

Notice: Please consult with the inexperienced coloration field information. Different information aren’t current on this venture. 

So at first create an src/predominant/java folder and inside this folder create a category named CalculatorAppIntilizer and put it contained in the com.geeksforgeeks.calculator.config bundle and extends the AbstractAnnotationConfigDispatcherServletInitializer class. Confer with the beneath picture.

 

And every time you’re extending this class, it has some pre summary strategies that we have to present the implementation. Now inside this class, we have now to simply write two strains of code to Configure the Dispatcher Servlet. Earlier than that, we have now to create one other class for the Spring configuration file. So, go to the src/predominant/java folder and inside this folder create a category named CalculatorAppConfig and put it contained in the com.geeksforgeeks.calculator.config bundle. Under is the code for the CalculatorAppConfig.java file.

File: CalculatorAppConfig.java

Java

bundle com.geeksforgeeks.calculator.config;

  

import org.springframework.context.annotation.ComponentScan;

import org.springframework.context.annotation.Configuration;

  

@Configuration

@ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers")

public class CalculatorAppConfig {

  

}

And beneath is the whole code for the CalculatorAppIntilizer.java file. Feedback are added contained in the code to grasp the code in additional element.

File: CalculatorAppIntilizer.java

Java

bundle com.geeksforgeeks.calculator.config;

  

import org.springframework.internet.servlet.assist.AbstractAnnotationConfigDispatcherServletInitializer;

  

public class CalculatorAppIntilizer extends AbstractAnnotationConfigDispatcherServletInitializer {

  

    @Override

    protected Class<?>[] getRootConfigClasses() {

        

        return null;

    }

  

    

    @Override

    protected Class<?>[] getServletConfigClasses() {

        Class aClass[] = { CalculatorAppConfig.class };

        return aClass;

    }

  

    

    @Override

    protected String[] getServletMappings() {

        String arr[] = { "/geeksforgeeks.org/*" };

        return arr;

    }

  

}

Setup ViewResolver

Spring MVC is a Net MVC Framework for constructing internet purposes. In generic all MVC frameworks present a method of working with views. Spring does that by way of the ViewResolvers, which allows you to render fashions within the browser with out tying the implementation to particular view know-how. Learn extra right here: ViewResolver in Spring MVC. So for establishing 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 beneath is the up to date code for the CalculatorAppConfig.java file after writing the code for establishing the ViewResolver. 

File: Up to date CalculatorAppConfig.java

Java

bundle 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.internet.servlet.ViewResolver;

import org.springframework.internet.servlet.config.annotation.EnableWebMvc;

import org.springframework.internet.servlet.view.InternalResourceViewResolver;

  

@EnableWebMvc

@Configuration

@ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers")

public class CalculatorAppConfig {

  

    

    @Bean

    public InternalResourceViewResolver viewResolver() {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();

        viewResolver.setPrefix("/WEB-INF/view/");

        viewResolver.setSuffix(".jsp");

        return viewResolver;

    }

  

}

Create DTO

At first, we have now to create a DTO class. So go to the src/predominant/java folder and inside this folder create a category named JSTLDemoDto and put it contained in the com.geeksforgeeks.calculator.dto bundle. Under is the code for the JSTLDemoDto.java file. 

File: JSTLDemoDto.java

Java

bundle com.geeksforgeeks.calculator.dto;

  

public class JSTLDemoDto {

  

    non-public String identify;

    

      

      

    non-public String[] expertise;

  

    public String getName() {

        return identify;

    }

  

    public void setName(String identify) {

        this.identify = identify;

    }

  

    public String[] getSkills() {

        return expertise;

    }

  

    public void setSkills(String[] expertise) {

        this.expertise = expertise;

    }

  

}

Create Controller 

Go to the src/predominant/java folder and inside this folder create a category named JSTLController and put it contained in the com.geeksforgeeks.calculator.controllers bundle. Under is the code for the JSTLController.java file.

File: JSTLController.java file

Java

bundle com.geeksforgeeks.calculator.controllers;

  

import org.springframework.stereotype.Controller;

import org.springframework.internet.bind.annotation.ModelAttribute;

import org.springframework.internet.bind.annotation.RequestMapping;

  

import com.geeksforgeeks.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 Instance  

Create View

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

File: jstl-demo.jsp

HTML

<html>

<head>

</head>

<physique>

  

    <h1 align="heart">JSTL Fundamental Instance</h1>

  

    <kind:kind motion="display-data" methodology="get" modelAttribute="jstldemo">

  

        <div align="heart">

  

            

            <label>Identify : </label>

            <kind:enter path="identify" />

  

            <br />

              

            

            <label>Abilities : </label>

            Java : <kind:checkbox path="expertise" worth="java"/>

            Python : <kind:checkbox path="expertise" worth="python"/>

            C++ : <kind:checkbox path="expertise" worth="cpp"/>

            DSA : <kind:checkbox path="expertise" worth="dsa"/>

            Spring : <kind:checkbox path="expertise" worth="spring"/>

              

            <br />

              

            

            <enter kind="submit" worth="Show Information">

      

        </div>

      

    </kind:kind>

</physique>

</html>

Equally, create one other view named “display-data” to show the information. So beneath is the code for the display-data.jsp file. 

File: display-data.jsp

HTML

<html>

<head>

</head>

<physique>

  

    <h1 align="heart">JSTL Fundamental Instance</h1>

      

    <h2>The small print entered by the consumer are :</h2>

        Identify:         ${jstldemo.identify}     <br/>

        Abilities:     ${jstldemo.expertise} 

  

</physique>

</html>

Now let’s run and take a look at our utility. 

Run Your Software

To run our Spring MVC Software right-click in your venture > Run As > Run on Server. And run your utility as proven within the beneath picture as depicted beneath as follows:  

 

After that use the next URL to run your controller

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

Output:

 

And now click on on the Show Information button to show the information which might be entered by the consumer. 

 

However within the Abilities what kind of knowledge we’re getting!! 

Entry of JSTL 

So right here within the expertise, we’re getting the reference of the String Array. So every time we are attempting to get the talents it’s giving us the reference as an alternative of the content material. For instance, on this venture, we have now chosen Java, DSA, and Spring and they’re getting saved contained in the “String[] expertise” array (go to the JSTLDemoDto.java file). Proper now we have now the array object and in that object, there are 3 values (Java, DSA, and Spring) and we have now to iterate the array and get these values. And right here JSTL comes into the image. So we are able to do it by making the next adjustments to our venture. 

Step 1: 

Add the beneath dependency to your pom.xml file. 

XML

<dependency>

    <groupId>jstl</groupId>

    <artifactId>jstl</artifactId>

    <model>1.2</model>

</dependency>

Step 2:

Add the JSTL tags within the JSP information (Right here display-data.jsp file).

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

Step 3: 

Write down the next for loop to iterate the Array.

<c:forEach var="talent" objects="${jstldemo.expertise}">
    ${talent}
</c:forEach>

Under is the whole code for the display-data.jsp file. 

File: Up to date display-data.jsp

HTML

<html>

<head>

</head>

<physique>

  

    <h1 align="heart">JSTL Fundamental Instance</h1>

      

    <h2>The small print entered by the consumer are :</h2>

        Identify:         ${jstldemo.identify}     <br/>

        Abilities:      

          

            <c:forEach var="talent" objects="${jstldemo.expertise}">

                ${talent}

            </c:forEach>     

  

</physique>

</html>

Sure, we’re finished!! Now let’s re-run our utility once more and see what we received on the show web page. 

 

Sure, this time we received the content material. So this one is the essential real-world use case of JSTL within the Spring MVC utility. 

[ad_2]


Share To Your Friends

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles