简体   繁体   中英

Spring boot Request Mapping with Schedule

I'm newbie on spring boot. I'm already implement some request mappings with successfully output in json.

localhost:8080/gJson

 {
    ad: "Windows 10",
    mimari: "amd64",
    versiyon: "10.0",
    diskSize: 918,
    freediskSize: 614,
    cores: 8,
    usablediskSize: 614
    }

And My Controller here

@EnableAutoConfiguration
@Controller      
public class GreetingController {

     @RequestMapping(value = "/gJson", produces=MediaType.APPLICATION_JSON_VALUE)
     public @ResponseBody  MyPojo gJson(){
         ...
     }
}

And now, I need ... example when I'm going to this link > localhost:8080/GetInfo getting json from localhost:8080/gJson but every "X" seconds.

Thanks For Helping.

How is /GetInfo being served? Is it just a standard HTML page? If so you can code a Javascript element that has a setInterval() to make an XMLHttpRequest to the /gJson endpoint. There are a number of other ways to do it depending on what libraries you want to use to have browser to server communications.

* Update * Sample project: https://github.com/ShawnTuatara/stackoverflow-38890600

Main aspect that allows the refresh is the HTML page at src/main/resources/static/GetInfo.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>GetInfo</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>

</body>
<script type="text/javascript">
    $(function() {
        window.setInterval(function() {
            $.ajax({
                url : "/gJson"
            }).done(function(data, status, jqXHR) {
                $("body").text(jqXHR.responseText);
            });
        }, 10000);
    });
</script>
</html>

The controller is straightforward as outlined in the question.

@EnableAutoConfiguration
@RestController
public class GreetingController {
    @GetMapping(value = "/gJson", produces = MediaType.APPLICATION_JSON_VALUE)
    public MyPojo gJson() {
        return new MyPojo("Windows 10", System.currentTimeMillis());
    }
}

Finally the MyPojo is just a simple two field class.

public class MyPojo {
    private String ad;
    private long timestamp;

    public MyPojo(String ad, long timestamp) {
        this.ad = ad;
        this.timestamp = timestamp;
    }

    public String getAd() {
        return ad;
    }

    public void setAd(String ad) {
        this.ad = ad;
    }

    public long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(long timestamp) {
        this.timestamp = timestamp;
    }
}

I included the timestamp so that you can see the time refreshing every 10 seconds on the web page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM