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.
Related
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.
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
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>");
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
I'm new to jQuery and am not quite sure how to do the following:
I'm using EasyUI TreeGrid and want to display dynamic data rather than providing static data from a .json file. Currently, the code I'm using is as follows:
$(function(){
$('#test').treegrid({
url:'treegrid_data.json',
and so on. Instead, is there any way I can pass an ArrayList or bean object or something directly?
Thanks in advance.
instead of getting the static json file.. point the url to a page where you are getting a dynamic value.. say dynamic.php
url:'dynamic.php',
....
and do your stuff like mysql connect.. or getting the dynamic datas in dynamic.php and return it as json....
dynamic.php
//do your stuff like getting dynamic datas in array..
$dynamicarray= $yourDynamicDataArray..
echo json_encode($dynamicarray);
this should do...
Figured it out...instead of pointing to a static json file, specify the url as url: 'dynamic.jsp' or url: 'dynamic.java' pointing towards a jsp or servlet respectively(since we are developing a web application). In that page simply get the json string, say, as an attribute and print it using out.println(jsonString). Do not include any HTML tags whatsoever or you won't get the desired output.