Skip to content Skip to sidebar Skip to footer

How To Use REST Api In JSP?

I have a textbox in JSP file. When user enters the postcode in the textbox it should go the url of the api and bring the necessary data as required. REST Api is ready and everythi

Solution 1:

If I understand the question properly, you have a text box in a view(which is being rendered using a JSP template). As soon as the user enters the postal code in the text box, you want to make an request to a server and fetch data.

This can be done using an AJAX call with javascript in the frontend (I'm using jquery here to simplify things). Put this in between tags in the JSP:

BASE_URL = "http://server_url/" // Your REST interface URL goes here

$(".postcode-input button").click(function () {
    var postcode = $(this).parents(".postcode-input")
        .children("input").val();
    // First do some basic validation of the postcode like
    // correct format etc.
    if (!validatePostcode(postcode)) {
        alert("Invalid Postal Code, please try again");
        return false;
    }
    var finalUrl = BASE_URL += "?postcode=" + postcode; 
    $.ajax({
        url: finalUrl,
        cache: false,
        success: function (html) {
            // Parse the recieved data here.
            console.log(html);
        }
    });
});

Use an input element like this:

<div class="postcode-input">
    <input type="text" maxlength="6">
    <button type="submit"></button>
</div>

The above code sends a GET request, you can similarly send a POST request. Have a look at the jQuery AJAX docs for more info.


Post a Comment for "How To Use REST Api In JSP?"