簡體   English   中英

檢測ajax請求調用

[英]Detect ajax request call

(我是Java世界的新手)

我正在學習dropwizard,並且我想創建根據請求類型(是否為ajax)返回視圖(html)或json的資源

例:

@Path("/")
public class ServerResource {

    @GET
    @Produces(MediaType.TEXT_HTML)
    public MainView getMainView() {
        return new MainView("Test hello world");
    }
}

如果請求是AJAX,如何在相同的Path JSON響應中添加到此資源?

更新1.我創建了以下內容:

@Path("/")
public class ServerResource {

    @GET
    @Consumes(MediaType.TEXT_HTML)
    @Produces(MediaType.TEXT_HTML)
    public MainView getMainView(@HeaderParam("X-Requested-With") String requestType) {
        return new MainView("hello world test!");
    }

    @GET
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public List<String> getJsonMainView() {
        List<String> list = new ArrayList<String>();
        for (Integer i = 0; i < 10; i++) {
            list.add(i, "test" + i.toString());
        }
        return list;
    }
}

看起來這按預期工作,但是我知道這不是一個好習慣。

Ajax請求通常(並非總是)具有X-Requested-With:XMLHttpRequest請求標頭。 請參閱如何區分Ajax請求和普通的Http請求?

以下代碼尚未經過測試。

@Path("/")
public class ServerResource {
    @GET
    @Produces({MediaType.TEXT_HTML, MediaType.APPLICATION_JSON})
    public MainView getMainView(@HeaderParam("X-Requested-With") String requestType) {
        if(requestType != null && requestType.equals("XMLHttpRequest")) {
           //The request is AJAX
        } else {
           //The request is not AJAX
        }
        ...
    }
}

AJAX請求和僅請求服務器之間沒有區別。 只是GET,POST,PUT,DELETE或HEAD。 如果要分離輸出,則應通過添加查詢參數或使用另一個URL或添加一些標頭,然后在處理方法內部進行解析,在請求本身中以某種方式對其進行標記。

希望有道理。

暫無
暫無

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

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