Send JS object to JSP page [duplicate] - javascript

This question already has answers here:
Call Servlet and invoke Java code from JavaScript along with parameters
(3 answers)
Closed 6 years ago.
I have a JS object in a JavaScript file. I have to pass this object to a JSP page. The page picks up this object and processes it. How can I do it?

The same way you get any other data from a web browser to an HTTP server.
Encode it in an HTTP request by submitting a form / setting the window location / using XMLHttpRequest / etc.

There are a couple of issues you need to resolve first, are you doing this in an AJAX style of request? is this a form submission? is there going to be on-going interaction within the page-session between the client/server passing JSON objects back-and-forth?
Lets tackle the simple case of a form submission, once you get that you should be able to get the remaining cases going as they are just "extensions" of this base case. Say you have some form that will submit the data in some field:
<form name='my_form' id='my_ford_id'>
<input type='hidden' name='my_input_field' />
</form>
then at some point in time you have a piece of code that executes and you have your JSON object
function myFunction() {
var json_data = getJsonData();
document.forms['my_form']['my_input_field'].value = json_data;
document.forms['my_form'].submit();
}
You will then on the JSP side receive this data as a JSON string inside of a form field, at which point you need to process it, lets assume you have some kind of a JSON library available to you, the code might look something like this:
<%
String myInputField = request.getParameter("my_input_field");
if(myInputField != null) {
try {
JSONObject myObject = new JSONObject(myInputField);
}
catch(JSONException e) {
}
}
%>
If you need an "AJAX" style of interaction, you will be making a number of such requests in the page, but fundamentally it falls back to the original problem of submitting the data. Since you are using forms in this example, and JSP, you don't have to worry at any point about encoding, the browser/server will take care of things for you.

When you send json object the servlet receive it in the same way of receiving data sent by submitting the form, for example, if you send a variable "action" with value="getCountries"
var option = {
"action": "getCountries"
};
$.getJSON('YourServlet', option, function() {
//hadle the result returned by servlet
});
The defualt method is GET, in the servlet you handle the request as you handle a normal request
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String action = request.getParameter("action");
if (action != null) {
if (action.equals("getCountries")) {
List coutries = getAllICountries(request); //get the countries
String json = new Gson().toJson(coutries);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(json);
return;
}
}
}
Notice how we return the result from servlet to javascript, we return a json object.

"JSON" Site helps you to manage Json Objects in JSp/java.
You have to convert the string obtained from javascript to a json object.Then manage it easily.

Related

URL GET using Basic Auth with Java Servlet

