use code inside ajax success
method
var json = jQuery.parseJSON(data);
console.log("success", json);
and in servlet write code
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(<Object_to_be_passed>);
out.write(element.toString());
and also you have to import two packages com.google.gson.Gson
and com.google.gson.JsonElement
in servlet
if you pass a model class in json use the variable names to access data in ajax
like if you have a model class Address
having fields name
and phone
you should write code in ajax is json.name
& json.phone
Example
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="jquery-3.2.1.js"></script>
<title>Ajax Sample</title>
</head>
<body>
<div>
<textarea id="text"></textarea>
<button onclick="load()">Load Now</button>
</div>
<script>
function load() {
$.ajax({
url: "GetData",
type: 'POST',
success: function (data, textStatus, jqXHR) {
alert(data);
var json = jQuery.parseJSON(data);
document.getElementById("text").innerHTML = 'Name: ' + json.name + ' & Phone:' + json.phone;
}
});
}
</script>
</body>
</html>
Index.java servlet
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Chirag
*/
public class Index extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter writer = response.getWriter()) {
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(new Address("Chirag", "123456"));
writer.write(element.toString());
}
}
class Address {
private final String name;
private final String phone;
public Address(String name, String phone) {
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
@Override
public String getServletInfo() {
return "Get Ajax Result";
}
}
I used the deployment descriptor to create the servlet address GetData.
following the snip part of web.xml
<servlet>
<servlet-name>Index</servlet-name>
<servlet-class>Index</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Index</servlet-name>
<url-pattern>/GetData</url-pattern>
</servlet-mapping>
This code place the value to textarea in html and also make a alert of passed data from servlet to jsp.
Hope it helps..:)