Introduction

Autocomplete allows you to easily create autocomplete and auto-suggest boxes for text input fields. When you start a search on Google, you can find the information you are looking for using search predictions. Search predictions are possible search terms you can use that are related to the terms you are typing and what other people are searching for. Spring Boot MVC autocomplete example will show you exactly the same thing here.

Autocomplete is a feature in which an application predicts the rest of a word a user is typing. In graphical user interfaces, users can typically press the tab key to accept a suggestion or the down arrow key to accept one of several.

Autocomplete speeds up human-computer interactions when it correctly predicts the word a user intends to enter after only a few characters have been typed into a text input field. The autocomplete is a normal text input enhanced by a panel of suggested options.

Here we will create Spring Boot MVC using Gradle script. Here we will use AJAX based auto-complete input field.

If you need Maven based Sping Boot MVC project then you may first like to read Spring Boot MVC with Maven and Spring Boot MVC with Tiles and AJAX.

Prerequisites

Eclipse 4.12, Java 12(or 8), Spring Boot 2.1.7, Gradle 5.6, jQuery 1.12

Creating Project

Create a gradle based project in Eclipse called spring-mvc-autocomplete-input.

Updating Build Script

The default generated build.gradle script does not include required dependencies, so we will include the required dependencies.

We are going to use JSP pages for view technologies.