I have a .jsp page which handles some basic html (text field, submit button a table to populate) and javascript. On click it calls my java Servlet class which handles the request and the response from and to the jsp respectfully. I also have a Java class to handle url connection to make a REST call using GET which should return a json string result. This is the scenario: User wishes to make a simple search by entering an ID value to populate the table using REST to connect to a url and get a json response.
I have separately tested the Java class to make a REST call made by URL connection with Basic Authentication to GET the data in json string and it works perfectly fine. (I have coded 4 different methods of doing this and all work fine and return the expected json).
I have separately tested the jsp page making a call to the servlet to populate "dummy" values in the table and the servlet response is fine and the table populates as expected.
THE PROBLEM:
When I tried to populate the table by the values obtained from the GET REST call, it hangs and I get no result. So I tried to investigate why and found out that for some crazy reason, the servlet doesn't like the line of code which sets the header with the basic authentication to get access to the URL. I tried commenting the basic auth 1 line code out (to debug, so now we have no authentication) but passing through some "dummy" hard coded data, and it populates the table.
I actually don't know why the servlet doesn't like it when I set the authentication. My guess is probably it is overwriting the servlet's response path and therefore lost the initial response location to the jsp? (i.e. where to send the json back to?) Can anyone help me here? Anyone know whats happening? is my assumption of the problem correct? if so, how do I overcome this problem?
Javascript call to the servlet:
$("#myForm2").submit(function(e) {
$.ajax({
type: "GET",
url: "servlet1", // the script where the form input is handled.
data: $("#myForm2").serialize(), // serializes the form's elements.
success: function(responseData){
var dataObj = $.parseJSON(responseData)
$('#myTable').append(>>add values to table here<<);
});
e.preventDefault(); // avoid to execute the actual submit of the form.
$("#myForm2")[0].reset(); // clear previous values entered
});
Servlet class, request made by jsp page and the servlet's response:
Rest getCallOnURL = new Rest(); // instance of my rest class
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException {
// create a dummy string "test" to hold the ID value passed in from javascript
String testID = request.getParameter("ID");
// Hard coded - only for testing purposes
if (testID.equals("1")){
//call my java class' method to connect to url and retrieve the json string
getCallOnURL.connectToUrlAndMakeAGetRequest();
valueToPopulateTable = getCallOnURL.testJsonString;
}
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
// using backslash to escape the quotes to make a valid json response
out.print("{\"testRow\": \"valueToPopulateTable\"}");
out.close();
}
My Java Class method to make URL call and Basic Authentication:
String testJsonString = "defaultValue";//testing purposes
//creates a valid encoded authentication string
private String basicAuth(String name, String pass){
String authString = name + ":" + pass;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
return authStringEnc;
}
private HttpURLConnection prepareGETConnection(final URL verifierURL)
throws IOException {
final HttpURLConnection connection = (HttpURLConnection) verifierURL.openConnection();
connection.setRequestMethod("GET");
//this is the line which authorizes access to the url via Basic Auth
connection.setRequestProperty("Authorization", "Basic " + basicAuth(name, password));
return connection;
}
public void connectToUrlAndMakeAGetRequest(){
try {
String webPage = "URL HERE";// pass it a valid REST url with endpoints
URL url = new URL(webPage);
HttpURLConnection conn = prepareGETConnection(url);
// get the url response json string
InputStream getUrlresponse = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(getUrlresponse));
//get only the first line of the string - testing purposes only!
testJsonString = rd.readLine();
rd.close();
conn.disconnect();
} catch(IOException e){
System.out.println("IO exception: "+e);
}
}

Retrive post data back using javascript/jquery

I want to pass the object to the new page by using only client side script(javascript),
and I want to read the data back when the new page is loads, but I could not find any tutorial or method to get it.
function postToURL(path, parameters) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
// The form needs to be a part of the document in
// order for us to be able to submit it.
$(document.body).append(form);
form.submit();
}
The POST message sent to the server to retrieve the current page is not exposed, by the browser, to JavaScript in that page, so you cannot.
Pass the data via some other technique (such as through the URL, or localstorage).
Yeah, POST data is only handled and seen by the server side (ex. PHP). Javascript is on the client side so it will never be able to see that data unless the POST data first gets passed to server side and that server side in turn hands it off to the client side (ex. Javascript).
Consider using GET as your method in your code above so that you can pass the parameters inside the actual URL to make it accessible to the browser / client / Javascript.
parameters can be parsed from a JSON-encoded string. If you build your parameters programmically (in the previous step) like:
parameters = {};
parameters['USA'] = 'Washington DC';
parameters['UK'] = 'London';
You can create a flat JSON String representing your structured data by:
parametersString = JSON.stringify(parameters);
and end up with something like this:
"{'USA': 'Washington DC', 'UK': 'London'}"
You can store this string in a cookie, or in a query string or fragment part of the URL.
Your next page can read back this value on the following page, and re-create the structured parameters by decoding the JSON string like:
parameters = JSON.parse(parametersString);
and you're getting the original data back, on which you can run JQuery's each.

Can JavaScript read HTTP Session object?

Is it possible to read the value of a dynamic variable like httpRequest.getSession("attr_name") from within a JavaScript?
(With Javascript, I assume that you mean client script in the browser.)
No, that is not possible. The contents of the Session object never leaves the server, so client script can't read Session data directly.
If you want to access it in the browser, you have to read the data out of the Session object and send it along in the response (for example in a hidden field), or provide a web service that reads data from the Session object and returns to the browser.
As I said in my comment, the only way would be some kind of Ajax call and request it from the server. I dont know what backend your using, here's how I would do it in Asp.net MVC and jQuery.
(If there are minor syntax errors, I apologize - not in front of a compiler)
public class HomeController : Controller
{
//abstract the session code away, don't let the evil javascript touch
//it directly. Ideally this would all be in a seperate logic class or something.
public string NameAttribute
{
get
{
return Session["attr_name"] as string ?? string.empty;
}
}
[HttpGet]
public string GetNameAttribute()
{
return NameAttribute;
}
public ActionResult Index()
{
return View();
}
}
<script>
$(function(){
$.get( 'home/GetNameAttribute', function( response ) {
var name = response; //don't forget error checking, ommited
});
});
</script>
Alternatively, you could always write down the values you need into hidden fields, and read them with normal javascript.

AJAX responseXML

i have a problem regarding the responseXML of ajax..
I have this code from my callback function:
var lineString = responseXML.getElementsByTagName('linestring')[0].firstChild.nodeValue;
However, the linestring can only hold up to 4096 characters max.. the remaining characters are rejected.
I dont know what to use to get all the values that the lineString
returns. its quite a big data thats why I thought of using the responseXml
of AJAX, BUT turned out it still cannot accomodate everything.
My linestring consists of lines from a logfile which I concatenated and just
put line separator. I need to get this data in my form so that is why after reading from the php, i send it back via AJAX
Do you have suggestions guys.
XML adds a lot of extra markup for most ajax requests. If you are expecting some kind of list with data entities, sending them in a JSON format is the way to go.
I used JSON to get quite huge arrays with data.
First of all, JSON is just Javascript Object Notation meaning that the Ajax Request would request a String which will actually be evaluated as a Javascript object.
Some browsers offer support for JSON parsing out of the box. Other need a little help. I've used this little library to parse the responseText in all webapps that I developed and had no problems with it.
Now that you know what JSON is and how to use it, here's how the PHP code would look like.
$response = [
"success" => true, // I like to send a boolean value to indicate if the request
// was valid and ok or if there was any problem.
"records" => [
$dataEntity1, $dataEntit2 //....
]
];
echo json_enconde($response );
Try it and see what it echos. I used the php 5.4 array declaration syntax because it's cool! :)
When requesting the data via Ajax you would do:
var response
,xhr = getAjaxObject(); // XMLHttp or ActiveX or whatever.
xhr.open("POST","your url goes here");
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && xhr.status==200) {
try {
response = JSON.parse(xhr.responseText);
} catch (err) {
response = {
success : false,
//other error data
};
}
if(response.success) {
//your data should be in response
// response.records should have the dataEntities
console.debug(response.records);
}
}
}
Recap:
JSON parsing needs a little help via JSON2 library
PHP can send maps as JSON
Success boolean is widely used as a "successful/unsuccessful" flag
Also, if you're into jQuery, you can just set the dataType : "json" property in the $.ajax call to receive the JSON response in the success callback.

How to handle jSON XMLHttpRequest response?

I'm trying to control the json response I send back to the client but didnt know exactly how..
Here is a simple demo:
js code
xhr = new XMLHttpRequest();
xhr.open("POST", "page.aspx", true);
xhr.send();
// handle the response with xhr.responseText
.cs code
bool success = false;
string message = String.Empty;
// Create JSON Response
var jsonData = new
{
success = success,
message = message
};
Response.Write(jsonData);
The problem is that when I look on the xhr.responseText I see:
"{ success = False, message = }
<!DOCTYPE html PUBLIC ....
....
..
"
You want to do Response.Clear() and then Response.End() after writing the jsonData.
Then you'll need to handle the JSON response in javascript. I recommend Crockford's JSON library.
I also recommend using jQuery's $.ajax() function rather than hand-rolling your own XHR calls.
PS. Ajax calls would be better made to either ASHX resources or PageMethods/WebMethods declared on your ASPX page. Better still, abandon webforms and use ASP.NET MVC with JsonResults returned from your Controller.
PPS. If you do end up using WebMethods, this article is excellent.
You need to Response.Clear() to clear the response before Response.Write
Your cs code is not generating valid JSON (in addition to it displaying other things after the JSON data). All JSON descriptors must be double quoted, and so must any string values. Values are separated from their descriptors by colons. Example:
{"success": false, "message": "It didn't work"}.
Have a look at http://json.org/ for libraries to use with specific languages.

Categories

Resources