Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Servlet: Best Way to Determine if request is AJAX

What is the best way to determine whether a GET or POST request coming into a java servlet is an AJAX request? The method I've come across so far in my search is to strip the information out of the header with

"XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

Are there other ways to handle this? It seems like relying on the header is not a terribly robust solution.

like image 740
AJBradley Avatar asked Sep 19 '14 05:09

AJBradley


People also ask

How do I know if request is AJAX request?

mypage. php: if(isset($_GET['ajax'])) { //this is an ajax request, process data here. }

How do I know if AJAX request is successful?

You can check when exactly it returns "success" : // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { ... // If not modified if ( status === 304 ) { statusText = "notmodified"; ... // If we have data } else { try { ...

What is the difference between AJAX request and HTTP request?

AJAX stands for asynchronous javascript and XML so if you are using javascript to load data after the browser request has finished you are doing AJAX. REST on the other hand stands for Representational State Transfer which as Stefan Billet pointed out uses HTTP requests to transfer data.

Is AJAX request GET or POST?

GET vs POST in AJAX callsUnless you are sending sensitive data to the server or calling scripts which are processing data on the server it is more common to use GET for AJAX calls. This is because when using XMLHttpRequest browsers implement POST as a two-step process (sending the headers first and then the data).


1 Answers

Following HTML document uses jQuery.post() method to send an asynchronous AJAX request to Servlet:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>click demo</title>
  <style>
  body {font-family: verdana;margin:20px; font-size: 14px;}
  div.container {border: 1px solid black;
    background-color: #f0ffff;padding:10px;width:460px;
  }
  p.result {color:red;font-weight:bold;}
  h3 {color:blue;}
  </style>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<script>
$(document).ready(function() {
    $("#myAsyncBtn").click(function() {
        $.post(
                "async",
                function( data ) {
                $(".result").html(data);
                }
        );
    }); 
});
</script>
<body>
<div class="container">
<h3>Ajax Request Detection using Java</h3>
<p>Click this button to make a Asynchronous Request 
    <button id="myAsyncBtn"> Click Here</button>
</p>
<p>Now click a Link to make a synchronous request 
    <a href="async">Sync Call</a>
</p>
<p class="result"></p>
</div>
</body>
</html>

A Controller which needs to deal with both type of request can use request.getHeader() method to detect the Request type. Developer can use x-requested-with header parameter to get the request type. In case of Ajax Request request.getHeader('x-requested-with') will return XMLHttpRequest as String else return null.

package org.techzoo.async;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/async")
public class AsyncServlet extends HttpServlet {

    public AsyncServlet() {
        super();
    }

    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) 
        throws ServletException, IOException {

        String headerName = request.getHeader("x-requested-with");

        if(null == headerName){
            PrintWriter out = response.getWriter();
            String html = "<h3>Clinet send a Synchronous request</h3>" +
                "<p><a href=\"index.jsp\">Go Back</a> to main page</p>";
            out.write(html);
        }
        else {
            ServletOutputStream out = response.getOutputStream();
            out.print("Ajax Request Detected");
            out.flush();
        }
    }

}
like image 186
Mustkeem Mansuri Avatar answered Oct 04 '22 09:10

Mustkeem Mansuri