簡體   English   中英

如何使用RestEasy REST.Request訪問表單參數?

[英]How to access form parameters using RestEasy REST.Request?

我的表格如下:

<form id="form1" name="form1">
    <fieldset>
        <ol>
            <li>
                <label>Project:</label>
                <select id="project" name="project" required></select>
            </li>
        </ol>
        <input type="button" onclick="request();">
    </fieldset>
</form>

我在輸入按鈕的onclick事件上創建了request()函數。 我將輸入類型更改為button,因為我不想重新加載頁面。

request函數使用RestEasy REST.Request類創建自定義的rest請求。 我在REST.Request對象上使用了setEntity,但是我不知道如何在服務器端訪問該信息。

下面是請求函數:

request: function() {
    var myRequest = new REST.Request();
    var form1 = document.forms["form1"];

    var projectTxt = form1.elements["project"].value;

    myRequest.setURI(REST.apiURL + "/request/item");
    myRequest.setMethod("GET");
    myRequest.setEntity({project:projectTxt});

    myRequest.execute(function(status, request, entity) {
        if (status === 200 && request.readyState === 4) {
            // entity is always null
            sessionStorage.setItem("project", entity);
            console.log("entity=" + entity);
        }
    });
},

在上面的代碼中,傳遞給myRequest.execute()的函數中的實體始終為null。

這是Java代碼:

@Path("item")
@GET
public String itemFormatRequest(@FormParam("project") String project)
{
    // project is always null
    return "blarg!!! project is " + project;
}

在上面的代碼中,project為null。 我試過使用@QueryParam ,但也不起作用。 我只是在錯誤地使用它,還是我缺少其他東西? 通過在JavaScript和Java代碼中將@GET更改為@POST,我做了很多試驗和錯誤。 還嘗試在Java代碼中添加@Consumes(“ application / x-www-form-urlencoded”) ,但此方法無效。

我要做的唯一一件事就是將查詢參數添加到REST.request對象中,如下所示:

myRequest.addQueryParameter("project", projectTxt);

然后,我可以使用(@QueryParam(“ project”)String project)檢索此內容。

謝謝!

您正在使用GET作為請求方法。 GET旨在檢索數據,因此您不會傳遞實體。 如果只想讀取所選項目的數據,則可以將GET@QueryParam結合使用。 但是,那么您就不會傳遞實體。 只需添加queryParameter即可:

myRequest.addQueryParameter('project', projectTxt);

如果要將數據傳遞到服務器,則應將請求的方法更改為POST (在客戶端和服務器代碼中)。 另外,您的實體是JSON,但是您的服務器代碼需要@FormParam REST.Request對象具有addForm和add addFormParameter方法。 因此,以下其中一項也應起作用(未試用):

myRequest.addForm('form1', form1);

要么

myRequest.addFormParameter('project', projectTxt);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM