[英]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.