How to Call a REST API Using jQuery AJAX in Spring Boot
1. Introduction
This is an in-depth article related to the JQuery AJAX Call to Spring Boot based Rest Service. Spring Boot framework has features to build applications. Spring Boot has features related to building rest services and unit testing the application.
2. Spring Boot Rest API – JQuery AJAX Call
2.1 Prerequisites
Java 8 or 9 is required on the Linux, windows, or Mac operating system. Maven 3.6.1 is required for building the spring and hibernate application.
2.2 Download
You can download Java 8 can be downloaded from the Oracle web site . Apache Maven 3.6.1 can be downloaded fromApache site. Spring framework’s latest releases are available from the spring website.
2.3 Setup
You can set the environment variables for JAVA_HOME and PATH. They can be set as shown below:
Setup For Java
JAVA_HOME=”/jboss/jdk1.8.0_73″ export JAVA_HOME PATH=$JAVA_HOME/bin:$PATH export PATH
The environment variables for maven are set as below:
Environment Setup for Maven
JAVA_HOME=”/jboss/jdk1.8.0_73″ export M2_HOME=/users/bhagvan.kommadi/Desktop/apache-maven-3.6.1 export M2=$M2_HOME/bin export PATH=$M2:$PATH
2.4 Building the application
2.4.1 Spring
You can start building Spring applications using the Spring Boot framework. Spring Boot has a minimal configuration of Spring. Spring Boot has features related to security, tracing, application health management, and runtime support for web servers. Spring configuration is done through maven pom.xml. The XML configuration is shown below:
Spring Configuration
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.springframework</groupId> <artifactId>spring-helloworld</artifactId> <version>0.1.0</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.4.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <properties> <java.version>1.8</java.version> </properties> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
You can create a HelloWorldController
class as the web controller. The class is annotated using @RestController
. Rest Controller is used to handle requests in Spring Model View Controller framework. Annotation @RequestMapping
is used to annotate the index()
method. The code for the HelloWorldController
class is shown below:
HelloWorld Controller
package helloworld; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; @RestController public class HelloWorldController { @RequestMapping("/") public String index() { return "Hello World\n"; } }
HelloWorldApp
is created as the Spring Boot web application. When the application starts, beans, and settings are wired up dynamically. They are applied to the application context. The code for HelloWorldApp
class is shown below:
HelloWorld App
package helloworld; import java.util.Arrays; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class HelloWorldApp { public static void main(String[] args) { ApplicationContext ctx = SpringApplication.run(HelloWorldApp.class, args); System.out.println("Inspecting the beans"); String[] beans = ctx.getBeanDefinitionNames(); Arrays.sort(beans); for (String name : beans) { System.out.println("Bean Name" +name); } } }
Maven is used for building the application. The command below builds the application.
Maven Build Command
mvn package
The output of the executed command is shown below.
The jar file spring-helloworld-0.1.0.jar is created. The following command is used for executing the jar file.
Run Command
java -jar target/spring-helloworld-0.1.0.jar
The output of the executed command is shown below.
The curl command is invoked on the command line for the execution of the index method. The method returns a string “Hello World” text. @RestController aggregates the two annotations @Controller and @ResponseBody. This results in returning data. The output is shown below.
2.5 Rest Web Service -Calling with JQuery Ajax
Let us start building a Spring Boot based Rest Service first. You can create a SpringBootApplication
as shown below:
SpringBootRestAjaxApplication
package org.javacodegeeks.jqueryrest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringBootRestAjaxApplication { public static void main(String[] args) { SpringApplication.run(SpringBootRestAjaxApplication.class, args); } }
You can create a Customer
class which hascustomerId
, name
, and orders
attributes. The code is presented below:
Customer Class
package org.javacodegeeks.jqueryrest.model; import java.util.ArrayList; import java.util.List; import org.springframework.hateoas.ResourceSupport; public class Customer extends ResourceSupport { private Long customerId; private String name; private List orders; public Customer() { } public Customer(Long customerId, String name) { this.customerId = customerId; this.name = name; orders = new ArrayList(); } public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getOrders() { return orders; } public void setOrders(List orders) { this.orders = orders; } }
You can create a CustomerRepository
class as shown below. The customer API maps to the rest api path /customers
.
Customer Repository
package org.javacodegeeks.jqueryrest.repo; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Repository; import org.javacodegeeks.jqueryrest.model.Customer; @Repository public class CustomerRepository { private final List customers = new ArrayList(); public CustomerRepository() { this.customers.add(new Customer(1L, "Thomas Smith")); this.customers.add(new Customer(2L, "Jack Smith")); this.customers.add(new Customer(3L, "George Kay")); this.customers.add(new Customer(4L, "Joanne Smith")); this.customers.add(new Customer(5L, "Seanne Kane")); } public List findAll() { return this.customers; } public Customer findOne(Long id) { for (Customer customer : this.customers) { if (customer.getCustomerId().equals(id)) { return customer; } } return null; } }
Maven pom.xml is created to build the application and for execution. The xml configuration is attached below:
Maven xml
<?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.javasampleapproach</groupId> <artifactId>spring-boot-ajax-jquery</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>SpringBootAjaxRest</name> <description>Rest with Ajax</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.4.RELEASE</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-hateoas</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
Maven is used for building the application. The command below builds the application.
Maven Build Command
mvn package
The output of the executed command is shown below.
Build – Output
apples-MacBook-Air:spring_rest_jquery bhagvan.kommadi$ mvn package [INFO] Scanning for projects... [INFO] [INFO] ---------------------- [INFO] Building SpringBootAjaxRest 0.0.1-SNAPSHOT [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ spring-boot-ajax-jquery --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 1 resource [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ spring-boot-ajax-jquery --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ spring-boot-ajax-jquery --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory /Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/src/test/resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ spring-boot-ajax-jquery --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to /Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/test-classes [INFO] [INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ spring-boot-ajax-jquery --- [INFO] Surefire report directory: /Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/surefire-reports ------------------------------------------------------- T E S T S ------------------------------------------------------- 02:40:52.309 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.350 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate] 02:40:52.370 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)] 02:40:52.426 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper] 02:40:52.457 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests], using SpringBootContextLoader 02:40:52.466 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: class path resource [org/javacodegeeks/jqueryrest/SpringBootAjaxHateoasApplicationTests-context.xml] does not exist 02:40:52.467 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: class path resource [org/javacodegeeks/jqueryrest/SpringBootAjaxHateoasApplicationTestsContext.groovy] does not exist 02:40:52.468 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}. 02:40:52.470 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: SpringBootAjaxHateoasApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration. 02:40:52.544 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.571 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence 02:40:52.572 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence 02:40:52.573 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment] 02:40:52.596 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [org/javacodegeeks/jqueryrest/] to resources [URL [file:/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/test-classes/org/javacodegeeks/jqueryrest/], URL [file:/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/classes/org/javacodegeeks/jqueryrest/]] 02:40:52.597 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/test-classes/org/javacodegeeks/jqueryrest] 02:40:52.598 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/test-classes/org/javacodegeeks/jqueryrest] for files matching pattern [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/test-classes/org/javacodegeeks/jqueryrest/*.class] 02:40:52.603 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/classes/org/javacodegeeks/jqueryrest] 02:40:52.605 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/classes/org/javacodegeeks/jqueryrest] for files matching pattern [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/classes/org/javacodegeeks/jqueryrest/*.class] 02:40:52.607 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved location pattern [classpath*:org/javacodegeeks/jqueryrest/*.class] to resources [file [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/test-classes/org/javacodegeeks/jqueryrest/SpringBootAjaxHateoasApplicationTests.class], file [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/classes/org/javacodegeeks/jqueryrest/ServletInitializer.class], file [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/classes/org/javacodegeeks/jqueryrest/SpringBootRestAjaxApplication.class]] 02:40:52.708 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/classes/org/javacodegeeks/jqueryrest/SpringBootRestAjaxApplication.class] 02:40:52.710 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration org.javacodegeeks.jqueryrest.SpringBootRestAjaxApplication for test class org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests 02:40:52.718 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: using defaults. 02:40:52.722 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] 02:40:52.747 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource] 02:40:52.749 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute] 02:40:52.749 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@7dc222ae, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@aecb35a, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@5fcd892a, org.springframework.test.context.support.DirtiesContextTestExecutionListener@8b87145, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@6483f5ae, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@b9afc07, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@382db087, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@73d4cc9e, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@80169cf, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@5427c60c] 02:40:52.754 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.757 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] Running org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests 02:40:52.762 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.763 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate] 02:40:52.764 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)] 02:40:52.765 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper] 02:40:52.766 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests], using SpringBootContextLoader 02:40:52.767 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: class path resource [org/javacodegeeks/jqueryrest/SpringBootAjaxHateoasApplicationTests-context.xml] does not exist 02:40:52.767 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: class path resource [org/javacodegeeks/jqueryrest/SpringBootAjaxHateoasApplicationTestsContext.groovy] does not exist 02:40:52.767 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}. 02:40:52.768 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: SpringBootAjaxHateoasApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration. 02:40:52.777 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.778 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence 02:40:52.780 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence 02:40:52.782 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment] 02:40:52.784 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration org.javacodegeeks.jqueryrest.SpringBootRestAjaxApplication for test class org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests 02:40:52.794 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests]: using defaults. 02:40:52.799 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] 02:40:52.810 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource] 02:40:52.811 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Could not instantiate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute] 02:40:52.811 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@2bbaf4f0, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@11c20519, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@70beb599, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4e41089d, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@32a068d1, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@33cb5951, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@365c30cc, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@701fc37a, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@4148db48, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@282003e1] 02:40:52.812 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.813 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.814 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.815 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.828 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@25359ed8 testClass = SpringBootAjaxHateoasApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@21a947fe testClass = SpringBootAjaxHateoasApplicationTests, locations = '{}', classes = '{class org.javacodegeeks.jqueryrest.SpringBootRestAjaxApplication}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.SpringBootTestContextCustomizer@617faa95, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@2038ae61, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@544fe44c, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@3b0143d3], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null]. 02:40:52.831 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.831 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests] 02:40:52.972 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence 02:40:52.972 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence 02:40:52.973 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment] 02:40:52.976 [main] DEBUG org.springframework.core.env.MutablePropertySources - Adding [inline] PropertySource with highest search precedence 02:40:52.987 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1} 02:40:52.987 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [Inlined Test Properties] PropertySource with highest search precedence . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.4.RELEASE) 2020-11-18 02:40:54.014 INFO 34910 --- [ main] .j.SpringBootAjaxHateoasApplicationTests : Starting SpringBootAjaxHateoasApplicationTests on apples-MacBook-Air.local with PID 34910 (started by bhagvan.kommadi in /Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery) 2020-11-18 02:40:54.015 INFO 34910 --- [ main] .j.SpringBootAjaxHateoasApplicationTests : No active profile set, falling back to default profiles: default 2020-11-18 02:40:54.155 INFO 34910 --- [ main] o.s.w.c.s.GenericWebApplicationContext : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@55740540: startup date [Wed Nov 18 02:40:54 IST 2020]; root of context hierarchy 2020-11-18 02:40:57.850 INFO 34910 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@55740540: startup date [Wed Nov 18 02:40:54 IST 2020]; root of context hierarchy 2020-11-18 02:40:58.050 INFO 34910 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/getcustomer/{id}],methods=[GET]}" onto public org.javacodegeeks.jqueryrest.message.Response org.javacodegeeks.jqueryrest.controller.CustomerController.getResource(java.lang.Long) 2020-11-18 02:40:58.052 INFO 34910 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{id}/orders]}" onto public java.util.List org.javacodegeeks.jqueryrest.controller.CustomerController.getOrdersForCustomer(java.lang.Long) 2020-11-18 02:40:58.053 INFO 34910 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{id}]}" onto public org.javacodegeeks.jqueryrest.model.Customer org.javacodegeeks.jqueryrest.controller.CustomerController.getCustomerById(java.lang.Long) 2020-11-18 02:40:58.054 INFO 34910 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/postorder],methods=[POST]}" onto public org.javacodegeeks.jqueryrest.message.Response org.javacodegeeks.jqueryrest.controller.CustomerController.postCustomer(org.javacodegeeks.jqueryrest.message.Request) 2020-11-18 02:40:58.055 INFO 34910 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto org.springframework.web.servlet.ModelAndView org.javacodegeeks.jqueryrest.controller.WebController.home(org.springframework.web.servlet.ModelAndView) 2020-11-18 02:40:58.060 INFO 34910 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2020-11-18 02:40:58.061 INFO 34910 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2020-11-18 02:40:58.178 INFO 34910 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2020-11-18 02:40:58.178 INFO 34910 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2020-11-18 02:40:58.281 INFO 34910 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2020-11-18 02:40:58.695 INFO 34910 --- [ main] .j.SpringBootAjaxHateoasApplicationTests : Started SpringBootAjaxHateoasApplicationTests in 5.684 seconds (JVM running for 7.192) Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 6.034 sec - in org.javacodegeeks.jqueryrest.SpringBootAjaxHateoasApplicationTests 2020-11-18 02:40:58.800 INFO 34910 --- [ Thread-2] o.s.w.c.s.GenericWebApplicationContext : Closing org.springframework.web.context.support.GenericWebApplicationContext@55740540: startup date [Wed Nov 18 02:40:54 IST 2020]; root of context hierarchy Results : Tests run: 1, Failures: 0, Errors: 0, Skipped: 0 [INFO] [INFO] --- maven-war-plugin:2.6:war (default-war) @ spring-boot-ajax-jquery --- [INFO] Packaging webapp [INFO] Assembling webapp [spring-boot-ajax-jquery] in [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/spring-boot-ajax-jquery-0.0.1-SNAPSHOT] [INFO] Processing war project [INFO] Copying webapp resources [/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/src/main/webapp] [INFO] Webapp assembled in [295 msecs] [INFO] Building war: /Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/spring-boot-ajax-jquery-0.0.1-SNAPSHOT.war [INFO] [INFO] --- spring-boot-maven-plugin:1.5.4.RELEASE:repackage (default) @ spring-boot-ajax-jquery --- [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 16.690 s [INFO] Finished at: 2020-11-18T02:41:03+05:30 [INFO] ------------------------------------------------------------------------
Maven is used for executing the application. The command below runs the spring boot application.
Maven Run Command
mvn spring-boot:run
The output of the executed command is shown below.
Execution – Output
apples-MacBook-Air:spring_rest_jquery bhagvan.kommadi$ mvn spring-boot:run [INFO] Scanning for projects... [INFO] [INFO] ---------------------- [INFO] Building SpringBootAjaxRest 0.0.1-SNAPSHOT [INFO] --------------------------------[ war ]--------------------------------- [INFO] [INFO] >>> spring-boot-maven-plugin:1.5.4.RELEASE:run (default-cli) > test-compile @ spring-boot-ajax-jquery >>> [INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ spring-boot-ajax-jquery --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] Copying 1 resource [INFO] Copying 0 resource [INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ spring-boot-ajax-jquery --- [INFO] Nothing to compile - all classes are up to date [INFO] [INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ spring-boot-ajax-jquery --- [INFO] Using 'UTF-8' encoding to copy filtered resources. [INFO] skip non existing resourceDirectory /Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/src/test/resources [INFO] [INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ spring-boot-ajax-jquery --- [INFO] Changes detected - recompiling the module! [INFO] Compiling 1 source file to /Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/test-classes [INFO] [INFO] <<< spring-boot-maven-plugin:1.5.4.RELEASE:run (default-cli) < test-compile @ spring-boot-ajax-jquery <<< [INFO] [INFO] [INFO] --- spring-boot-maven-plugin:1.5.4.RELEASE:run (default-cli) @ spring-boot-ajax-jquery --- . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.4.RELEASE) 2020-11-18 02:44:31.482 INFO 35143 --- [ main] o.j.j.SpringBootRestAjaxApplication : Starting SpringBootRestAjaxApplication on apples-MacBook-Air.local with PID 35143 (/Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery/target/classes started by bhagvan.kommadi in /Users/bhagvan.kommadi/Desktop/JavacodeGeeks/Code/spring_rest_jquery) 2020-11-18 02:44:31.500 INFO 35143 --- [ main] o.j.j.SpringBootRestAjaxApplication : No active profile set, falling back to default profiles: default 2020-11-18 02:44:31.911 INFO 35143 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@36e503f4: startup date [Wed Nov 18 02:44:31 IST 2020]; root of context hierarchy 2020-11-18 02:44:35.960 INFO 35143 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http) 2020-11-18 02:44:35.996 INFO 35143 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2020-11-18 02:44:36.013 INFO 35143 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15 2020-11-18 02:44:36.389 INFO 35143 --- [ost-startStop-1] org.apache.jasper.servlet.TldScanner : At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time. 2020-11-18 02:44:36.397 INFO 35143 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2020-11-18 02:44:36.398 INFO 35143 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4497 ms 2020-11-18 02:44:36.779 INFO 35143 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2020-11-18 02:44:36.787 INFO 35143 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2020-11-18 02:44:36.788 INFO 35143 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2020-11-18 02:44:36.789 INFO 35143 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2020-11-18 02:44:36.789 INFO 35143 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2020-11-18 02:44:37.859 INFO 35143 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@36e503f4: startup date [Wed Nov 18 02:44:31 IST 2020]; root of context hierarchy 2020-11-18 02:44:38.119 INFO 35143 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/getcustomer/{id}],methods=[GET]}" onto public org.javacodegeeks.jqueryrest.message.Response org.javacodegeeks.jqueryrest.controller.CustomerController.getResource(java.lang.Long) 2020-11-18 02:44:38.123 INFO 35143 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{id}/orders]}" onto public java.util.List org.javacodegeeks.jqueryrest.controller.CustomerController.getOrdersForCustomer(java.lang.Long) 2020-11-18 02:44:38.123 INFO 35143 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/{id}]}" onto public org.javacodegeeks.jqueryrest.model.Customer org.javacodegeeks.jqueryrest.controller.CustomerController.getCustomerById(java.lang.Long) 2020-11-18 02:44:38.124 INFO 35143 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/postorder],methods=[POST]}" onto public org.javacodegeeks.jqueryrest.message.Response org.javacodegeeks.jqueryrest.controller.CustomerController.postCustomer(org.javacodegeeks.jqueryrest.message.Request) 2020-11-18 02:44:38.124 INFO 35143 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto org.springframework.web.servlet.ModelAndView org.javacodegeeks.jqueryrest.controller.WebController.home(org.springframework.web.servlet.ModelAndView) 2020-11-18 02:44:38.130 INFO 35143 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2020-11-18 02:44:38.131 INFO 35143 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2020-11-18 02:44:38.216 INFO 35143 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2020-11-18 02:44:38.218 INFO 35143 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2020-11-18 02:44:38.443 INFO 35143 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2020-11-18 02:44:39.142 INFO 35143 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2020-11-18 02:44:39.368 INFO 35143 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2020-11-18 02:44:39.378 INFO 35143 --- [ main] o.j.j.SpringBootRestAjaxApplication : Started SpringBootRestAjaxApplication in 9.18 seconds (JVM running for 20.364)
The web application can be accessed at : http://localhost:8080. The screenshot below shows the landing page.
Customer can be found by entering the customer id as the input. The output is shown in the screen below:
The order can be added to the existing customer as shown in the picture below:
Orders for existing customer can be accessed by clicking on the link for all Orders. The output is shown in the picture below.
3. Download the Source Code
You can download the full source code of this example here: How to Call a REST API Using jQuery AJAX in Spring Boot