show data from servlet in jsp but without override the current value - java

I need to display the data from a servlet in a jsp page.
At the moment I have this:
SERVLET:
Object data = text;
request.setAttribute("data", data);
request.getRequestDispatcher("index.jsp").forward(request, response);
JSP:
<p>result: ${data}</p>
In the JSP there is a simple text box and a send button.
At the moment when I push the send button the response is being overwritten ervery time.
How can I do it that after every search I see the result in a new line?
I want also see the previous searches...
Thanks a lot!

You've got a couple of options:
Send over the current value to the server, do the search and append the new result there, and send back the whole string to the JSP in the Request to display it all again. You'll have to wrap the value in an <input> tag, possibly <input type="hidden"> if you still want to show data in a <p> and not as an input field.
JSP:
<input type="hidden" name="oldData" value="${data}"/>
<p>result: ${data}</p>
Servlet:
Object newData = text;
Object oldData = request.getParameter("oldData");
request.setAttribute("data", oldData + "<br/>" + newData);
request.getRequestDispatcher("index.jsp").forward(request, response);
Store all values of data in the session scope, and just append to it from your servlet. The JSP would have to output the value from the session scope instead of the request. In this example values are stored in a unique concatenated String. It woukld probably be nicer to store each value of data in a data structure, such as a List, and just iterate over it in the JSP so the separator remains in the view.
JSP:
<c:if test="${not empty sessionScope.data}">
<p>result: ${sessionScope.data}</p>
</c:if>
Servlet:
Object newData = text;
Object oldData = request.getSession().getAttribute("data");
request.getSession().setAttribute("data", oldData + "<br/>" + newData);
request.getRequestDispatcher("index.jsp").forward(request, response);

1 .Use an array instead of a simple object in servlet
Populate the array with the new values :Servlet
Traverse the array and display each item where ever you want to display as new lines

You are putting your data in RequestScope you have to add them into the SessionScope in order to see the previous results.
See this example: http://viralpatel.net/blogs/jsp-servlet-session-listener-tutorial-example-in-eclipse-tomcat/.
It is not very good practice to write java code in JSP, so you would want to move the logic into servlet. But this example describes the point you need.

Related

Why won't my JSP page load when I call it via a method in my Controller class?

