Java – Detect ajax request call

dropwizard, java, jax-rs

(I'm new to java world)

I'm learning dropwizard and I want to create resource that is returning view (html) or json depending on request type (ajax or not)


@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?

I created something like this:

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

Best Solution

Ajax requests USUALLY have (not always) X-Requested-With: XMLHttpRequest request header. See How to differentiate Ajax requests from normal Http requests?

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