I am using JSP to extract some data and then using JavaScript to display data in form of some graphs. But now I want to filter data for eg: Filter data according to some manager or filter data on basis of salary.
Since I am getting the data from JSP, I don't want to send a JSP request everytime I need to filter some data. How can I do this using JavaScript and where and in which format can I store data in JavaScript after getting it using JSP?
Store the data as JavaScript objects. There are plenty of JSON parsers/marshallers in Java. Choose the one you like the most, and do the following:
in the servlet/controller:
String json = transformToJSON(myGraphData);
request.setAttribute("json", json);
in the JSP:
<script>
var graphData = ${json};
// graphData is a JavaScript object containing the graph data
</script>
Related
Is there an easy way to send HTML from a servlet to a JSP, using AJAX.
I've already figured out how to make AJAX work with servlets dynamically, but now I want to press a button on a form and generate HTML based on text-input.
Is it possible, and if so, how, to send just pieces of HTML to an existing HTML page?
Example,
I have a basic form where you can input your age, and based on the age the text has a different size/color. So, you send for example, 25 as your age to the servlet, and it send back a piece of HTML like this <p STYLE="font-size: age;"> to the page.
Through ajax call you can get the output result either a string, html or a Json object that will be parsed and results can be displayed over JSP/HTML. So for sure you can send html code segment from servlet to jsp through ajax call.
For example you can use this approach--
1. Take a string variable in your servlet.
2. Put appropriate html string as per your conditions in this string variable
3. send this string as a response from servlet like:
response.setCharacterEncoding("UTF-8");
response.getWriter().write("your string variable here");
4. In your ajax call do like this:
success : function(dataString) {
document.getElementById("containerId").innerHTML=dataString;
},
where containerId is the id of html element (like div or span) where you want to display output html.
The easiest approach, without client-side javascript libraries, would be to point an HTML form to an iframe, just like
<iframe name="myIframe"...>
<form target="myIframe"...>
And submit your form as many times as necessary. The HTML returned by the servlet would load itself in the iframe element.
If you like AJAX and client-side javascript libraries, you can find very easy programmatical ways to do this in jQuery and similar libraries.
Basically your servlet can generate any kind of content, e.g. JSON, HTML etc.
You'd then send that content back to the client and integrate it into the page.
How that is done depends on the type of content.
Example:
You issue an AJX request (e.g. by using jQuery's ajax functionality) and your servlet generates plain html. When your JavaScript receives the anser you just replace the relevant part, e.g. by replacing the content of some defined element.
If you used JSON instead, your servlet might send data only instead, e.g. a font size based on the age as in your example. You'd then use JavaScript to access that JSON data and perform relevant operations, e.g. by changing the style of the paragraph.
I have a very complex scenario where i need to change the java objects(basically HashMap ) from jquery get Request and get the response and print that in the jsp. User can send number of request and get seperate response from servlet based on request and display the data.
after every request i have to put the map in session and than in another request i get the same in session and do the updates and put it back in session.
JqueryGet(parameter) to Java.
Updating Hashmap according to parameter.
Putting hashmap in session . ( session.setAttribute("map",map))
sending response back to Jsp in jquery and print results in jsp.
Than another request send to Java .
it will get the map from session session.getAttribute("map",map) and than update the map based on new request .
Put the map again in session and so on....Than i have a submit button finally which will show the new data on the page and than update the server.
Is this the right approach ? My functionality is working fine as of now in Dev environment. But i am worried whether i should use DOM. if i will use DOM it will be very complex since i have to manipulate much values of Hashmap based on request.
Here is the jquery code :
$.ajax({
url: '<%=portalContext.createTemplateProcessURI()%>'
+'?s1='+ $("#networkBox1").val()+'&box1=Box1&tick=add&val1='+ allvs+'&s2='+ $("#networkBox2").val()+'&box2=Box2&val2='+ allvs,
type: 'get',
dataType: 'text',
async: false,
success: function(data) {
Processbox(data); // This function displaying the result.
}
});
dude, first of all, I think after you get your data from back end side, your java object has already changed to json object. I think your flow has no problem, because once you change to DOM, then all the data is send through front side but not back end side, if you use session, actually you handle your data at back end side, for me, I prefer the second one.
Here is my idea:
1.set a dom object in your page with the data get from your ajax
$(domId).val(value get from ajax);
2.If your don't want to show the data, use hidden type input in your jsp form
<input type="hidden" id="domId" name="domName">
3.once you click submit button, handle your data in your servlet
String data = request.getParameter("domName");
session.setAttributes("sessionData", data);
Hope this will help you.
I have tried different things but i am not able to do this.
I am very new to jquery json and ajax. I wrote a servlet which connects to my databse and retrive user ids from the table. I wrote a jsp and which has a text box that takes input text and refines the results on each key press I want to do it in a html page using jquery ajax by sending json object from my servlet. can someone give me an example for this scenario.
Thanks in advance.
http://jsfiddle.net/tAjNz/
<input type="text" />
<select id="autoPop" multiselect="true"></select>
<script>
// define a data source (ajax or on page load);
myJson = [{value:1,text:'Item One'},{value:1,text:'Item Two'},{value:1,text:'Item Three'},{value:1,text:'Item Four'}];
$('input[type="text"]').keyup(function(){
//Optionally update the data source when a user starts typing or use the predefined source.
//Populate the select list
$sel = $('select');
$sel.html('');
var $this = $(this);
$.each(myJson,function(k,v){
if(v.text.toLowerCase().indexOf($this.val().toLowerCase()) > -1) {
$sel.append('<option value="' + v.value+ '">'+ v.text+'</option>');
}
});
});
</script>
I am new to Java EE programming. Following my understanding on jsp. Corret me if I am wrong
- JSP pages are converted to servlet first then to html and resulted html page is displayed in browser.
Now suppose jsp page is displayed in browser i.e now it is html page and I have a java List which have names or some sort of data that I want to print on the currently loaded page. I can get the List object using ajax but the how will I display it on html as html cant render java collections.
Correct me wherever I misunderstood the flow or basic concepts.
Thanks.
You could use ajax (using jQuery would be easy) to make a call to your Servlet
function callMe(){
$.ajax({
type: "POST",
url: "/someServlet",
data: { param1: "val1" , param2: "val2" }
}).done(function( data) {
//TODO
});
}
Now on Servlet, in doPost(), Use Gson to generate JSON representation for your collection
String parameter1 = request.getParameter(param1);
String parameter2 = request.getParameter(param2);
//call to service to generate the collection
//for example List<Employee>
List<Employee> employees = someService(parameter1, parameter2);
//using google's gson
Gson gson = new Gson();
String json = new Gson().toJson(employees);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Now we have response in javascript function as a array of javascript objects, So modify it to
}).done(function( data) {
//some processing for display
var len = data.length
for (var i=0; i<len; ++i) {
var employeeFirstName = data[i].firstName;
var employeeLastName = data[i].lastName;
//set it to some DIV, or do the processing you want
}
}
});
Also See
How to call a java method from jsp by clicking a menu in html page?
You need to send the contents of your list as text to the user's browser (which is what normally happens).
A convenient format for transferring the contents of the list between the browser and the server is JSON, due to its simple readability with JavaScript and easy generation on the server.
You can then display the returned text in whatever way you like using JavaScript.
A JSP is compiled into a java servlet class, which can handle HTTP requests. When the servlet is deployed to an application server HTTP requests are passed to the servlet for handling: an HTTP response is generated which normally contains some HTML, a status code, etc.
So it's the java code in the servlet which loops over your list and presumably generates the appropriate HTML to render that list in a browser.
Whether or not it's an AJAX request or not doesn't really matter. Rather than rendering a full HTML page, the AJAX request would probably be handled by a different servlet, which generates only a partial page - perhaps just the <ul><li>...</li></ul> to render your list. The javascript in your HTML page can then take care of updating the user interface by replacing the old version of the list.
I'm using Spring MVC for my web application. I'm implementing the file upload functionality. Following the tutorial, I was able to send the uploaded file to server through submit action of input type of "file". Then I parsed the uploaded xls file at server side and need to send parsed data (3 lists of custom objects) back to the same form to display. I sent the data back through ModelAttribute.
However, my problem now is that on the client side, I need to use those lists of custom objects in my javascript, but I can only retrieve each field of the custom objects through jstl tag library but I cannot get those custom objects in my javascript where I need them for other logic implementation.
Then I have tried an Ajax file upload plug-in because ajax call can return JSON response which objects can be used in Javascript. But cannot get the plug-in work properly.
I have been stuck on this problem for several days>.< Can anybody help on this? Either a solution on using ModelAttribute in Javascript or a Ajax call solution is ok. Thank you very much!!!
Is there any reason why you can't simply "flatten" your model objects into HTML and then access them from Javascript using the DOM API?
You said you return 3 lists of custom objects. So how about for each list, you build up a (hidden) HTML table, for example if you have a list of Person objects in a ModelAttribute called people:
<table id="people-table">
<c:forEach var="person" items="${people}">
<tr id="${person.id}>
<td class="person-name">${person.name}</td>
<td class="person-age">${person.age}</td>
<td class="person-height">${person.height}</td>
</tr>
</c:forEach>
</table>
Now in your Javascript, you iterate over the rows in people-table, doing whatever you need to do - for example using jQuery:
$("#people-table tr").each(
var personId = $(this).attr("id");
var personName = $(this).find("td.person-name").text();
// etc, etc
// Do something with these as required
);
It's possibly not the most elegant solution but it's easy to debug at least - you can always just inspect the table with Firebug etc to see if the data is correct, and from there you'll know whether to continue debugging the server-side or in the Javascript.