I'm trying to pass two values from a method in my controller class to a JSP page, the functionality in the controller seems to work but the JSP page won't load. The two values are an average house price and an integer value representing the number of houses returned from a database query. I take in a latitude and longitude value from a different JSP page and they determine the values returned from the database. (I don't want to pass the average house price and number of houses values back to that same JSP page where the latitude and longitude originally came from, but a new page).
In my controller class, I have a debug that prints the results from the database query successfully in my Eclipse console so I know the query works, I've also included a print statement to see if the session contains a value and it prints successfully. So it seems that the values are correct and ready to be sent to the new JSP page however the page I'm trying to load simply won't load and I've tried several different ways to fix this but none work (I'll go into these ways below).
At the moment I'm trying to use HttpSession to pass the values from the controller to the new JSP page like so:
#RequestMapping(value = "/parseHousePrice", method = RequestMethod.GET)
public String parseHousePrice(#RequestParam("latitude") double latitude,
#RequestParam("longitude") double longitude,
HttpSession session) {
// This passes the lat & long into a method that will query the database
// and store the result into the housePrice double varaible
double housePrice = parseHousePrice.ParseHousePrice(latitude, longitude);
// This gets the number of houses returned from the query
// and stores it into the number_of_houses integer value
List<Double> housePriceList = parseHousePrice.getList();
int number_of_houses = housePriceList.size();
// Debug to show the query works successfullt
System.out.println("The average house price for this area is: " + housePrice + " based on " + number_of_houses + " property prices in this area");
// Assigning the values to session attributes
session.setAttribute("houseprice", housePrice );
session.setAttribute("housepricelistsize", number_of_houses);
// Debug that shows the session currently holds a value
System.out.println(session.getServletContext());
// New JSP page I want to pass the values to
return "houseprice";
}
In my new JSP page I try to pass the values from above into the following <p> tags:
<p th:text="${session.houseprice}" th:unless="${session == null}">[...]</p>
<p th:text="${session.housepricelistsize}" th:unless="${session == null}">[...]</p>
Like I said above I've tried various methods of passing the values to the JSP page but none work and the page won't load.
I've attempted to use a model to pass the values through like so:
model.addAttribute("houseprice", housePrice);
model.addAttribute("housepricelistsize", number_of_houses);
I printed the model as a debug using a simple System.out.println(model); and this printed the correct values and names of values.
And I've attempted to create a HousePriceObject entity and create a list of these objects in the controller. I would then use a ModelAndView and return the name of the ModelAndView instead of the JSP page name (houseprice) at the end of the method in the controller class like so:
ModelAndView map = new ModelAndView("houseprice");
map.addObject("housepricesList", housepricesList);
// Return the ModelAndView instead of "houseprice" JSP page
return map;
And use a <c:forEach> loop to iterate through the list and print it on the JSP page but it still won't work.
<table>
<c:forEach items="${housepricesList}" var="HousePrice">
<tr>
<td><c:out value="${HousePrice.housePrice}"/></td>
<td><c:out value="${HousePrice.number_of_houses}"/></td>
</tr>
</c:forEach>
</table>
Am I missing something small here or am I going about this the completely wrong way. As I said the values seem to ready to be sent and I think they will print as soon as the page loads, but the page simply will not load. An advice would be appreciated!
Edit I have other JSP pages loading from the controller when the methods are called, however it seems the fact the particular method highlighted above has a lot more functionality (i.e. taking in data from one JSP page, querying the database, and printing the data to a new JSP page, etc) something stops the houseprice JSP page from opening.
For example, the JSP page will open when I run the method above without all the extra code.
#RequestMapping(value = "/parseHousePrice", method = RequestMethod.GET)
public String parseHousePrice(#Valid HousePrice housePriceObject, BindingResult bindingResult, Model model) {
// houseprice.jsp will open but obviously has none of the data
return "houseprice";
}

Changed select on jsp get null value in servlet

I have a jsp page with a number of selects that are populated using jQuery i.e. they have the <option> tags, they just get it via a function. Each select has some 30 options each.
<form id="target" name="target" action="/project/myservlet" method="get">
<select class="myClass" id="sel1" name="sel1" ></select>
<select class="myClass" id="sel2" name="sel2"></select>
...
</form>
I received these values in my servlet using request.getParameter("sel1") but I'm getting null for the selects that are changed. As in, say I select values from the 2nd, 4th and 5th selects, then these selects get null values in the servlet. Others get the 0th value (default and unchanged) - which is okay.
This can help explain my question. I'm getting null in the next page when I modify the select.
According to this, if I use onload in select, it helps take the updated values to the next page for ONE select. But the problem is that I don't just have one select on the page. I want the updated values to go the next page without a page refresh/going to another page, unless submit for them is clicked. I think the request is not getting updated when the change takes place? Even the url in "get" doesn't get the changed selects.
There is no error as such, just that I am getting the values if the selects are unmodified (defaults). It sends the default values to the next page. When I select another option from the drop down, I get null on the servlet unless I use onchangeto submit the form. But that doesn't work for me since I have many selects. I can't keep submitting the form and going to the next page on every select change.
EDIT:
If it helps, here is my jQuery code:
$(document).ready(function() {
$('select').change(function(){
var v = $(this).val();
$('select option[value="'+$(this).data('old-val')+'"]').prop('disabled', false);
$(this).data('old-val',v);
if(v != "0"){
$('select option[value="'+v+'"]').not(this).prop('disabled',true);
}
});
$('select').each(function(idx,select){
var stateArray = ["Preference No. "+(idx+1),"Bill", "Sally", "Alice"];
$.each(stateArray, function(iIdx, iItem){
$(select).append('<option value="'+iIdx+'">'+iItem+'</option>');
});
});
$( "#target" ).submit(function( event ) {
alert( "Handler for .submit() called." );
});
});
EDIT 2: Servlet:
public class Preference extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response) {
response.setContentType("text/html;charset=UTF-8");
try {
PrintWriter out = response.getWriter();
String sel = request.getParameter("sel1");
}catch(Exception e){ }
}
}
You need to add <option> tags into your <select> tags.
Each <option> must have value attribute like this:
<option value="3">Apple</option>
Value from the value attribute of the selected option will be value of your <select>. You will get it on server-side by name as usual.
The selected options were disabled from all the select elements in my jQuery. I had to modify the jQuery a little. Disabled elements are not carried forward in a form. On modifying the jQuery to not disable the options, the problem was resolved. Had to take a bit of a help to recognize and correct that.

how to get data from server without refreshing the page

I am new to web development. My job is to get data from the server and plot them using amcharts every 1 or 2 seconds.
This is what i have so far:
<form id="getdata" role="form" method="post" action=#routes.DataApplication.get_data()>
<input type="text" name="device" id="device">
<input type="text" name="type" id="type">
<button id = "submit" type="submit">Submit</button>
</form>
Once I enter device and type and click the submit button, it will run the Java method get_data(). The method will search the database and return data that matches the device name, but the thing is it will display is the data in another page, for example www.somepage/getdata. The above html is in www.somepage/data page.
I tried using jquery .post() but the thing is it requires an url, I tried passing /getdata to it but didn't work.
My question is: is there a way to save the data we get from the #routes.DataApplication.get_data() action without reloading the page?
By the way, I am using play framework to develop the webpage.
UPDATE
Ok, making some progresses now, I tried using ajax post, but the data return (in console) is like this:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
Here I got 11 objects. If i don't use ajax post (using the original post form method), I get 11 data points too.
Here is my code:
<script>
$('#driver').click(function(evt) {
var dataabc = $('form').serialize();
console.log(dataabc);
$('#errors').hide();
$.ajax({
type : 'POST',
data : dataabc,
url : '#routes.DataApplication.get_data()',
success : function(data) {
alert("good");
console.log(data);
},
error : function(result) {
setError('Make call failed');
}
});
return false;
});
</script>
What get_data() does is just take the user input data (which is the form) and get corresponding data from the database and return ok(node);. This node is JsonNode
Any help would be appreciated..
Since you are getting an array of objects back in javascript and it is stored in data. You can loop through it and display the content is some div tag.
Example:
Create an empty div to populate the data after a successful ajax call.
<div id="mytextarea"></div>
Then in your ajax success, instead of printing to console you would loop through the array and append the data to the innerHTML of the div tag like so...
var myTextArea = document.getElementById('mytextarea');
for (var x = 0; x < data.length; x++){
myTextArea.innerHTML = myTextArea.innerHTML + data[x].id + '<br/>';
}
Edit 1: I see you know your object's attributes so I updated the code to append just id to the text area.
It will be very helpful to tell us what exactly the url returns in response. Usually that should be XML or JSON.
You can use FireBug or any other developer tools to catch the response and post it here.
IT doesn't decide what to return - it's YOU!
If you'll return for an instance JSON object in your get_data() action, your AJAX will receive a JSON, check yourself:
public static Result get_data(){
ObjectNode node = Json.newObject();
node.put("hello", "world");
return ok(node);
}

Return Java list into jQuery object

Basically I have an Ajax request instantiated by a button where it is passed to my controller, and then that controller returns a list of objects. I initially was thinking whether this could be done by loading the returned ajax object into the JSTL forEach loop, but I think that cannot be done after some research.
This is my ajax request which loads sighting based on a value:
//edit the sighting based on the username value
$(this).on("click", ".edit_sighting", function(){
$username = +$(".edit_sighting").val();
$.get("${pageContext.request.contextPath}/getSighting/" + username, function(sightings){
// load returned object somewhere
});
});
This is my controller which handles the ajax request and responds returning a list of objects 'sighting':
#RequestMapping("/getSighting/{username}")
public #ResponseBody List<Sighting> getSighting(Model model, #PathVariable String username) {
List<Sighting> sightings = sightingsService.getSightings(username);
model.addAttribute("sightings", sightings);
return sightings;
}
And essentially I would like to load the returned objects into a for each loop or something that would display the object fields. for example: something like that.
My for each loop:
<c:forEach var="sighting" items="${sightings }">
<c:out value="sighting.name"/> <!-- load some sighting value -->
</c:forEach>
So essentially what I am trying to achieve is, load multiple or one 'sightings' into a modal type thing when a button is instantiated.
You can't use JSTL for this since JSTL is executed on the server before a page is sent to the client. What you could do is render the HTML on the server and return a HTML document (instead of JSON). So the solution would be to define a JSP view which uses JSTL to render the list and change the AJAX request to accept HTML.
The other solution is to add a JavaScript based template engine and do the template rendering client side.
Or do it manually with jQuery. If you have
<ul id="sightings"></ul>
then you can
var sightings = $('#sightings');
sightings.empty();
$.each(sightings, function(index, e){
var li = $('<li>');
li.text(e);
sightings.append(li);
});
The response to the ajax request is returned to the client, which does not have access to server side mechanisms such as JSTL. The code should use Javascript/jQuery on the client side to display the new DOM elements.
So if you had the following HTML on your page:
<ul id="sightings"></ul>
The callback would look like:
$(this).on("click", ".edit_sighting", function(){
$username = +$(".edit_sighting").val();
$.get("${pageContext.request.contextPath}/getSighting/" + username, function(sightings){
var output = "";
for(var i = 0; i < sightings.length; i++){
output =+ "<li>" + sightings[i].name + "<\/li>";
}
$("#sightings").append(output);
});
});
This will build a String containing HTML which has an li for each sighting. The HTML is then appended to the DOM as children of the #sightings ul.
Since you are using ajax so the page will not reload once your request returns the response so anyway this code
will not work.
what you can do is instead of sending a list you can send a JSON array as response and each array element will have a JSON object having all the required properties and this array can be iterated after the response is received.

