Overview

In this tutorial, we show you how to create a Spring Boot Web Project and use the JQuery’s Ajax function to send to the data in JSON format.

Spring Boot Ajax Jquery Example

Prerequisites

  • Eclipse Oxygen and Install Spring Tool Suite for Eclipse IDE
  • Spring Boot v2.1.0.BUILD-SNAPSHOT
  • spring-boot-starter-jdbc
  • spring-boot-starter-web
  • spring-boot-devtools
  • javax.servlet jstl
  • org.webjars bootstrap 4.0.0
  • tomcat-embed-jasper
  • mysql-connector-java 5.1.46
  • com.fasterxml.jackson.core jackson-core
  • com.fasterxml.jackson.core jackson-databind
  • com.fasterxml.jackson.core jackson-annotations
  • spring-boot-configuration-processor
  • Java 1.8+

Database and tables in MySQL Databases

CREATE DATABASE `jack_rutorial` /*!40100 DEFAULT CHARACTER SET utf8 */;

DROP TABLE IF EXISTS `jack_rutorial`.`country`;
CREATE TABLE  `jack_rutorial`.`country` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL default '',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `jack_rutorial`.`city`;
CREATE TABLE  `jack_rutorial`.`city` (
  `id` int(11) NOT NULL auto_increment,
  `name` varchar(100) NOT NULL default '',
  `country_id` int(11) NOT NULL default '0',
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

Project Directory Structure

The following screenshot shows final structure of the project.
Project Directory Structure

Creating a Spring Boot Project with Eclipse STS

Launch Eclipse IDE. Go to File -> New -> Other... Select Spring Starter Project under Spring Boot category then click Next as shown below
Spring Starter Project

In the next screen, you enter the content as shown below then click Next
new spring starter project

In the next step, you choose Spring Boot Version is 2.1.0 (SNAPSHOT) and choose the Web + DevTools + JDBC + MySQL, then click Finish.
new spring starter project

Project Dependencies

The updated pom.xml file will have the following code.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.jackrutorial</groupId>
 <artifactId>SpringBootAjaxJqueryExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>SpringBootAjaxJqueryExample</name>
 <description>Demo project for Spring Boot</description>

 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.0.BUILD-SNAPSHOT</version>
  <relativePath/> <!-- lookup parent from repository -->
 </parent>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  <java.version>1.8</java.version>
 </properties>

 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-jdbc</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>jstl</artifactId>
  </dependency>
  <dependency>
   <groupId>org.webjars</groupId>
   <artifactId>bootstrap</artifactId>
   <version>4.0.0</version>
  </dependency>
  <dependency>
   <groupId>org.apache.tomcat.embed</groupId>
   <artifactId>tomcat-embed-jasper</artifactId>
   <scope>provided</scope>
  </dependency>
  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.46</version>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-core</artifactId>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
  </dependency>
  <dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-annotations</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-configuration-processor</artifactId>
   <optional>true</optional>
  </dependency>
 </dependencies>

 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>

 <repositories>
  <repository>
   <id>spring-snapshots</id>
   <name>Spring Snapshots</name>
   <url>https://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </repository>
  <repository>
   <id>spring-milestones</id>
   <name>Spring Milestones</name>
   <url>https://repo.spring.io/milestone</url>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </repository>
 </repositories>

 <pluginRepositories>
  <pluginRepository>
   <id>spring-snapshots</id>
   <name>Spring Snapshots</name>
   <url>https://repo.spring.io/snapshot</url>
   <snapshots>
    <enabled>true</enabled>
   </snapshots>
  </pluginRepository>
  <pluginRepository>
   <id>spring-milestones</id>
   <name>Spring Milestones</name>
   <url>https://repo.spring.io/milestone</url>
   <snapshots>
    <enabled>false</enabled>
   </snapshots>
  </pluginRepository>
 </pluginRepositories>


</project>

application.properties

Open src/main/resources/application.properties file and add the following properties.
spring.datasource.url=jdbc:mysql://localhost:3306/jack_rutorial
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

server.port=8080
server.servlet.context-path=/

SpringBootAjaxJqueryExampleApplication.java

package com.jackrutorial;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringBootAjaxJqueryExampleApplication {

 public static void main(String[] args) {
  SpringApplication.run(SpringBootAjaxJqueryExampleApplication.class, args);
 }
}

HomeController

HomeController.java
package com.jackrutorial.controller;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jackrutorial.model.City;
import com.jackrutorial.model.CountryCriteria;
import com.jackrutorial.model.Country;
import com.jackrutorial.model.CustomForm;
import com.jackrutorial.service.CityService;
import com.jackrutorial.service.CountryService;

@Controller
@RequestMapping("/")
public class HomeController {

 @Autowired
 private CityService cityService;
 
 @Autowired
 private CountryService countryService;
 
 @RequestMapping(value = { "/", "" }, method = RequestMethod.GET)
 public ModelAndView home() {
  ModelAndView model = new ModelAndView();
  
  CustomForm customForm = new CustomForm();
  List<Country> countries = countryService.getCountriesList();
  List<City> cities = new ArrayList<City>();
  
  model.addObject("countries", countries);
  model.addObject("cities", cities);
  model.addObject("customForm", customForm);
  
  model.setViewName("home");
  return model;
 }
 
 @RequestMapping(value = "/loadCityByCountry", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
 public @ResponseBody List<City> loadCityByCountry(@RequestBody CountryCriteria countryCriteria) {
  List<City> cities = cityService.getCitiesByCountry(countryCriteria.getCountryId());
  
  return cities;
 }
}

DAO Model

CityDao.java
package com.jackrutorial.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.jackrutorial.model.City;

@Transactional
@Repository
public class CityDao {

 @Autowired
 private JdbcTemplate jdbcTemplate;

 public List<City> getCitiesByCountry(int countryId) {
  String sql = "select * from city where country_id = ?";

  RowMapper<City> rowMapper = new CityRowMapper();
  List<City> list = jdbcTemplate.query(sql, rowMapper, countryId);

  return list;
 }

 class CityRowMapper implements RowMapper<City> {

  @Override
  public City mapRow(ResultSet rs, int rowNum) throws SQLException {
   City city = new City();
   city.setId(rs.getInt("id"));
   city.setName(rs.getString("name"));
   return city;
  }
 }
}

CountryDao.java
package com.jackrutorial.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.jackrutorial.model.Country;

@Transactional
@Repository
public class CountryDao {

 @Autowired
 private JdbcTemplate jdbcTemplate;

 public List<Country> getCountriesList() {
  String sql = "select * from country";

  RowMapper<Country> rowMapper = new CountryRowMapper();
  List<Country> list = jdbcTemplate.query(sql, rowMapper);

  return list;
 }

 class CountryRowMapper implements RowMapper<Country> {

  @Override
  public Country mapRow(ResultSet rs, int rowNum) throws SQLException {
   Country country = new Country();
   country.setId(rs.getInt("id"));
   country.setName(rs.getString("name"));
   return country;
  }
 }
}

Model

City.java
package com.jackrutorial.model;

public class City {
 private int id;
 private String name;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
}

Country.java
package com.jackrutorial.model;

public class Country {
 private int id;
 private String name;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
}

CountryCriteria.java
package com.jackrutorial.model;

public class CountryCriteria {
 private int countryId;

 public int getCountryId() {
  return countryId;
 }

 public void setCountryId(int countryId) {
  this.countryId = countryId;
 }
}

CustomForm.java
package com.jackrutorial.model;

public class CustomForm {
 private int countryId;
 private int cityId;
 
 public int getCountryId() {
  return countryId;
 }
 public void setCountryId(int countryId) {
  this.countryId = countryId;
 }
 public int getCityId() {
  return cityId;
 }
 public void setCityId(int cityId) {
  this.cityId = cityId;
 }
}

Service Layer

CityService.java
package com.jackrutorial.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jackrutorial.dao.CityDao;
import com.jackrutorial.model.City;

@Service
public class CityService {
 
 @Autowired
 private CityDao cityDao;

 public List<City> getCitiesByCountry(int countryId) {
  return cityDao.getCitiesByCountry(countryId);
 }
}

CountryService.java
package com.jackrutorial.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jackrutorial.dao.CountryDao;
import com.jackrutorial.model.Country;

@Service
public class CountryService {

 @Autowired
 private CountryDao countryDao;

 public List<Country> getCountriesList() {
  return countryDao.getCountriesList();
 }
}

View Layer

Create home.jsp file under src\main\webapp\WEB-INF\jsp\ folder and write the following code in it.
<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Home</title>
 <link href="webjars/bootstrap/4.0.0/css/bootstrap.min.css"
  rel="stylesheet" />
 <script src="webjars/bootstrap/4.0.0/js/bootstrap.min.js"></script>
 <script src="webjars/jquery/3.0.0/jquery.min.js"></script>
</head>
<body>
 <div class="container">
  <form:form modelAttribute="customForm" method="post" action="">
   <div class="form-group">
    Country
    <form:select id="countryId" path="countryId" cssClass="form-control">
     <form:option value="0" label="" />
     <form:options items="${countries}" itemValue="id" itemLabel="name" />
    </form:select>
   </div>
   <div class="form-group">
    City
    <form:select id="cityId" path="cityId" cssClass="form-control">
     <form:option value="0" label="" />
     <form:options items="${cities}" itemValue="id" itemLabel="name" />
    </form:select>
   </div>
  </form:form>

  <script type="text/javascript">
   $(document).ready(function() {
    $("#countryId").change(function() {
      var countryId = $(this).find(":selected").val();
      var json = {
       "countryId" : countryId
      };
 
      $.ajax({
       type : "POST",
       contentType : "application/json",
       url : "/loadCityByCountry",
       data : JSON.stringify(json),
       dataType : 'json',
       cache : false,
       timeout : 600000,
       success : function(data) {
        var html = '';
        var len = data.length;
        html += '<option value="0"></option>';
        for (var i = 0; i < len; i++) {
         html += '<option value="' + data[i].id + '">'
           + data[i].name
           + '</option>';
        }
        html += '</option>';
        $('#cityId').html(html);
       },
       error : function(e) {
        alert(e);
       }
      });
    });
   });
  </script>
 </div>
</body>
</html>

Run Spring Boot Application

  • Right click to the Project and follow the below steps:
  • select Run As -> Maven clean.
  • select Run As -> Maven install.
  • select Run As -> Spring Boot App.
View console output in eclipse, you will see following output:
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::  (v2.1.0.BUILD-SNAPSHOT)

  INFO 9548 --- [  restartedMain] j.SpringBootAjaxJqueryExampleApplication : No active profile set, falling back to default profiles: default
  INFO 9548 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
  INFO 9548 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
  INFO 9548 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/9.0.10
  INFO 9548 --- [  restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
 DEBUG 9548 --- [  restartedMain] o.s.web.context.ContextLoader            : Published root WebApplicationContext as ServletContext attribute with name [org.springframework.web.context.WebApplicationContext.ROOT]
  INFO 9548 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1416 ms
  INFO 9548 --- [  restartedMain] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
  INFO 9548 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
  INFO 9548 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
  INFO 9548 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'formContentFilter' to: [/*]
  INFO 9548 --- [  restartedMain] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
  INFO 9548 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService  'applicationTaskExecutor'
 DEBUG 9548 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [/**/favicon.ico] in 'faviconHandlerMapping'
 DEBUG 9548 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerAdapter : ControllerAdvice beans: 0 @ModelAttribute, 0 @InitBinder, 1 RequestBodyAdvice, 1, ResponseBodyAdvice
 DEBUG 9548 --- [  restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : 4 mappings in 'requestMappingHandlerMapping'
 DEBUG 9548 --- [  restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping  : Patterns [/webjars/**, /**] in 'resourceHandlerMapping'
 DEBUG 9548 --- [  restartedMain] .m.m.a.ExceptionHandlerExceptionResolver : ControllerAdvice beans: 0 @ExceptionHandler, 1 ResponseBodyAdvice
  INFO 9548 --- [  restartedMain] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
  INFO 9548 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
  INFO 9548 --- [  restartedMain] j.SpringBootAjaxJqueryExampleApplication : Started SpringBootAjaxJqueryExampleApplication in 2.3 seconds (JVM running for 3.098)

Demo Spring Boot Web Application

Type the following URLs in browser's address bar to open user page.
http://localhost:8080/
Demo

Latest
Next Post

post written by: