PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   14-10-2021

Ajax App

Create a new Spring Web project.
 
package com.example.ajaxapp;

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);
    }

}
... 3 lines
 
The jQuery module consumes the REST service. The index.html page loads the client into the user's browser.
 
<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>
... 31 lines
 
The REST controller displays the response as JSON.
 
package com.example.ajaxapp;

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; 
    }
}
... 33 lines
 
Test and run the application.
 
./mvnw spring-boot:run

http://localhost:8080/

#15:56:30

Questions    
Lambda Expressions

        A B C D E F
🔔
1/1