Home > OS >  How to access API controller from Spring in HTML
How to access API controller from Spring in HTML

Time:06-26

This is my controller:

@GetMapping("/getRandomWildSwimming")
public List<WildSwimming> getRandomWildSwimming() {
    return wildSwimmingService.getRandomWildSwimming();
}

How I can access it with HTML? I'm confused, I saw some tutorials where I set return index.html for example, but I'm returning here actually service that show me collection data from Mongo in JSON when I send request for example: http://localhost:8080/wildswimming/getRandomWildSwimming page show me one collection from mongo in JSON format, how I can show that via html and stylize it a bit?

CodePudding user response:

If you want to use this approach, you need a client. For example, you can use JS or PHP for it.

Then you need to create HTML pages, add scripts (using JS or PHP) to send requests, get responses and show it to user.

This looks like: user opens page -> client sends request to your spring controller -> spring controller returns response -> client gets and shows it to user.

OR

You can use Spring MVC if you do not how to launch client server.

CodePudding user response:

You will need to add a dependency to your project so that spring knows how to convert an object into json. If you're using maven, add com.fasterxml.jackson.core:jackson-databind to your pom file.

Then, add the @ResponseBody annotation to the getRandomWildSwimming method, so it looks like this...

@GetMapping("/getRandomWildSwimming")
public @ResponseBody List<WildSwimming> getRandomWildSwimming() {
    wildSwimmingService.getRandomWildSwimming();
}

This will make the controller respond with json when it is called in a web browser.

Assuming that it returns JSON that looks like this...

[{"rating":89},{"rating":24},{"rating":68}]

You can using the $.get function from the jquery library to do something like this...

<!DOCTYPE html>
<html>
    <head>
        <title>Test</title>
        <script src="resources/jquery-3.6.0.min.js"></script>
    </head>
    <body>
        <h1>Wild Swimming Records</h1>
        <ul id="canvas">
        </ul>
        
        <script type="text/javascript">
            $(document).ready(function(){
                $.get("./getRandomWildSwimming", function(data) {
                    console.log("JSON: "   JSON.stringify(data));
                    $.each(data, function(index, value) {
                        $("#canvas").append("<li>"   value.rating   "</li>");
                    });
                });
            });
        </script>
    </body>
</html>

This should result in a page that looks something like this...

Wild Swimming Records

    - 89
    - 24
    - 68

The console.log line will print the JSON returned to the console for you to examine.

  • Related