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.
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 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>
I am a building project in which I am using java-beans,jsp and servlets. I need to send the response to the client on the same page from where request was made with a slightly modified html. But when I(server) sent the request to the jsp page, the controls in the form are getting reset to their original value. But I don't want to override the user's input after the request was made. One way to achieve this is to take value of the property for each control in the form when request is made and then set them again while responding. Actually there are a large number of controls in my form, taking values of each doesn't seem efficient.
So is there some other way to keep the form in the jsp file unchanged while responding to the client.
you can use ajax for what you are asking, or you have to save the data on form submit, in session or some place and set them back again while responding. Apart from that I think there is no other way you can retain form data even after page reload.
Thanks
Chakri
Why dont you use iframe ? so you dont have to refresh the whole page when the request is made to the same page.
Instead of making the action of the form to the same page, call a javascript function that set the parameters in the link and then
var f = document.getElementById('iframe');
f.src = 'newlink';
f.contentWindow.location.reload(true);
This populated the iframe with the latest content
function openOffenderInfo(i)
{
$.ajax({
url:'../loginServlet',
type: 'POST',
success: function(data)
{
alert("reset your div values in this block");
.... for example .....
documnet.getElementById('reloading Div').innerHTML=data;
},
error: function(data)
{
alert("error");
}
});
}
URL : c=name of the servlet you want to call
this servlet calculates the data and gives the new data you want to reset in your div
success : this is the function which will be executes if your ajax call is made successfully
so you can set the values of your reloading part inside this function
I hope this might serve you the purpose
I want to send a JSP page which consists of some divs and table as part of AJAX response from spring framework, is there any way to send JSP as a response of AJAX call
Sending JSP by AJAX makes no sense, it is basically the HTML generated by a JSP that is sent over to the browser through AJAX, as rightly pointed out by the lost.
You do not need any server-side coding for this. All you need is to write some JavaScript on client-side to receive your HTML asynchronously. For this, I would recommend using some JavaScript framework like jQuery, otherwise, it would make your life hell.
Assuming that the page you want to access by AJAX has the link http://domain:port/mypage.htm. First you need to include jQuery in your base JSP (JSP in which former page has to load by AJAX):
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery.js"></script>
Then you need to call jQuery's AJAX function:
$(document).ready(function(){
$.ajax({
type:"GET",
url: "http://domain:port/mypage.htm",
success: function(data) {
// Now you have your HTML in "data", do whatever you want with it here in this function
alert(data);
}
});
});
Hope it helps!
Yes, there's no magic to this though. In your Java AJAX handler just return a forward or redirect to the JSP page you want. The response will then be available as the responseText in your AJAX callback.
You can use JSP to generate just the elements you need as a sort of incomplete HTML fragment then returns this from your server-side handler. Then in your JavaScript callback you can insert the fragment into your existing HTML like this
element.innerHTML = resp.responseText
//element is the parent you want to insert to
//resp is the parameter supplied to your callback