HttpServletResponse shall send data without printing them to client screen - java

I am building a web application.
Part of this web application is an ajax request from the client-side to the server:
$.ajax({
url: url,
type: "get",
data: {
id: ID,
},
success: function(response) {
//parameter response contains the data sent back from the server
//some stuff is done to this data in the rest of this function
},
error: function() {
alert("An error occurred.");
}
});
On the server side I am using a servlet to handle the requests.
Once the data from the client is received, and some business logic has been applied to it, I want to send back a simple String.
The data string would then be handled by the following part of the ajax-function above:
success: function(response) {
//parameter response contains the data sent back from the server
//some stuff is done to this data in the rest of this function
},
My problem is this:
I know how to send data to the screen of the client:
PrintWriter out = response.getWriter();
out.println(data);
However, I don't know how to send data (not to the screen but instead) to the ajax-function, so that this ajax-function can then work with the data received from the server.
The java object "response" of class "HttpServletResponse" only provides methods such as "sendError()".
I want to send the data without printing them to the screen.
How can I do that?
*************************UPDATE********************************************
I tried to use PrintWriter to send a string back to the ajax function:
PrintWriter out = response.getWriter();
out.println("test");
... I then wanted to output the text "test" in an alert-message:
$.ajax({
url: url,
type: "get",
data: {
latitude: location.lat(),
longitude: location.lng(),
radius: 10
},
success: function(response) {
alert(response);
},
error: function() {
alert("Ein Fehler beim Abfragen der Daten ist aufgetreten.");
}
});
But instead of outputting an alert-message with content "test", the output consists of the whole html code of the JSP-Page from which the ajax-call had been sent!

Nothing gets sent to the "screen" specifically, it is all about where the request originates.
If you click on a link, the browser initiates the request, and the browser receives response and processes the output to display.
In this case, the request will originate from your ajax call, and therefore the ajax call will process the request and the content will be received in the .requestText property of the response.
You'll probably want to make sure the response content type of the HttpServletResponse object is set to "text/html", But since you're going so far as to use ajax, you might as well consider a step into using JSON as well.

Related

Passing Arabic data from node request to Java server

I am trying to send Arabic data from post request of node to Java (Glassfish server, grizzly framework, formatted to be utf-8 for request content). But the request upon receiving in the Java server shows some garbage value "ÙÙاÙبة اÙعاÙÙ " instead of Arabic text.
The request from node is:
var request = require('request');
request.post("http://localhost:8080/taJavaServer/taResponse", {json: true, body: "مواكبة العالم "}, function(err, res, body) {console.log(body);console.log(err)});
So, I dont know how to send exact same Arabic text from node's request post to Java server.
More Info
On calling the java-api via ajax (jQuery), it works fine and Arabic text is getting detected.
$.ajax({
url: "http://localhost:8080/taJavaServer/taResponse",
type: 'POST',
dataType: "JSON",
data: JSON.stringify({data: "مواكبة العالم "}),
success: function (respon) {..}...
You're not actually sending valid json, try something like this:
request.post("http://localhost:8080/taJavaServer/taResponse", {json: true, body: {data:"مواكبة العالم "}}, function(err, res, body) {console.log(body);console.log(err)});

How to build request to java server?

I am writing a REST server and client for it on Java. I do this for educational purpose.
My server is a web application that handle request from clients via servlet. After that it opens a storage conenction, retrieve data and send it as a json.
My client is a web aplication which has some simple web pages. User click a button, servlet on client handle and send(sic!) request to the server.
May be this way a little bit odd because on the client side moderbn world write just html pages with rich JS code, e.g. Bootstrap, Backbone Angular etc.and server side is wrote via JAX-RS or Spring, but my aim is to write this pet project on pure java as simple as it can be.
I faced with an issue that I don't understand how to send request from client side to the server side. I have received request from user in servlet and I want to send a reponse to the server.
What are possible ways to do that and what is the best one?
Thanks.
You can use Jquery Ajax to call your webservices with parameter required on server side. Update your view/jsp/html based on the data get from servlet.
Ajax Call from javascript :
function onButtonClick(){
$.ajax({
type: "post", //method type
dataType: "json", //response data type
url: ajaxUrl, //your webservice URL
data: "jsonobj", // Data to be send to server
success: function(response) // call back function after get successfull responce
{
// Process JSON response here
}
});
}
Your servlet code :
public class ResellerServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse res)
{
//Process request here
// Convert your response in JSON and send it back to client
}
}

Form submission with POST method is truncated in Firefox

I have an Struts 2 application running in https.
I have a large form with data size approx 8KB, where the back end object is binding from the front end.
The form is submitted to the server properly in IE.
But when the form is submitted through Firefox then the data is not binding properly in the back end objects as well as the request method is truncated. we are submitting the form by using POST method but in server the method name is 'OST'.
Ex :
HttpServletRequest request;
request.getMethod() return "OST"
form is submitting with java script and jquery
Ex :
var data = $('#regHHFormID').serialize();
$.get('activateProfile.action', data, function(result) {
console.log(result);
}, "json");
Here is the sample data which is submitted to the server after serialize.
household.status=0&dualActiveDutyfamilyTypeID=15&household.key=897788905893&household.createFrom=CONSUMER&household.profileDatas%5B0%5D.type=SPONSOR&household.profileDatas%5B0%5D.profileID=1847&household.profileDatas%5B0%5D.profileNameData%5B0%5D.profileNameID=1885&household.profileDatas%5B0%5D.profileNameData%5B0%5D.firstName=sss&household.profileDatas%5B0%5D.profileNameData%5B0%5D.middleName=&household.profileDatas%5B0%5D.profileNameData%5B0%5D.lastName=sss&household.password=111111111aA&password2=111111111aA&household.familyGroupID=1&household.familyTypeID=4&household.profileDatas%5B0%5D.branchID=5&household.profileDatas%5B0%5D.command=&household.profileDatas%5B1%5D.type=SPOUSE&household.profileDatas%5B1%5D.profileID=&household.profileDatas%5B1%5D.profileNameData%5B0%5D.profileNameID=&household.profileDatas%5B1%5D.profileNameData%5B0%5D.firstName=ss&household.profileDatas%5B1%5D.profileNameData%5B0%5D.middleName=rrr&household.profileDatas%5B1%5D.profileNameData%5B0%5D.lastName=sss&household.profileDatas%5B1%5D.branchID=0&household.profileDatas%5B1%5D.command=&childProfile.profileNameData%5B0%5D.firstName=C4&childProfile.profileNameData%5B0%5D.middleName=CR&childProfile.profileNameData%5B0%5D.lastName=RG&childProfile.isUnBorn=false&birthDate=11.4.2013&childProfile.profileIATAnswerDatas%5B0%5D.questionID=1&childProfile.profileIATAnswerDatas%5B0%5D.profileIATAnswerID=&childProfile.profileIATAnswerDatas%5B0%5D.answer=false&childProfile.profileIATAnswerDatas%5B0%5D.answerDetails=Please+provide+information+that+will+help+us+support+your+child's+medical+needs.&childProfile.profileIATAnswerDatas%5B1%5D.questionID=2&childProfile.profileIATAnswerDatas%5B1%5D.profileIATAnswerID=&childProfile.profileIATAnswerDatas%5B1%5D.answer=false&childProfile.profileIATAnswerDatas%5B1%5D.answerDetails=Please+describe+accommodations+necessary+to+help+this+child+participate+in+Child+and+Youth+Programs.&household.profileDatas%5B2%5D.profileID=0&household.profileDatas%5B2%5D.type=CHILD&household.profileDatas%5B2%5D.profileNameData%5B0%5D.profileNameID=&household.profileDatas%5B2%5D.profileNameData%5B0%5D.firstName=C4&household.profileDatas%5B2%5D.profileNameData%5B0%5D.middleName=CR&household.profileDatas%5B2%5D.profileNameData%5B0%5D.lastName=RG&household.profileDatas%5B2%5D.birthDateConsumer=11.4.2013&household.profileDatas%5B2%5D.isUnBorn=false&household.profileDatas%5B2%5D.editStatus=&household.profileDatas%5B2%5D.profileIATAnswerDatas%5B0%5D.questionID=1&household.profileDatas%5B2%5D.profileIATAnswerDatas%5B0%5D.profileIATAnswerID=&household.profileDatas%5B2%5D.profileIATAnswerDatas%5B0%5D.answer=false&household.profileDatas%5B2%5D.profileIATAnswerDatas%5B1%5D.questionID=2&household.profileDatas%5B2%5D.profileIATAnswerDatas%5B1%5D.profileIATAnswerID=&household.profileDatas%5B2%5D.profileIATAnswerDatas%5B1%5D.answer=false&household.profileDatas%5B0%5D.profilePostalAddressDatas%5B0%5D.profilePostalAddressID=&household.profileDatas%5B0%5D.profilePostalAddressDatas%5B0%5D.typeCode=PRIMARY&household.profileDatas%5B0%5D.profilePostalAddressDatas%5B0%5D.line1=D&household.profileDatas%5B0%5D.profilePostalAddressDatas%5B0%5D.line2=F&household.profileDatas%5B0%5D.profilePostalAddressDatas%5B0%5D.city=F&household.profileDatas%5B0%5D.profilePostalAddressDatas%5B0%5D.stateCode=AL&household.profileDatas%5B0%5D.profilePostalAddressDatas%5B0%5D.zip=12323&household.profileDatas%5B0%5D.profilePostalAddressDatas%5B0%5D.countryCode=USA&household.profileDatas%5B0%5D.profilePhoneNumberDatas%5B0%5D.profilePhoneNumberID=0&household.profileDatas%5B0%5D.profilePhoneNumberDatas%5B0%5D.phoneNumber=111.111.1111&household.profileDatas%5B0%5D.profilePhoneNumberDatas%5B0%5D.typeCode=WORK&household.profileDatas%5B0%5D.profilePhoneNumberDatas%5B0%5D.entityType=CONSUMER&household.profileDatas%5B0%5D.profilePhoneNumberDatas%5B0%5D.entityID=0&household.profileDatas%5B0%5D.profilePhoneNumberDatas%5B0%5D.belongsTo=1&household.profileDatas%5B0%5D.profilePhoneNumberDatas%5B0%5D.editStatus=&household.profileDatas%5B0%5D.profilePhoneNumberDatas%5B0%5D.isPreferred=true&household.profileDatas%5B0%5D.profileEmailAddressDatas%5B0%5D.profileEmailAddressID=1232&household.profileDatas%5B0%5D.profileEmailAddressDatas%5B0%5D.emailAddress=ss%40fer.com&household.profileDatas%5B0%5D.profileEmailAddressDatas%5B0%5D.typeCode=PRIMARY&household.profileDatas%5B0%5D.profileEmailAddressDatas%5B0%5D.entityType=CONSUMER&household.profileDatas%5B0%5D.profileEmailAddressDatas%5B0%5D.entityID=1847&household.profileDatas%5B0%5D.profileEmailAddressDatas%5B0%5D.belongsTo=1&household.profileDatas%5B0%5D.profileEmailAddressDatas%5B0%5D.isNotify=true&household.profileDatas%5B0%5D.profileEmailAddressDatas%5B0%5D.editStatus=&household.emailNotificationDatas%5B0%5D.emailNotificationID=58&household.emailNotificationDatas%5B0%5D.isMandatory=false&household.emailNotificationDatas%5B0%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B0%5D.isSelected=true&household.emailNotificationDatas%5B1%5D.emailNotificationID=59&household.emailNotificationDatas%5B1%5D.isMandatory=true&household.emailNotificationDatas%5B2%5D.emailNotificationID=60&household.emailNotificationDatas%5B2%5D.isMandatory=false&household.emailNotificationDatas%5B2%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B2%5D.isSelected=true&household.emailNotificationDatas%5B3%5D.emailNotificationID=61&household.emailNotificationDatas%5B3%5D.isMandatory=false&household.emailNotificationDatas%5B3%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B3%5D.isSelected=true&household.emailNotificationDatas%5B4%5D.emailNotificationID=62&household.emailNotificationDatas%5B4%5D.isMandatory=false&household.emailNotificationDatas%5B4%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B4%5D.isSelected=true&household.emailNotificationDatas%5B5%5D.emailNotificationID=63&household.emailNotificationDatas%5B5%5D.isMandatory=true&household.emailNotificationDatas%5B6%5D.emailNotificationID=64&household.emailNotificationDatas%5B6%5D.isMandatory=false&household.emailNotificationDatas%5B6%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B6%5D.isSelected=true&household.emailNotificationDatas%5B7%5D.emailNotificationID=65&household.emailNotificationDatas%5B7%5D.isMandatory=false&household.emailNotificationDatas%5B7%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B7%5D.isSelected=true&household.emailNotificationDatas%5B8%5D.emailNotificationID=66&household.emailNotificationDatas%5B8%5D.isMandatory=false&household.emailNotificationDatas%5B8%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B8%5D.isSelected=true&household.emailNotificationDatas%5B9%5D.emailNotificationID=67&household.emailNotificationDatas%5B9%5D.isMandatory=false&household.emailNotificationDatas%5B9%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B9%5D.isSelected=true&household.emailNotificationDatas%5B10%5D.emailNotificationID=68&household.emailNotificationDatas%5B10%5D.isMandatory=true&household.emailNotificationDatas%5B11%5D.emailNotificationID=69&household.emailNotificationDatas%5B11%5D.isMandatory=false&household.emailNotificationDatas%5B11%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B11%5D.isSelected=true&household.emailNotificationDatas%5B12%5D.emailNotificationID=70&household.emailNotificationDatas%5B12%5D.isMandatory=false&household.emailNotificationDatas%5B12%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B12%5D.isSelected=true&household.emailNotificationDatas%5B13%5D.emailNotificationID=76&household.emailNotificationDatas%5B13%5D.isMandatory=false&household.emailNotificationDatas%5B13%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B13%5D.isSelected=true&household.emailNotificationDatas%5B14%5D.emailNotificationID=77&household.emailNotificationDatas%5B14%5D.isMandatory=false&household.emailNotificationDatas%5B14%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B14%5D.isSelected=true&household.emailNotificationDatas%5B15%5D.emailNotificationID=71&household.emailNotificationDatas%5B15%5D.isMandatory=false&household.emailNotificationDatas%5B15%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B15%5D.isSelected=true&household.emailNotificationDatas%5B16%5D.emailNotificationID=82&household.emailNotificationDatas%5B16%5D.isMandatory=false&household.emailNotificationDatas%5B16%5D.isSelected=true&__checkbox_household.emailNotificationDatas%5B16%5D.isSelected=true&household.emailNotificationDatas%5B17%5D.emailNotificationID=72&household.emailNotificationDatas%5B17%5D.isMandatory=true&household.emailNotificationDatas%5B18%5D.emailNotificationID=73&household.emailNotificationDatas%5B18%5D.isMandatory=true&household.emailNotificationDatas%5B19%5D.emailNotificationID=74&household.emailNotificationDatas%5B19%5D.isMandatory=true&household.emailNotificationDatas%5B20%5D.emailNotificationID=75&household.emailNotificationDatas%5B20%5D.isMandatory=true
I am not finding any clue why this is happening.
Jquery get method in turn calls the AJAX only. so you can think of using the AJAX api of Jquery
$.ajax({
url:"activateProfile.action"
type: "POST",
dataType : "json"
data: data,
success:function(data){
console.log('in your success step');
}
});
Make sure to declare the cache according to your usage. Hope this helps.
If your request.getMethod() returns "OST" this means that a method is not a valid HTTP one. And the browser revert to default which is "GET".
This method has bounds on data send in the URL. It could be limited by the length of the URL itself. Check the <form> tag or if you are using Ajax request the method "POST" is used to encapsulate the data with the request.

Is it possible to submit a form and send an ajax request at the same time jquery

I'd like to submit a form and, at the same time, send an ajax request to my Spring MVC Server. For it I have a form like this:
<form id='confirma' method='post' action='confirma'>
<button type='submit' id='save' class='btn btn-success' value='Save'>Enviar</button>
</form>
In my server, I would have two methods to receive both requests (the ajax request and the normal form submission).
// receive from form
#RequestMapping("fromForm")
public String fromForm(Model model)
{
// get atb1 values from database
model.addAttribute("atb1", atb1);
return "file.jsp";
}
// receive from ajax
#RequestMapping("fromAjax")
public void fromAjax(String jsonData)
{
// deserialize json Data and insert it on database
System.out.println("data received!");
}
My intention is to receive the data from the Ajax request, save it in database, and get this data in the form submission method, called, in this example, fromForm.
I know this might look crazy but I'm doing this because I have a sequence of submit forms and I'd like to make them independent from each other so I could call any of them without have passed the data from the previously form.
I have tried to deal with it by using jQuery. So this is what I've done:
function ajaxRequest() {
var jsonArray = new Array();
// Complete the jsonArray with an Array of objects created by myself
$.ajax({
url: "fromAjax",
cache: false,
contentType: false,
processData: false,
data: JSON.stringify(jsonArray, null, 4),
type: 'POST',
success: function (data, textStatus, jqXHR) {
console.log("success ajax");
return true;
},
error: function (xhr, status, error) {
console.log("error ajax");
return false;
}
});
}
$(document).on('submit', '#confirma', function(event) {
event.preventDefault();
// by return this method, I would just call the another jsp page, if the ajax
// request is completed successfully
return ajaxRequest();
});
This is not working though.. If I remove the event.preventDefault in the form submission, I only receive the form submission on the server. If I have the event.preventDefault call, only the ajax request hits the server.
How can I make both of the requests hit the server?
Think of this from the browser's perspective. Imagine that it has successfully fired both a XmlHttpRequest to /fromAjax and a regular form submission POST to /confirma. Now imagine that the server responds to the POST /confirma first. What is the browser to do when the form submission response contains a new HTML page to display, or is a redirect to another page - what should the browser do with the (still pending) XmlHttpRequest?
Or if you look at it from the server's perspective - what should happen when the server processes the request to your fromForm() method before it has received or begin to process the request to the fromAjax() method?
If your intention is to
receive the data from the Ajax request, save it in database, and get this data in the form submission method
then I would first send the ajax request and then when you receive the response, trigger the form submission from Javascript, so that these requests happen serially (one after the other) rather than in parallel.

Java-ajax cross site empty response string

I am doing a cross-site ajax to java data transaction(Not sure if I named that correctly, so please forgive me about that). Part of code in Java file:
BufferedReader input =
new BufferedReader(new InputStreamReader(connectionsocket.
getInputStream()));
DataOutputStream output =
new DataOutputStream(connectionsocket.getOutputStream());
...
output.writeChars("some random text");
output.close();
Also I have index.php file with some jQuery:
$(document).ready(function()
{
$("#send_data").click(function(){
$.ajax({
type: 'get',
dataType: 'text',
url: 'http://localhost:1024/'+$("#command").val(),
success: function(data) {console.log(data);},
error: function() { console.log("Error"); }
})
});
});
The command is sent correctly and received in Java side correctly. Then the request from java to ajax is 200 OK too. The output is also working. (For example if I remove output.close(), I do see in the firebug, that it is waiting for the output to be closed.)
The only problem is, no matter what I do I get no response text. It's always an empty string :(
cross-site ajax to java data transaction
and
index.php
and
Java
Implies you are violating same origin policy. You must use same host:port combination to retrieve the webpage (or at least the javascript version of the code that does AJAX) and send AJAX requests.
In other words, if your JS comes from localhost:80 and you are trying to send AJAX request to localhost:1024, you are violating security policies.
There are ways to do cross-domain AJAX like jsonp, but do you really need that? I would suggest serving jQuery code from the servlet, or eliminate PHP at all, or, even better, rewrite everything in Scala or Erlang. :)
in your code you create dataType:"xml"
try to use with text.because in your response i don't see the xml format,you're create response with format text.
$.ajax({
type: 'get',
dataType: 'text',
url: 'http://localhost:1024/'+$("#command").val(),
success: function(data) {console.log(data);},
error: function() { console.log("Error"); }
read this for option ajax request http://api.jquery.com/jQuery.ajax/

Categories

Resources