简体   繁体   English

检测ajax请求调用

[英]Detect ajax request call

(I'm new to java world) (我是Java世界的新手)

I'm learning dropwizard and I want to create resource that is returning view (html) or json depending on request type (ajax or not) 我正在学习dropwizard,并且我想创建根据请求类型(是否为ajax)返回视图(html)或json的资源

Example: 例:

@Path("/")
public class ServerResource {

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

How to add to this resource at the same Path JSON response if request is AJAX? 如果请求是AJAX,如何在相同的Path JSON响应中添加到此资源?

UPDATE 1. I created something like this: 更新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;
    }
}

Looks like this is working as expected, but I know that is not a good practice. 看起来这按预期工作,但是我知道这不是一个好习惯。

Ajax requests USUALLY have (not always) X-Requested-With: XMLHttpRequest request header. Ajax请求通常(并非总是)具有X-Requested-With:XMLHttpRequest请求标头。 See How to differentiate Ajax requests from normal Http requests? 请参阅如何区分Ajax请求和普通的Http请求?

The following code hasn't been tested. 以下代码尚未经过测试。

@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
        }
        ...
    }
}

There is no difference between AJAX-request and just request for the server. AJAX请求和仅请求服务器之间没有区别。 It's just GET, POST, PUT, DELETE or HEAD. 只是GET,POST,PUT,DELETE或HEAD。 If you want to separate output you should mark it somehow in the request itself by adding query parameter or use another URL or adding some header and then parsing in inside your processing method. 如果要分离输出,则应通过添加查询参数或使用另一个URL或添加一些标头,然后在处理方法内部进行解析,在请求本身中以某种方式对其进行标记。

Hope that makes sense. 希望有道理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM