Sending json data from Ajax to Servlet in java? [duplicate] - java

This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 5 years ago.
I am totally confused about this strange bug that I am facing in my code. So, I am trying to send data from my jQuery script to a servlet with AJAX. Now, here is the strange part that I have noticed, when I set the contentType to application/json, I notice that all the values in server side are null but the moment I remove it, I get the right data in my servlet. Now, I would like to know why am I facing such a bug?
Here is my jsp -
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var apiname=$("#apiname").val();
var apiendpoint=$("#apiendpoint").val();
var apiversion=$("#apiversion").val();
var source=$("#source").val();
$.ajax({
type: "POST",
url: "HomeServlet",
contentType: "application/json",
dataType:'json',
data:{"apiname":apiname,"apiendpoint":apiendpoint,"apiversion":apiversion,"source":source},
success: function(status){
console.log("Entered",status);
},
error:function(error){
console.log("error",error);
},
});
});
</script>
Servlet code -
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<String, String> job = new LinkedHashMap<>();
//doGet(request, response);
JSONArray jArray = new JSONArray();
// response.setContentType("text/html");
PrintWriter out= response.getWriter();
String n = request.getParameter("apiname");
String p = request.getParameter("apiendpoint");
String e = request.getParameter("apiversion");
String c = request.getParameter("source");
String status ="091";
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
System.out.println("Connection created");
PreparedStatement ps= ((java.sql.Connection) con).prepareStatement("insert into apiinfo(apiname,apiendpoint,apiversion,accessibility) values (?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3, e);
ps.setString(4,c);
ps.execute();
out.close();
status ="000";
con.close();
System.out.println("Inserted");
}
catch(Exception e1)
{
System.out.println(e1);
}
job.put("status",status);
jArray.put(job);
System.out.println(jArray.toString());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jArray.toString());
}

That is because when you sent the ajax request as this:
$.ajax({
type: "POST",
url: "HomeServlet",
contentType: "application/json",
dataType:'json',
data:{"apiname":apiname,"apiendpoint":apiendpoint,"apiversion":apiversion,"source":source},
success: function(status){
console.log("Entered",status);
},
error:function(error){
console.log("error",error);
}
});
you send the data as normal POST parameters (not Stringnyfied) and you tell your servlet that this is a JSON string (Which is not!!!)
So to actually get this to work you have to either Stringnify the data you send to the servlet or to remove the contentType: "application/json" and 'dataType:'json' so you can treat the data as normal POST data.

Related

AJAX not receiving response from servlet

I have an AJAX making a POST to a servlet. Servlet does some computation and returns a response. AJAX success function reads the response and does certain things.
AJAX CALL
$.ajax( {
type: "POST",
url: "/bin/path/to/Servlet",
data: $(this).serialize(),
dataType: "html",
success: function(responseValue) {
if(responseValue == '200') {
// Do something
}else {
console.log("it is not 200");
}
},
error: trialForm.trialError
}).done(function(status) {
$(trialForm.submitButton).show();
$(trialForm.loader).hide();
});
}
SERVLET
protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
response.setContentType("text/html");
URL url = new URL("www.apriurl.com");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type","application/json");
conn.setRequestProperty("Authorization","XXXXZZZZ " + strSig);
conn.setRequestProperty("Accept","application/json");
conn.setRequestProperty("ZZZZZ",clientID);
OutputStream os = conn.getOutputStream();
os.write(inputParameters.getBytes());
os.flush();
System.out.println(conn.getResponseCode());
response.getWriter().write(conn.getResponseCode());
}
responseValue is a variable used in teh java class.
It has the right value. I see the value being print in log file after sys out executed
The response is just a garbled question mark (?). I console logged it. I am guessing it has to do something with the data type. I tried a few other types but couldn;t figure out. Any help is appreicated.
This is doing a write (int) rather than a write (String)
so if you do write(200) it is sending the ascii value of 200
try sending 200 as a String
as
response.getWriter().write(String.valueOf (conn.getResponseCode()));
see https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#write(int)
public void write(int c)
Writes a single character.

Cannot display response of HTML servlet in Ajax and qTip2

I am trying to display text (or html) that is received from a servlet response in a qTip2 tooltip within a jsp. I have almost everything working and have verified with Firebug that the servlet is being invoked and text is being returned, but when I try to use the 'html' (or data) variable in my ajax call, I get an error: HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy.
I've tried displaying the html in a JavaScript alert, and this is what displays: [object XMLDocument].
Here is the sequence of events:
1.User clicks on a section of HTML text, which has a link defined that points to the servlet and passes parameters
2.The ajax invokes the servlet which does some processing and returns text or html
3.The text is displayed as a tooltip with qTip2
How can I properly handle the response from the servlet and manipulate the text that is received from it?
Ajax call:
$(".ajax_link").click(function(e) {
e.preventDefault();
var $this = $(this);
var link = $(this).attr('href'); //Gets link url
$.ajax({
type: "GET",
url: link,
cache: false,
}).done(function(html) {
$this.qtip({
content: {
text: html //<--this causes error above
//text: "<table><tr><th>Team</th></tr></table>" <--this works fine
}
});
$this.qtip('toggle', true);
});
});
Servlet Code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("inside doGet");
String var1 = "<table><tr><th>Team</th></tr></table>";
//var1 = request.getParameter("var1");
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.print(var1);
out.flush();
out.close();
}
pass dataType as html in ajax request
i.e.
$.ajax({
type: "GET",
url: link,
cache: false,
dataType : "html"
}

Interacting the JSP page with the Servlet doGet() method through AJAX call

Am doing the JAVA code found below, to call the servlet doGet() method from JSP page through AJAX call.
Here is my AJAX call..
Am sending the clicked text captured by ng-click of Angular js as a querystring to Servlet's doGet() method .
In my JSP file,
$scope.requestFunc = function (clickData) {
var urlquerystring = clickData;
jQuery.ajax({
type: 'GET',
url: "/Charts/testExecution/"+"?"+ urlquerystring,
dataType: 'html',
success: function(respnsedata)
{
window.location.assign(respnsedata);
}
});
}
In my Servlet's doGet() method,
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.err.println("In TestExecutionESO servlet..");
String teamnametextfield= req.getParameter("teamnametextfield");
System.out.println("Teamname is.."+teamnametextfield);
try {
dcmanager = DataCollectorManager.getInstance();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String selectedteam= req.getQueryString();
String testexeclistofobjectsjson = null;
if(selectedteam!=null)
{
String release=selectedteam.replace("%20"," ").toString();
testexecutionobjlist = dcmanager.getRallyDcMgr().gettestExecutionobjlist(release);
}
Gson gson = new Gson();
testexeclistofobjectsjson = gson.toJson(testexecutionobjlist);
System.out.println(testexecutionobjlist);
System.out.println(testexeclistofobjectsjson);
req.getSession().setAttribute("testexeclistofobjectsjson", testexeclistofobjectsjson);
resp.sendRedirect("TestExecutionESO.jsp");
}
Am getting the querystring perfectly..After the processing, I will do SetAttribute() and redirect to next JSP page..
Redirect is not working..
Here is my error code,
Failed to load resource: net::ERR_TOO_MANY_REDIRECTS..
http://10.112.81.95:9000/Charts/testExecution/TestExecutionESO.jsp.... Failed to load resource: net::ERR_TOO_MANY_REDIRECTS
Please help me resolve the problem..
how to redirect to next JSP page by doing the setAttribute() .??
resp.sendRedirect("TestExecutionESO.jsp");
This is the culprit in your code. when you call sendRedirect(), it will issue a 302 response containing the location-header, URI of the new resource. When the browser sees this header, it will issue a new request for that new URI.
All of this works well for a synchronous request but in case of AJAX calls, we use an XMLHttpRequest, which will not handle redirects so well.
I'd suggest you to use a RequestDispatcher instead to forward to the JSP like this
RequestDispatcher rd = req.getRequestDispatcher("path-to-ur-jsp");
rd.forward(req,res);

Passing custom objects from servlet to Jquery

i have a servlet my goal is to return a customer object from the process request, where i can then access this object in my jquery. Does anyone know how i can go about doing this?
e.g. myObject.getMethod()
Servlet Code:
Customer loginResult;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here. You may use following sample code. */
//request.setAttribute("customerFirstName", loginResult.getFirstName()); //String Value
//request.setAttribute("customerID", loginResult.getCustomerID()); //IntegerValue
out.println(loginResult);
} finally {
out.close();
}
}
JSP CODE:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "get",
data: dataf,
success: function(data) {
alert(data);
}
});
return false;
});
});
</script>
Can someone please assist me in resolving this issue, thank you for your help in advance.
Since you want to handle an ajax request using a Servlet, the best bet you have is writing the data of your custom object into the response. The easier way I found to accomplish this is using JSON. There are lot of libraries that handles JSON conversion from objects to Strings and vice versa, I recommend using Jackson. This is how your code should look like.
Servlet code:
import com.fasterxml.jackson.databind.ObjectMapper;
#WebServlet("/loginServlet") //assuming you're using Servlet 3.0
public class YourServlet extends HttpServlet {
//Jackson class that handles JSON marshalling
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
//login operation should be handled in POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Customer loginResult = ...; //process data and get the loginResult instance
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
//marshalling the data of your loginResult in JSON format
String json = OBJECT_MAPPER.writeValueAsString(loginResult);
response.getWriter().write(json);
}
}
Javascript code:
<script type="text/javascript">
$().ready(function() {
$('#submit').click(function() {
var dataf = 'email=' + $('#email').val()
+ '&password=' + $('#password').val();
$.ajax({
url: "http://localhost:8080/RetailerGui/loginServlet",
type: "post", //login action MUST be post, NEVER a get
data: dataf,
success: function(data) {
//shows the relevant data of your login result object in json format
alert(data);
//parsing your data into a JavaScript variable
var loginResult = JSON && JSON.parse(data) || $.parseJSON(data);
//now you can use the attributes of your loginResult easily in JavaScript
//for example, assuming you have a name attribute in your Customer class
alert(loginResult.name);
}
});
return false;
});
});
</script>
More info:
How to use Servlets and Ajax?
Parse JSON in JavaScript?

jquery ajax call returns error on successful call to a servlet

I have a servlet that adds a user to a file on the server side.
I invoke it with a jqueries ajax call.
I can see on the server that the method is being called correctly and my user is added, but the error callback is being invoked on the jquery call. All the status text says is error.
Using firebug the response seems to be empty. Why can I not get a success jquery callback?
//Servlet Code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
String responseStr = "";
if(action.equals("addUser"))
{
responseStr = addUser(request);
}
System.out.println("Reponse:" + responseStr);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().println(responseStr);
}
private String addUser(HttpServletRequest request) throws IOException
{
Storage s;
s = Storage.load();
String name = request.getParameter("name");
String imageUrl = request.getParameter("imageUrl");
User u = new User();
u.setName(name);
u.setImageUrl(imageUrl);
s.addUser(u);
s.save();
return "success";
}
.
//javascript code
function addUser() {
var name = $('#name').val();
var imageUrl = $('#imageUrl').val();
var url = "http://ws06525:8080/QCHounds/QCHoundServlet?action=addUser&name=${name}&imageUrl=${imageUrl}";
url = url.replace("${name}", name);
url = url.replace("${imageUrl}", imageUrl);
$('#result').html(url);
$.ajax({
url: url,
success: function( data ) {
$('#result').html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error: " + textStatus);
alert("error: " + errorThrown);
}
});
}
Aaargh! Feel like an idiot. It's a cross site scripting issue.
I was testing the call to the server from the html file on disk so my browser address was
file://projects/myproject/content/Users.html <<< Fail
instead of:
http://myboxname:8080/appname/Users.html <<< Works
The actual code is fine...
use this for learn what is the problem, it will be better for get solution i think
error: function(e){
alert(JSON.stringify(e))
}
For one thing the string "success" isn't valid json. If your ajax query is expecting json, that would fail it.
What if you returned "{ \"success\": true }" ?
EDIT
It looks like from your ajax call that the response shouldn't be json, why is your return content type json?
If it is true that firebug shows no response, your problem must be in the java code that writes the response.

Categories

Resources