minte9
LearnRemember



Ajax App

Create a new Spring Web project.
 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
 
/**
 * Spring Boot Web App (Ajax)
 */

package com.minte9.ajax;

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

@SpringBootApplication
public class App {

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

}

Client

The index.html loads into the user's browser the client that consume REST service.
 
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        function crono() {
            setTimeout(function() {
                $.ajax({
                    url: "http://localhost:8080/getcurrtime"
                }).then(function(data){
                    $("#crono").html(data.time);
                });

                crono();
            }, 1000);
        }
        crono();
    });

    function start() {
        $.ajax({ 
            url: "http://localhost:8080/start"
        });
    }

    function stop() {
        $.ajax({
            url: "http://localhost:8080/stop"
        });
    }
</script>
</head>
<body>
    Get current time (with Ajax):  

    <a href='javascript: start();'>Start</a> | 
    <a href='javascript: stop();'>Stop</a>

    <div id='crono'></div>
</body>
</html>

Service

The REST controller displays the response as JSON.
 
package com.minte9.ajax;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class CronoController {

    private Boolean start = true;
    private SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
    private String lastTime = dateFormat.format(new Date());

    @GetMapping("/getcurrtime")
    public Crono crono() {
        if (start) {
            String time = dateFormat.format(new Date());
            lastTime = time;
        }        
        return new Crono(lastTime);
    }

    @GetMapping("/start")
    public void start() { 
        this.start = true; 
    }

    @GetMapping("/stop")
    public void stop() { 
        this.start = false; 
    }
}

/**
 * Data representation class (to return as JSON)
 */
class Crono {
    private final String time;

    public Crono(String time) { 
        this.time = time; 
    }

    public String getTime() { 
        return time; 
    }
}

Run

Test and run the application.
 
mvn spring-boot:run

http://localhost:8080/

// Get current time (with Ajax): Start | Stop
// 13:21:55



  Last update: 183 days ago