These days Builders the world over makes use of JavaScript frameworks like jQuery UI, ExtJs, Dojo to develop Wealthy Web Functions (RIA). This JavaScript framework makes use of Asynchronous calls (Ajax Request) to get knowledge from server in Json format.
On server aspect we’ve loads of frameworks like spring, Struts which might deal with Asynchronous and synchronous request.
In response to a Asynchronous request, Controller must ship response in Json format. For synchronous request, controller can delegate response to a View.
Following HTML doc makes use of jQuery.publish() methodology to ship a Asynchronous Ajax request to Servlet.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<!doctype html>
<html lang=“en”>
<head>
<meta charset=“utf-8”>
<title>click on demo</title>
physique {font-family: verdana;margin:20px; font-size: 14px;}
div.container {border: 1px stable black;
background-color: #f0ffff;padding:10px;width:460px;
}
p.consequence {colour:pink;font-weight:daring;}
h3 {colour:blue;}
</head>
<physique>
<div class=“container”>
<h3>Ajax Request Detection utilizing Java</h3>
<p>Click on this button to make a Asynchronous Request
<button id=“myAsyncBtn”> Click on Right here</button>
</p>
<p>Now click on a Hyperlink to make a synchronous request
<a href=“async”>Sync Name</a>
</p>
<p class=“consequence”></p>
</div>
</physique>
</html>
|
A Controller which must take care of each sort of request can use request.getHeader()
methodology to detect the Request sort. Developer can use x-requested-with
header parameter to get the request sort. In case of Ajax Request request.getHeader('x-requested-with')
will return XMLHttpRequest as string else return null.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
bundle 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() {
tremendous();
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String heardeName = request.getHeader(“x-requested-with”);
if(null == heardeName){
PrintWriter out = response.getWriter();
String html = “
Clinet ship a Synchronous request“ +“
Go Back to most important web page “ ;out.write(html);
}
else {
ServletOutputStream out = response.getOutputStream();
out.print(“Ajax Request Detected”);
out.flush();
}
}
}
|
Output will look much like as follows.
Supply techzoo.org