(我是 Java 世界的新手)
我正在学习 dropwizard,我想创建根据请求类型(是否为 ajax)返回 View (html) 或 json 的资源
例子:
@Path("/")
public class ServerResource {
@GET
@Produces(MediaType.TEXT_HTML)
public MainView getMainView() {
return new MainView("Test hello world");
}
}
如果请求是 AJAX,如何在同一路径 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 请求 header 。参见 How to differentiate Ajax requests from normal Http requests?
以下代码未经测试。
@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
}
...
}
}
关于java - 检测ajax请求调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19298693/