Getting null values while using request.setAttribute and get

I need to pass a variable from Admin.java file to index.jsp. I get the value when I print it in Admin.java. I need to pass that value to another variable which needs to be sent to index.jsp. This new variable gets null value.
The code in Admin.java is
public string static rest;
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
{
SemanticSearch semsearch = new SemanticSearch(request.getSession());
semsearch.loadData(REALPATH + RDFDATASOURCEFILE1);
String res=semsearch.searchForUser(userName, password);
System.out.println("The value of res been passed is "+res);
request.setAttribute("rest", res);
System.out.println("The value of rest is "+rest);
request.getRequestDispatcher("index.jsp").forward(request, response);
if(res != null)
{
request.getSession().setAttribute("access", true);
System.out.println("Admin:doGet:login:true");
response.getWriter().write("existsnoadmin");
return;
}
Output:
The value of res been passed is C Language.
The value of rest is null.
As per the questions asked in stack overflow we need to use forward or redirect when we need to send the value to jsp page. But in my case, I am trying to return value from a function so I do not know whether the way I am trying to do in the above code is right or not.
The code in index.jsp is:
if(response=="existsnoadmin")
{
alert(response);
alert("The value obtained by the admin.java is " +request.getAttribute("rest"));
out.println("The value obtained by the admin.java is " +request.getAttribute("rest"));
alert("we have done in index.jsp");
}
The output is that I am getting the alert box which says "existsnoadmin".
But I am not able to get the value of rest here nor in Admin.java.
What is the mistake I have done here? Please help.
Regards,
Archana.
You say that the code in the JSP is this:
if(response=="existsnoadmin")
{
alert(response);
alert("The value obtained by the admin.java is " +request.getAttribute("rest"));
out.println("The value obtained by the admin.java is " +request.getAttribute("rest"));
alert("we have done in index.jsp");
}
I'm having problems understanding what this really means.
If the above code is Java code that appears inside scriptlet tags <% ... %>, then I don't understand how alert(response); is showing you anything. In fact, it should give you a compilation error in the JSP.
On the other hand, if the above is Javascript code that is embedded in the page that the JSP generates, then
request.getAttribute("rest") cannot possibly work ... because the request object that you set the attribute on does not exist in the web browser, and
out.println(...) cannot work because the JspWriter does not exist in the web browser.
Either you have not transcribed the JSP excerpt accurately, or your Java and/or Javascript doesn't make sense.
Based on your comment, I think you need the following.
if(response=="existsnoadmin")
{
alert(response);
alert('The value obtained by the admin.java is ' +
'<% request.getAttribute("rest") %>');
// The value obtained by the admin.java is <% request.getAttribute("rest") %>
}
Or if you want to get rid of the scriplet stuff ...
if(response=="existsnoadmin")
{
alert(response);
alert('The value obtained by the admin.java is ' +
'${requestScope.rest"}');
// The value obtained by the admin.java is ${requestScope.rest"}
}
If you want the stuff that I've turned into a // JS comment to be visible on the page, you been to move it to some content part of the HTML. Currently it is (I assume) inside a <script> element, and therefore won't be displayed.
The key to all of this black magic is understanding what parts of a JSP are seen/evaluated by what:
JSP directives e.g. <# import ...> are evaluated by the JSP compiler.
Stuff inside scriptlet tags e.g. <% ... %>, EL expressions e.g. ${...} or JSTL tags e.g. <c:out ...\> gets evaluated when the JSP is "run".
Anything generated by the JSP (HTML content, embedded Javascript) is displayed / executed in the user's browser after the HTTP response has been received.
Now is it neccessary to use the request.dispatcher....forward command in admin.java.
Your primary servlet can do one of two things.
It can use the request dispatcher to forward the request to your JSP. If it does this it can forward additional values by setting request attributes.
It can open the response output stream and write stuff to it.
It should not attempt to do both! (I'm not sure exactly what will happen, but it is likely to result in a 500 Internal Error.)

Categories