Java Spring Mvc Ajax Example
On the Eclipse, create a Spring MVC project in Spring Boot
Enter Project Information:
- Name: LearnSpringMVCWithRealApps
- Group: com.demo
- Artifact: LearnSpringMVCWithRealApps
- Description: Learn Spring MVC with Real Apps
- Package: com.demo
Select the technologies and libraries to be used:
- Web
Click Next button to show Site Information for project
Click Finish button to finish create Spring MVC project
<?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.demo</groupId> <artifactId>LearnSpringMVCWithRealApps</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>LearnSpringMVCWithRealApps</name> <description>Learn Spring MVC with Real Apps</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.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> <!-- Spring MVC --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- JSTL tag lib --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- Tomcat for JSP rendering --> <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> spring.mvc.view.prefix = /WEB-INF/views/ spring.mvc.view.suffix = .jsp spring.mvc.static-path-pattern=/resources/** server.port=9596 Create new folder named js in src\main\resources\static folder. Copy jquery file to this folder
Create new package, named com.demo.entities. In this package, create entities class as below:
Create new java class, named Product.java
package com.demo.entities; import java.io.Serializable; public class Product implements Serializable { private String id; private String name; private double price; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Product(String id, String name, double price) { this.id = id; this.name = name; this.price = price; } public Product() { } } Create new package, named com.demo.models. In this package, create ProductModel class as below:
package com.demo.models; import java.util.ArrayList; import java.util.List; import com.demo.entities.Product; public class ProductModel { public Product find() { return new Product("p01", "name 1", 20); } public List<Product> findAll() { List<Product> products = new ArrayList<Product>(); products.add(new Product("p01", "name 1", 20)); products.add(new Product("p02", "name 2", 21)); products.add(new Product("p03", "name 3", 22)); return products; } } Create new package named com.demo.controllers. In this package, create controllers as below:
Create new java class, named DemoController.java
package com.demo.controllers; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; @Controller @RequestMapping("demo") public class DemoController { @RequestMapping(method = RequestMethod.GET) public String index() { return "demo/index"; } } In com.demo.controllers package, create new Spring Rest API controller give data for ajax as below:
Create new java class, named AjaxRestController.java as below:
package com.demo.controllers; import java.util.List; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MimeTypeUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.demo.entities.Product; import com.demo.models.ProductModel; @RestController @RequestMapping("api/ajaxrest") public class AjaxRestController { @RequestMapping(value = "demo1", method = RequestMethod.GET, produces = { MimeTypeUtils.TEXT_PLAIN_VALUE }) public ResponseEntity<String> demo1() { try { ResponseEntity<String> responseEntity = new ResponseEntity<String>("Demo 1", HttpStatus.OK); return responseEntity; } catch (Exception e) { return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } } @RequestMapping(value = "demo2/{fullName}", method = RequestMethod.GET, produces = { MimeTypeUtils.TEXT_PLAIN_VALUE }) public ResponseEntity<String> demo2(@PathVariable("fullName") String fullName) { try { ResponseEntity<String> responseEntity = new ResponseEntity<String>("Hi " + fullName, HttpStatus.OK); return responseEntity; } catch (Exception e) { return new ResponseEntity<String>(HttpStatus.BAD_REQUEST); } } @RequestMapping(value = "demo3", method = RequestMethod.GET, produces = { MimeTypeUtils.APPLICATION_JSON_VALUE }) public ResponseEntity<Product> demo3() { try { ProductModel productModel = new ProductModel(); ResponseEntity<Product> responseEntity = new ResponseEntity<Product>(productModel.find(), HttpStatus.OK); return responseEntity; } catch (Exception e) { return new ResponseEntity<Product>(HttpStatus.BAD_REQUEST); } } @RequestMapping(value = "demo4", method = RequestMethod.GET, produces = { MimeTypeUtils.APPLICATION_JSON_VALUE }) public ResponseEntity<List<Product>> demo4() { try { ProductModel productModel = new ProductModel(); ResponseEntity<List<Product>> responseEntity = new ResponseEntity<List<Product>>(productModel.findAll(), HttpStatus.OK); return responseEntity; } catch (Exception e) { return new ResponseEntity<List<Product>>(HttpStatus.BAD_REQUEST); } } } Create new folders with path webapp\WEB-INF\views in src\main. In views folder, create JSP Pages as below:
Create new folder named demo. Create new jsp file named index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Ajax in Spring MVC</title> <script src="${pageContext.request.contextPath }/resources/js/jquery-1.6.2.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#buttonDemo1').click(function() { $.ajax({ type : 'GET', url : '/api/ajaxrest/demo1', success : function(result) { $('#result1').text(result); } }); }); $('#buttonDemo2').click(function() { var fullName = $('#fullName').val(); $.ajax({ type : 'GET', url : '/api/ajaxrest/demo2/' + fullName, success : function(result) { $('#result2').text(result); } }); }); $('#buttonDemo3').click(function() { $.ajax({ type : 'GET', url : '/api/ajaxrest/demo3', dataType : 'json', contentType : 'application/json', success : function(result) { var s = 'Id: ' + result.id; s += '<br/>Name: ' + result.name; s += '<br/>Price: ' + result.price; $('#result3').html(s); } }); }); $('#buttonDemo4').click(function() { $.ajax({ type : 'GET', url : '/api/ajaxrest/demo4', dataType : 'json', contentType : 'application/json', success : function(result) { var s = ''; for (var i = 0; i < result.length; i++) { s += '<br/>Id: ' + result[i].id; s += '<br/>Name: ' + result[i].name; s += '<br/>Price: ' + result[i].price; s += '<br/>======================'; } $('#result4').html(s); } }); }); }); </script> </head> <body> <fieldset> <legend>Demo 1</legend> <input type="button" value="Demo 1" id="buttonDemo1" /> <br/> <span id="result1"></span> </fieldset> <fieldset> <legend>Demo 2</legend> Full Name <input type="text" id="fullName" /> <br/> <input type="button" value="Demo 2" id="buttonDemo2" /> <br/> <span id="result2"></span> </fieldset> <fieldset> <legend>Demo 3</legend> <input type="button" value="Demo 3" id="buttonDemo3" /> <br/> <span id="result3"></span> </fieldset> <fieldset> <legend>Demo 4</legend> <input type="button" value="Demo 4" id="buttonDemo4" /> <br/> <div id="result4"></div> </fieldset> </body> </html>
Select LearnSpringMVCWithRealAppsApplication.java file in com.demo package, right click and select Run As/Spring Boot App menu
Access index method in demo controller with following url: http://localhost:9596/demo
Output
Click Demo 1 button to call Demo1 method in AjaxRestController controller with ajax
Output
Click Demo 2 button to call Demo2 method in AjaxRestController controller with ajax
Output
Click Demo 3 button to call Demo3 method in AjaxRestController controller with ajax
Output
Click Demo 4 button to call Demo4 method in AjaxRestController controller with ajax
Output
I recommend you refer to the books below to learn more about the knowledge in this article:
- Spring MVC Beginners Guide – Second Edition
- Spring MVC Cookbook
- Spring MVC Blueprints
- Building RESTful Web Services with Spring 5 – Second Edition: Leverage the power of Spring 5.0, Java SE 9, and Spring Boot 2.0
- Spring Boot in Action
- Pro Spring Boot
- jQuery in Action
- JavaScript & jQuery: The Missing Manual
- Murach's JavaScript and jQuery (3rd Edition)
rodriguezhantimpok.blogspot.com
Source: https://learningprogramming.net/java/spring-mvc/ajax-in-spring-mvc/
0 Response to "Java Spring Mvc Ajax Example"
Post a Comment