Open In App
Related Articles

Query String and Query Parameter in Spring MVC

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

According to Wikipedia “A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a page, or jumping to positions in multimedia content.” Let’s understand this statement in a simple way by an example. Suppose you have filled out a form on the internet and if you have noticed the URL something like as shown below as follows:  

http://internet.org/process-homepage?number1=23&number2=12

So in the above URL, the query string is whatever follows the question mark sign (“?”) i.e (“number1=23&number2=12”) this part. And “number1=23”, “number2=12” are Query Parameters which are joined by a connector “&”. 

Let us consider another URL something like as follows: 

http://internet.org?title=Query_string&action=edit

So in the above URL, the query string is “title=Query_string&action=edit” this part. And “title=Query_string”, “action=edit” are Query Parameters which are joined by a connector “&”. 

In this article, we are going to discuss the concept of the query string and query parameter from the Spring MVC point of view. We are going to develop a simple MVC application and will understand how query strings and query parameters are generated. 

Implementation

Step 1: 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 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:  

 

Step 2: Add the following maven dependencies and plugin to the 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.geeksforgeeks</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>

                    

Step 3: Configuring Dispatcher Servlet

Let us prior have a look at the file structure in the below image. 

 

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

 

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.geeksforgeeks.calculator.config package.

File: CalculatorAppConfig.java

package com.geeksforgeeks.calculator.config;

// Importing required classes 
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

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

Here is the complete code for the CalculatorAppIntilizer.java file.

File: CalculatorAppIntilizer.java

Java

// Java Program to Illustrate CalculatorAppIntilizer
  
package com.geeksforgeeks.calculator.config;
  
// Importing required classes
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  
// Class
public class CalculatorAppIntilizer
    extends AbstractAnnotationConfigDispatcherServletInitializer {
  
    @Override protected Class<?>[] getRootConfigClasses()
    {
  
        return null;
    }
  
    // Registering the Spring config file
    @Override protected Class<?>[] getServletConfigClasses()
    {
  
        Class aClass[] = { CalculatorAppConfig.class };
        return aClass;
    }
  
    // Adding mapping URL
    @Override protected String[] getServletMappings()
    {
  
        String arr[] = { "/geeksforgeeks.org/*" };
        return arr;
    }
}

                    

Step 4: 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 that is 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

// Java Program to Demonstrate Updated
// Calculator App Configuration
  
package com.geeksforgeeks.calculator.config;
  
// Importing required classes
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;
  
// Class
@EnableWebMvc
@Configuration
@ComponentScan(basePackages
               = "com.geeksforgeeks.calculator.controllers")
public class CalculatorAppConfig {
  
    // Setting up ViewResolver
    @Bean public InternalResourceViewResolver viewResolver()
    {
  
        InternalResourceViewResolver viewResolver
            = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
  
        return viewResolver;
    }
}

                    

Step 5: Create Controller 

Go to the src/main/java folder and inside this folder create a class named AppController and put it inside the ‘com.geeksforgeeks.calculator.controllers’ package. 

File: AppController.java file

// Java Program to Illustrate AppController Class

package com.geeksforgeeks.calculator.controllers;

// Importing required classes
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

// Class
@Controller
public class AppController {

    // Method
    @RequestMapping("/home")
    public String showHomePage() 
    {
        return "welcome-page";
    }
}

Step 6: Create a View

Now we have to create a view named “welcome-page” 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 welcome-page. So below is the code for the welcome-page.jsp file. 

File: welcome-page.jsp

HTML

<html>
<head>
<title>Hello</title>
</head>
<body>
    <h1 align="center">Simple Calculator Application</h1>
  
    <form action="process-homepage" method="get">
  
        <div align="center">
              
<p>
                <label for="num1">Enter First Number : </label> <input type="text"
                    id="num1" name="number1" />
            </p>
  
              
<p>
                <label for="num2">Enter Second Number : </label> <input type="text"
                    id="num2" name="number2" />
            </p>
  
  
            <input type="submit" value="Calculate" />
  
        </div>
  
    </form>
</body>
</html>

                    

The view is looking like this 

 

Step 7: Run Your Application

Now our project is ready to run. So let us test our application and understand the query string concept. 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/home

Output:

 

Now let’s put some values inside the label and click on the Calculate button. Suppose here we have put 23 and 45 and whenever we click on the Calculate button an URL is generated as below as shown:

http://localhost:8080/simple-calculator/geeksforgeeks.org/process-homepage?number1=23&number2=45

And this is because of this line “<form action=”process-homepage” method=”get”>” written in welcome-page.jsp file. So now let’s understand this URL in deep. And as we have discussed earlier here “number1=23&number2=45” is the query string and “number1=23” is the query parameter. Here is the detailed analysis of the above URL

Element

Meaning

httpProtocol
localhostServer
8080Port Number
/simple-calculator/geeksforgeeks.org/process-homepageAddress to the resource
number1=23&number2=45Query String
?Identifier
number1=23, number2=45Query Parameter
&Connector

So this is how query strings and query parameters are generated in the Spring MVC application. 



Last Updated : 09 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads