如何在JSP中使用REST

如何在JSP中使用REST

本文介绍了如何在JSP中使用REST Api?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 JSP 文件中有一个文本框.当用户在文本框中输入邮政编码时,应转到api的网址,并根据需要携带必要的数据.

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 已准备就绪,一切就绪.我只想知道如何将请求发送到url.

REST Api is ready and everything is set. I just want to know how should i send my request to the url.

推荐答案

如果我正确理解了这个问题,则您在视图中有一个文本框(正在使用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.

这篇关于如何在JSP中使用REST Api?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 16:44