AJAX not receiving response from servlet - java

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.

Related

Java Servlet send form data to REST API

I have a simple HTML form to send a request to a REST API. It works well, when I submit, it sends the form data to API and displays the response in the browser.
<form name="theForm" action="localhost:8080/App/rest/consumeForm" method="post">
<input name="userName" value="Bob Smith" /><br/>
<input type="submit" value="submit"/>
</form>
Browser shows:
{"address": "12 First St.", "city": "Toronto"}
I would like to capture the response. Any ideas? (no ajax or javascript, just plain old Servlet or JSP please)
PART 2:
I now POST my form to a servlet I created, which handles the request and response from the REST API. It works nicely, but it needs the form data URLEncoded. Anyone know if there is a way to convert form data to such a string, or even convert form data to JSON directly?
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String userName = "Bob Smith";
String country = "Canada";
String queryString = String.format("userName=%s&country=%s"
,URLEncoder.encode(userName, charset)
,URLEncoder.encode(country, charset)
);
Can I build the above queryString dynamically?
//// send request
URLConnection connection = new URL("localhost:8080/App/rest/consumeForm").openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(queryString.getBytes(charset));
}
//// get response
BufferedReader apiResponse = new BufferedReader(new InputStreamReader((connection.getInputStream())));
String output;
System.out.println("\n\n\nrecieved....");
while ((output = apiResponse.readLine()) != null) {
System.out.println(output);
}
I would like to capture the response. Any ideas?
Install a servlet Filter that handles this. When it receives a request for the REST API endpoint, it can feed an HttpServletResponse to the next element in the chain that is equipped with any tooling you want. You would probably find HttpServletResponseWrapper to be a useful base class for your custom-tooled response class.
The Filter implementation might be along these lines:
public class ResponseCapturingFilter implements Filter {
private static final String SERVLET_TO_FILTER = "...";
#Override
public void init(ServletConfig config) {
// ...
}
#Override
public void destroy() {
// ...
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (((HttpServletRequest) request).getServletPath().equals(SERVLET_TO_FILTER)) {
response = new MyCapturingResponseWrapper(response);
}
chain.doFilter(request, response);
}
}
To capture the response text, you would want your wrapper to override at least getOutputStream() and getWriter() appropriately.
It turns out that submitting to a servlet using POST and communicating with the REST API using the servlet works for me. There may be better ways, but this seems relatively clean for junior developers to follow and maintain. (I'm still open to other options).
I build a queryString with the form data (req is the HttpServletRequest)
String theQueryString="domainId=1";
for(Entry<String, String[]> qsParm:req.getParameterMap().entrySet()) {
theQueryString+="&"+qsParm.getKey()+"="+URLEncoder.encode(req.getParameter(qsParm.getKey()), charset);
}
// set up connection to use as API interaction
URLConnection connection = new URL("localhost:8080/App/rest/consumeForm").openConnection();
connection.setDoOutput(true); // Triggers POST apparently
connection.setRequestProperty("Accept-Charset", java.nio.charset.StandardCharsets.UTF_8.name());
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + java.nio.charset.StandardCharsets.UTF_8.name());
// send request to API via connection OutputStream
try (OutputStream output = connection.getOutputStream()) {
output.write(theQueryString.getBytes(java.nio.charset.StandardCharsets.UTF_8.name())); // this sends the request to the API url
}
// get response from connection InputStream and read as JSON
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonMap = mapper.readTree(connection.getInputStream());
// now the response can be worked with in at least two ways that I have tried
String user1 = jsonMap.get("userName").asText();
String user2 = jsonMap.at("user").getValueAsText();

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

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.

My Titanium Post Works, how do I display in Java Servlet?

Hi im trying to send data from my titanium app to my Apache Web Service. The snippet of titanium code works as the output to the console is success. Now what im trying to do is when the post is sent, display the contents of the post on the web service page. Is my doPost correct?
Titanium Snippet
button.addEventListener('click', function(e) {
var params = {
"places" : {
Country : textCountry.getValue(),
Capital : textCapital.getValue()
}
};
var xhr = Ti.Network.createHTTPClient({});
// function to deal with errors
xhr.onerror = function() {
Ti.API.info('error, HTTP status = ' + this.status);
alert('Error Sending Data');
};
// function to deal with response
xhr.onload = function() {
console.log('success, HTTP status = ' + this.status);
};
xhr.open("POST", 'http://130.206.127.43:8080/Test');
//set enconding
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.send(JSON.stringify(params));
});
Java Servlet/Apache Tomcat Snippet
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String jsonData = request.getParameter("json");
response.setContentType("applicaiton/json");
PrintWriter out= response.getWriter();
out.println(jsonData);
out.close();
}
18/02/205
// function to deal with response
xhr.onload = function() {
console.log('success, HTTP status = ' + this.status);
Ti.API.info('json' + this.responseText);
};
[INFO] : success, HTTP status = 200
[INFO] : json = null
Set a breakpoint in the xhr.onload and look at the variables that are present before your write your log.
You are looking for the this.responseText, which will have the response from your call to the Java servlet. I mainly use WCF and C# and if I don't setup the WCF service specifically to clean-up the output, it will add the function name to the response.
Generally, my onload looks like this.
xhr.onload = function(){
var result = JSON.parse(this.responseText);
Ti.API.log(result);
}
* Look closer at your Java Servlet return type. It is a VOID return type so no data will be returned to the http call. *
http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.Network.HTTPClient

Parameter is not passing from extjs grid to servlet page

In my application I am passing parameters from grid to servlet page. But in servlet it is coming as null. Any idea what is wrong in my code..
Note: From this servlet page I am taking data for another grid.
Function to pass parameter:
function callAjaxToCheckSession(selected)
{ alert(selected);
Ext.Ajax.request({
url: 'YieldCurveServlet',
method:'POST',
headers: {'application/json'},
params: {
YCSET_ID: selected
},
success: function(response, opts) {
var obj = Ext.decode(response.responseText);
console.dir(obj);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
}
In this I am getting value in an alert. and same value in http header (request payload YCSET:value). But in servlet it is coming as null.
Here is my servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String val = request.getParameter("YCSET_ID");
System.out.println(val);
Here is header Part:
Request Method:POST
Status Code:200 OK
**Request Headers**
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:21
Content-type: text/html
Cookie:JSESSIONID=5621DF422D5E54A4EFFD29E5868A40FE
X-Requested-With:XMLHttpRequest
**Request Payload**
YCSET_ID=SPREAD_CURVE
**Response Headers**
Content-Length:56
Content-Type:text/html
Date:Tue, 24 Dec 2013 12:48:13 GMT
Server:Apache-Coyote/1.1
Any suggestion to fix this issue?
You have to get the value send as parameter in the request with the getParameter function, so uncomment the line :
String val = request.getParameter("YCSET_ID")
request.getParameter("parameter_name"); works for query string parameters and form data. To get JSON data serverside from a request try this:
BufferedReader buff = request.getReader();
String json = buff.readLine();
if (!json.startsWith("[")) {
json = "[" + json + "]";
}
The if part works when you have a single value on your array and it looks more like an object. That way you can treat it as an array always.

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