Explanation:
When we
click the button , request will come to JQuery $.ajax method,and then execuete
ServletClass ,ServletClass returns Json data as output,this output will display
inside div.
Here JSONObject json = new JSONObject(); is used to create JSON data.
Maven pom.xml
<dependencies>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
</dependencies>
Welcome.html
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#SubmitButton").click(function() {
$.ajax({
url:'sc',
type:'GET',
dataType: 'json',
success: function(data) {
$("#main").html("<p>Name:"+data.name+",Company:"+data.company+"</p>");
},
error: function(e) {
alert(e.status);
}
});
});
});
</script>
</head>
<body>
<div id="main">
<button id="SubmitButton">CallServlet</button>
</div>
</body>
</html>
ServletClass.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class ServletClass extends HttpServlet {
@Override
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
PrintWriter out=response.getWriter();
JSONObject json = new JSONObject();
try {
json.put("name","java");
json.put("company","oracle");
} catch (JSONException e) {
e.printStackTrace();
}
out.print(json);
}
}
Web.xml
<web-app>
<servlet>
<servlet-name>sc</servlet-name>
<servlet-class>ServletClass</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>sc</servlet-name>
<url-pattern>/sc</url-pattern>
</servlet-mapping>
</web-app>
hello sir , i like ur post .....Please post a program.....for ....sending json object to servlet and getting back using jquery ajax...
ReplyDeletek sure
ReplyDeletehello sir , i like ur post .....Please post a program.....for ....sending json object to servlet and getting back using jquery ajax.
ReplyDeletehttp://javabyramakrishna.blogspot.in/2013/12/jqueryajaxjsonmaven-example-with-input.html
ReplyDelete
ReplyDeleteAnd indeed, I’m just always astounded concerning the remarkable things served by you. Some four facts on this page are undeniably the most effective I’ve had.
Advanced C C++ Training in Chennai |Best C C++ Training course in Chennai
Advanced linux Training in Chennai | Best linux Training in Chennai
Advanced Unix Training in Chennai | Best Unix Training in Chennai
Advanced uipath training in chennai | Best uipath training in chennai
Advanced Rprogramming Training in Chennai | Best Rprogramming Training in Chennai