Ajax post with a file return - java

Is there a way to return a dynamically server-side generated file, which was fetched from a ajax post structure?
Writing a small web mvc project, which generates a list of data(the data is generated from a complex aggregation query and cannot be called from id or whatsoever), and come up to the part on which i want to export some selected parts to a file and download it.
How does it work:
1. On the page i select some fields with key data(using JQuery DataTable)
2. Send it to a controller(Spring to be precise)
3. Generate a bytestream and return it as a HTTPResponse with "Content-disposition", "attachment" header.
Thing is that i select the lines and form the needed data using JQuery->Ajax, so the result of the Controller->Post stays inside the javascript part, not giving me a "Save as...".
I'm already thinking of a temporary directory or something, but saving option for the last.

Unfortunately you can not get file through ajax, but you can achieve it by generate form dynamically and submit it. As per our comment discussion for generate form and submit it you can do something like this.
function autoSubmitForm(method, url, post_data) {
var element = document.getElementById("virtual_form");
if(element != null )
{
element.parentNode.removeChild(element);
}
var form = document.createElement("form");
form.setAttribute("id", "virtual_form");
form.setAttribute("style", "display:none;");
form.method = method;
form.action = url;
for(i in post_data)
{
var element=document.createElement("input");
element.value=post_data[i];
element.name=i;
form.appendChild(element);
}
document.body.appendChild(form);
form.submit();
}
autoSubmitForm('POST','your_url.php',{id:"xyz",other_input:"input value"});
Here {id:"xyz",other_input:"input value"} is object of post data you can define it dynamically pair of field name and value of field. pass it in function.

Related

REST web application: what is the role of XML/JSON?

I am currently learning about REST applications, and particularly Java implementations of REST.
I am unsure of what role JSON or XML plays in in REST?
An example to show my current understanding:
User clicks a button on front end.
User is re-directed to a URL e.g /user/{userid}
Java method in service class calls repository (e.g. Crud Repository) class to retrieve data
Repository pulls data from db (e.g. about that specific user)
data passed back to service class and is then shown on the UI to user.
Where does JSON or XML fit into this process?
If we divide your 5th step...
1) data is returned from service in a certain format
2) UI receives it in that format and display it on the screen.
This format is XML or JSON or even plain text. This is the Accept type you mention when making a call from UI, and set the response header in service.
JSON stands for Javascript Object notation, hence if the response is in JSON format, you can directly use it as a javascript variable by just parsing it using JSON.parse. The Accept type is actually depends on your requirement. For most of the cases JSON is preferred, as it is easily converted to JS object.
It is the format that the data is returned from the service to the front end.
The transmission of data between the front end and the api is done in JSON and/or XML.
So, simplisticly...
the user asks for some data, through some web page, and the web page asks the RESTful API for the specific data, the api sends the web page the data as JSON, then the web page manipulates that and displays it or does whatever it needs to do with that data.
That is a general way to describe its role
A Method inside the controller is shown below which give json response
#RequestMapping(value = "/getSomething", method = RequestMethod.POST)
public #ResponseBody String getSomething(HttpServletRequest req)
{
JSONArray jsonArr = new JSONArray();
Collection someList = new ArrayList();
someList = someService.getsomeList(req); // here you get the response from service class to controller
Iterator iter = categoryList.iterator();
while (iter.hasNext()) // iterate the colleection
{
JSONObject jsonObj = new JSONObject();
SomeClass someObj = (SomeClass) iter.next();
jsonObj.put("name", someObj.getName());
jsonArr.put(jsonObj);
}
return jsonArr.toString(); // return jsonstring as response
}
This is how it can be processed in view (Say JSP). Here an ajax call made to controller and response set to the field in the page.
$.ajax({
url : "getSomething.htm", //request send to controller
type : "POST",
data : {
'someData' : data
},
success : function(data) {
var arr = JSON.parse(data);
response($.map(arr, function(item) {
return {
value : item.name, //setting the value to the view
};
}));
}
});
Hope this helps!
As other have said, in your example JSON/XML fits at the end of the chain (almost), when data is returned from the server to the client.
Think of JSON and XML (and other formats) as a type of box. Some boxes are made of plastic, some are made of cardboard since they serve different purposes.
JSON/XML are types of "boxes" for the data you are sending/requesting to/from the server.
In your example:
User clicks a button on front end.
User is re-directed to a URL e.g /user/{userid}
Java method in service class calls repository (e.g. Crud Repository) class to retrieve data
Repository pulls data from db (e.g. about that specific user)
Data from DB is "translated" from the server's data format ("type of box") into a more common format (like JSON or XML)
Data in JSON/XML format is sent to the front-end for displaying purposes
Think of it this way: if there wasn't a common format for people/systems to refer to, then if you query an Oracle database you would need to be able to understand that format. If you then had to query a Sybase database, then you would need to be able to understand that as well.
To solve this, you can pick a "common" format (a box that it's easier to fit in more trucks, as opposed to a box that can only be transported by a specific type of truck) and thus make it easier to "transport" that data around.
So in essence, JSON/XML is just a way of representing data, and as such it can be used to represent data that was originally in other "hard to read" format and make it easier to read or work with.
For example by returning your DB objects as JSON you can display them in a web page because most web page frameworks understand JSON as opposed to very few of them natively understanding Oracle/Sybase formats (there are drivers to do this but it is beyond the scope of this toy example).
You can also use it to communicate with other servers that also understand JSON (like third-party APIs for example) and thus if servers A and B have different data representations (internally one is Oracle backed and the other is Sybase backed) they can still talk to each other using a "common" format like JSON.

Populating a table dynamically with the java web-service returns

I'm trying to implement a basic web application from the values that we are getting from web-service, it will include two datatables, each of them need to be populated in server-side.
For example, web-service have a structure like this ( Let's say these are books)
Firstly i am getting the string GUID value for the objects that i want to get an information, after that i am sending a request with the parameter of this GUIDs to service to get information XML for these book objects that includes name, page and author of them.
But as an important information, my servlet needs to get these values dynamically as soon as the page of datatable is changed, if this datatable will include 30 book ( i will get the 30 guid firstly so i can clarify that ) after that, send one request for 10 of them to show them on first page of datatable, if user clicked on page two, server behind needs to send request for the other group of ten and returns me result to show on the table.
I tried to implement the structure below :
http://www.codeproject.com/Articles/359750/jQuery-DataTables-in-Java-Web-Applications#ServerSideProcessing
but it populates a table with the DataRepository ones with all of them, so with this point of view i can't use it dynamically as i totally requested.
The main need for this, XML return for many objects needs so long time.
So do you know any example link or tutorial such a need for this ?
Thank you for informations in advance!
#Hayra, thanks for providing the Code Project link to the JQuery-DataTable example, it is very helpful. This is something that I might implement soon.
What I understood from the example, the JQuery-DataTable keeps track for you specific parameters that will allow you to return the exact number of records. The specific parameters that you need are "iDisplayStart" and the iDisplayLength". The "iDisplayLength" is set when the user specifies 10 records per page and the iDisplayStart, will is set when the page number changes.
So look at the code in the Code Project example doGet Method, this section of the code returns only the subset of records back to your table.
JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request);
if(companies.size()< param.iDisplayStart + param.iDisplayLength) {
companies = companies.subList(param.iDisplayStart, companies.size());
} else {
companies = companies.subList(param.iDisplayStart, param.iDisplayStart + param.iDisplayLength);
}
try {
JsonObject jsonResponse = new JsonObject();
jsonResponse.addProperty("sEcho", sEcho);
jsonResponse.addProperty("iTotalRecords", iTotalRecords);
jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords);
for(Company c : companies){
JsonArray row = new JsonArray();
row.add(new JsonPrimitive(c.getName()));
row.add(new JsonPrimitive(c.getAddress()));
row.add(new JsonPrimitive(c.getTown()));
data.add(row);
}
jsonResponse.add("aaData", data);
response.setContentType("application/Json");
response.getWriter().print(jsonResponse.toString());
} catch (JsonIOException e) {
e.printStackTrace();
response.setContentType("text/html");
response.getWriter().print(e.getMessage());
}
I hope this help

javascript called but not loaded on page

I am putting in changes to a tool we use, and I'm having trouble getting local javascript files to load in. The jquery library link works perfectly fine:
builder.append("<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>");
But js files stored within the project seem to be returning blank pages.
builder.append("<script src='/SessionInfo/js/session.js'></script>");
The project uses a custom controller that routes requests based on the uri, heres a snippet:
if ( lowerCaseUri.matches("/sessioninfo/v1/userid/?") ) {
UserIDHandlerV2.handleUserIdPrompt(output);
} else if ( lowerCaseUri.matches("/sessioninfo/v1/userid/.*") ) {
UserIDHandlerV2.handleUserIdSessionListDisplay(request, output);
} else if ( lowerCaseUri.matches("/sessioninfo/js/.*") ) {
response.setContentType("text/javascript");
}
Looking at fiddler and chrome tools, it shows 200 responses returning the correct content type, but 0 bytes are transferred and in resources/scripts it shows blank pages.
I would suggest, get rid of the "custom controller that routes requests based on the uri," and use a URL Rewrite filter like Tuckey Urlrewrite Filter
Your problem is obviously that your custom controller doesn't work. For one thing, look at this:
else if ( lowerCaseUri.matches("/sessioninfo/js/.*") )
{
response.setContentType("text/javascript");
}
If there is a request for a javascript file, all you are doing with that request is setting the content type to javascript. You aren't reading the javascript file and serving it.
What you are doing is trying to build your own url-rewriting, and that's not necessary.
You could also just take /sessioninfo/js/.* out of your controller. I'm assuming these are just normal .js files, right? So why are you using a controller to route them? The purpose of a controller is when you need to put backend information on a view, so you send the user to the controller (i.e. a servlet) first and then controller sets request attributes and then forwards to a JSP that simply displays them.
Use HttpServletRequest#getContextPath to append those sources:
builder.append("<script src='" + request.getContextPath() + "/SessionInfo/js/session.js'></script>");

Is it possible to pass a JavaScript Variable to Java code inside a Scriptlet

I have a Scriptlet inside a function , which gets data from a Session and checks for a value inside the Map
Can i pass the User Selected Option which is a javascript variable to a Map ??
function checker()
{
var selObj = document.getElementById('selSeaShells');
var optionselectedvalue = selObj.options[selObj.selectedIndex].value.split(':')[0];
if(optionselectedvalue==''||optionselectedvalue==null)
{
alert('Select a Book');
return false;
}
if (!text_form.quan.value)
{
alert('Enter Quantity');
return false;
}
var selectedbook = optionselectedvalue;
var selectedquantity = text_form.quan.value;
<%
Map cart = (Map) session.getAttribute("cart");
if(cart.containsKey(selectedbook))
{
String quant = (String) cart.get(str);
}
%>
return true;
}
javascript plays on client side and JSP plays on server side.
What you need is you have to make a server request. And send that string a query parameter.
You might misunderstand that jsp and javascript existed on same document. Yes but JSP part compiles on server side itself and JSP output is sent to the client.
So solutions are: either go for html form submit or go for Ajax request.
java processing is done at server side and javacript executes on client side. If you do view source on html page you wont find any map.So you can not pass the javascript value to java code (as java code has already been processed by server and its no more).
If you are really want to pass the javascript value to server side you can take help help of ajax or form submission as Baadshah pointed above

How to open new page and send to it POST data?

From current JSP I need to open new page with sending to it POST data. How I can make it?
In other words I need redirect from one page to another, but I cant use sendRedirect(because only GET) and requestDispatcher(because context of pages are different)
You have to create <form method="post">, fill the fields with respective data and submit it by JavaScript.
But on the other hand, what is your reason for that? There probably exists a cleaner solution.
Just make the behaviour that would happen if the initial POST data is received the default behaviour of the JSP when no post data is received.
e.g (in pseudo code - I don't know Java)
if (is_set(POST) ) {
if(POST == expectedInitialVals) {
defaultBahaviour();
} else {
handleOtherValues();
}
} else {
defaultBahaviour();
}
If you also want to persist the POST data in the page set the values on the relevant form fields in the page in your JSP.

Categories

Resources