buildscript { ext { springBootVersion = '2.1.7.RELEASE' } repositories { mavenLocal() mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'org.springframework.boot' sourceCompatibility = 12 targetCompatibility = 12 repositories { mavenLocal() mavenCentral() } dependencies { implementation("org.springframework.boot:spring-boot-starter-web:${springBootVersion}") compile('org.apache.tomcat.embed:tomcat-embed-jasper:9.0.22') compile('javax.servlet:jstl:1.2') }

Creating DAO Class

Create below DAO class in order to provide data to the Service layer.

The actual data should come from database or any other persistent sources.

package com.roytuts.spring.mvc.autocomplete.input.dao; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class AutoCompleteDao { private static final List<String> strings; static { strings = new ArrayList<>(); strings.add("Lorem Ipsum is simply dummy text of the printing and typesetting"); strings.add("Lorem Ipsum has been the industry's standard dummy"); strings.add("nd scrambled it to make a type specimen book. It"); strings.add("typesetting, remaining essentially unchanged. It "); strings.add("sum passages, and more recently with desktop publi"); strings.add("Contrary to popular belief, Lorem Ipsum is not sim"); strings.add("professor at Hampden-Sydney College in Virginia, looked up one"); strings.add("passage, and going through the cites of the word in"); strings.add("comes from sections 1.10.32 and 1.10.33 of \"de Finibus Bonorum"); strings.add("BC. This book is a treatise on the theory of ethics, very popu"); strings.add("here are many variations of passages of Lorem Ipsum availa"); strings.add("believable. If you are going to use a passage of Lorem Ips"); strings.add("middle of text. All the Lorem Ipsum generators on the Intern"); strings.add("tend to repeat predefined chunks as necessary, making this the"); strings.add("first true generator on the Internet. It uses a dictionary of over 20"); strings.add("he standard chunk of Lorem Ipsum used since the 1500s i"); strings.add("1.10.33 from \"de Finibus Bonorum et Malorum\" by Cicero are als"); strings.add("reproduced in their exact original form, accompanied by English"); strings.add("eadable content of a page when looking at its layout. The point"); } public static List<String> getStrings(final String input) { return strings.stream().filter(s -> s.toLowerCase().contains(input.toLowerCase())).collect(Collectors.toList()); } }

Creating Service Class

Create below Service class in order to provide data to Controller layer.

We load the data from DAO layer through the below service class.

package com.roytuts.spring.mvc.autocomplete.input.service; import java.util.List; import org.springframework.stereotype.Service; import com.roytuts.spring.mvc.autocomplete.input.dao.AutoCompleteDao; @Service public class AutoCompleteService { public List<String> doAutoComplete(final String input) { return AutoCompleteDao.getStrings(input); } }

You may also like to read the similar tutorial on Codeigniter jQuery .

Creating REST Controller

Create Rest Controller that returns JSON data to the view.

We call the REST API endpoint through AJAX technique. We are using jQuery UI library directly from CDN to call the REST API.

package com.roytuts.spring.mvc.autocomplete.input.rest.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.roytuts.spring.mvc.autocomplete.input.service.AutoCompleteService; @RestController public class AutoCompleteRestController { @Autowired AutoCompleteService autoCompleteService; @GetMapping("/search") public ResponseEntity<String> doAutoComplete(@RequestParam("q") final String input) { List<String> strings = autoCompleteService.doAutoComplete(input); ObjectMapper mapper = new ObjectMapper(); String resp = ""; try { resp = mapper.writeValueAsString(strings); } catch (JsonProcessingException e) { } return new ResponseEntity<String>(resp, HttpStatus.OK); } }

Creating Controller Class

As the project is Spring Boot MVC then we have to have some index page so that when client hits the base URL, the application will display the home page.

Therefore we need below Controller class to redirect to the home page.

package com.roytuts.spring.mvc.autocomplete.input.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HomeController { @RequestMapping("/") public String home() { return "index"; } }

Creating View File

Now create below index.jsp file and put it under src/main/webapp/views/ directory.

We will show input field in this page and in this input field when a user types character we will show list of results coming from a source – database, external API etc.

We are using AJAX technique with jQuery library to call the REST controller’s method at endpoint.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Spring Boot MVC Auto-Complete using jQuery</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/static/css/style.css"> <style> .ui-autocomplete-loading { background: white url("/static/images/ui-anim_basic_16x16.gif") right center no-repeat; } </style> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function() { $("#searchBox").autocomplete({ source : function(request, response) { $.ajax({ url : "http://localhost:8080/search", dataType : "json", data : { q : request.term }, success : function(data) { //alert(data); console.log(data); response(data); } }); }, minLength : 2 }); }); </script> </head> <body> <div style="width: 600px; margin: auto;"> <h3>Spring Boot MVC Auto-Complete using jQuery</h3> <fieldset> <legend>Search Here</legend> <p> <input type="text" name="search" id="searchBox" style="width: 560px; margin: auto;" /> </p> </fieldset> </div> </body>

Here we have used jQuery and jQuery’s UI library to get the benefits of Autocomplete functionality.

To get the desired result you have to type consecutively minimum two characters.

Applying Style

Add some style using below style.css file that should be kept under src/main/webapp/static/css/ directory.

/* Theme Name: jqueryui-com Template: jquery */ a, .title { color: #b24926; } #content a:hover { color: #333; } #banner-secondary p.intro { padding: 0; float: left; width: 50%; } #banner-secondary .download-box { border: 1px solid #aaa; background: #333; background: -webkit-linear-gradient(left, #333 0%, #444 100%); background: linear-gradient(to right, #333 0%, #444 100%); float: right; width: 40%; text-align: center; font-size: 20px; padding: 10px; border-radius: 5px; box-shadow: 0 0 8px rgba(0, 0, 0, 0.8); } #banner-secondary .download-box h2 { color: #71d1ff; font-size: 26px; } #banner-secondary .download-box .button { float: none; display: block; margin-top: 15px; } #banner-secondary .download-box p { margin: 15px 0 5px; } #banner-secondary .download-option { width: 45%; float: left; font-size: 16px; } #banner-secondary .download-legacy { float: right; } #banner-secondary .download-option span { display: block; font-size: 14px; color: #71d1ff; } #content .dev-links { float: right; width: 30%; margin: -15px -25px .5em 1em; padding: 1em; border: 1px solid #666; border-width: 0 0 1px 1px; border-radius: 0 0 0 5px; box-shadow: -2px 2px 10px -2px #666; } #content .dev-links ul { margin: 0; } #content .dev-links li { padding: 0; margin: .25em 0 .25em 1em; background-image: none; } .demo-list { float: right; width: 25%; } .demo-list h2 { font-weight: normal; margin-bottom: 0; } #content .demo-list ul { width: 100%; border-top: 1px solid #ccc; margin: 0; } #content .demo-list li { border-bottom: 1px solid #ccc; margin: 0; padding: 0; background: #eee; } #content .demo-list .active { background: #fff; } #content .demo-list a { text-decoration: none; display: block; font-weight: bold; font-size: 13px; color: #3f3f3f; text-shadow: 1px 1px #fff; padding: 2% 4%; } .demo-frame { width: 70%; height: 420px; } .view-source a { cursor: pointer; } .view-source>div { overflow: hidden; display: none; } @media all and (max-width: 600px) { #banner-secondary p.intro, #banner-secondary .download-box { float: none; width: auto; } #banner-secondary .download-box { overflow: auto; } } @media only screen and (max-width: 480px) { #content .dev-links { width: 55%; margin: -15px -29px .5em 1em; overflow: hidden; } }

Adding Image

Add rotating image to Autocomplete input box. Download the image and put it under src/main/webapp/static/images/ directory.

Creating Application Properties

Here is the src/amin/resources/application.properties file that resolves the view resolver for JSP pages.

#view resolver spring.mvc.view.prefix=/views/ spring.mvc.view.suffix=.jsp

Creating Main Class

For Spring Boot application main class is enough to deploy the application into embedded Tomcat server.

package com.roytuts.spring.mvc.autocomplete.input; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages = "com.roytuts.spring.mvc.autocomplete.input") public class SpringMvcAutocompleteInputApp { public static void main(String[] args) { SpringApplication.run(SpringMvcAutocompleteInputApp.class, args); } }

Testing the Application

Once you run the above main class, your application will be deployed into the server at port 8080.

You can hit the URL http://localhost:8080/ in the browser and try to type something.

One example is shown in the below image.

You may also like to read the similar tutorial on Codeigniter jQuery .

Source Code

download source code

Thanks for reading.