且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在JSP中使用REST Api?

更新时间:2022-03-17 00:37:02

如果我正确理解了这个问题,则您在视图中有一个文本框(正在使用JSP模板呈现).用户在文本框中输入邮政编码后,就想向服务器发出请求并获取数据.

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.

这可以通过在前端使用javascript的AJAX调用来完成(我在这里使用jquery来简化事情).将其放在JSP中的标记之间:

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

使用这样的输入元素:

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

上面的代码发送一个GET请求,您可以类似地发送一个POST请求.请查看 jQuery AJAX文档以获取更多信息.

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.