how to create a function in jsp - java

I have created a web page called allmeters.jsp. In the page I have a hyper link
<%=rs.getInt("meterid")%>
In my second page called demo.jsp, I have one label and search button and I am accessing the label value from allmeters.jsp by using
<label name="name1" value="<%=request.getParameter("mid")%>">
<font size="4">Meter ID : <%=request.getParameter("mid")%></font>
</label>
I am getting mid value from allmeters.jsp.
Now the problem is by using mid value I want to retrieve the data from MySql table after clicking on button. How to create a function in JSP and how to call that function in a button using JSP.

Well, just pass the mid value first to a servlet instead of passing it to a jsp directly. And run your query there using mid value and send the result in a arraylist or something according to your result to demo.jsp and then print them.
or
you can simply use scriptlets itself in the page to create your function and get the values..But i don't suggest you to do that..Try first method instead..

Related

clear() function does not erase the default value of input web element

I am a very beginner to use Java and Selenium to write a test.
I have this web element:
<input type="number" name="yield_target"
placeholder="Yield Target" value="0.00" min="0" step="any">
But I can not clear it by:
WebElement we = wait.until(ExpectedConditions.visibilityOfElementLocated
(By.xpath("//input[#placeholder='Yield Target']")));
we.clear();
But I can write into it, for example if I use:
action.sendKeys(we, "223").build().perform();
it will be 0.00223 instead of 223.
I'm not sure why we.clear() isn't working but you can clear and set in a single call (assuming that JavaScript on the page does not prevent you from using CTRL+A to select all of the contents of the number input field):
we.sendKeys(Keys.chord(Keys.CONTROL, "a"), "223");

Update single JSP page element without using form

In my Struts2/Java application, I am allowing the user to send in data to the application from JQGrid. I am using the "saverow" function to loop through each selected row and submit the edited cells. This function is in a separate js file which is included in my JSP.
function editRows(){
for (...){
...
...
...
jQuery('#myGrid').jqGrid('saveRow,rowID,false,null,null,aftersavefunc);
}
getResponse();
}
After the data is submitted from this function, a number of class variables in my action class are updated. I use the aftersavefunc to set the value of hidden jqgrid cells (jqgrid 'setCell') so I can recall them later from the grid.
I have additional values which are simply displayed in a div. These values are also updated within the application after it has been executed. At the time that I'm executing the editRows() function mentioned above, the following div is already visible and displaying a value for each of the fields within the div. These initial div values are the result of a previous form being submitted. Here's what the div looks like in my JSP.
<div id="headerBar">
<table>
<tr>
<td>Total Items: <s:property value="strutsActionName.totalItems</td>
...
...
...
</tr>
</table>
</div>
So for instance, when my function editRows is being executed, the div is already showing a value for "totalItems" on the webpage. It would just look something like this:
Total Items: 5
After function editRows has executed, the value of "totalItems" has been updated within the application. The java action class has the latest value for totalRows.
The editRows function is calling another function getResponse() when the loop has finished. The getResponse function is for obtaining the hidden jqgrid values that I set using the "aftersavefunc" parameter of "saverow". It uses the jqGrid('getCell') to get the updated value of those hidden jqGrid cells.
I want to have the getResponse() function to also refresh the value of "totalItems". This value is not in a jqGrid. I need to refresh the individual field and obtain the updated value. For instance, after editRows() has completed, the value of "totalItems" could have been doubled to 10 from 5.
Within my getResponse() function, I've tried updating this value by using the following, but it hasn't worked.
document.getElementById('headerBar').reload
I just need to update the values in this div without submitting a form.
The property tag is processed on the server side so it would not be updated until request is sent to the server.
As i see it the best way for doing this would be to put the property value inside an element with an id like span or p and then use document.getElemenrById to retrieve that element element and change its content from javascript after retrieving its new value.

access javascript variable value in jsp

I want to pass a javascript variable to my servlet, where I need to use it.
In javascript, the variable count returns the rows of my table and I can show count in the jsp, using $('#counter').html(count); , but I cannot pass count's value to my servlet. I tried document.getElementById("hiddenField").value=count; but it doesn't work.
Javascript
<script>
var count = 3;
$(function() {
$('#counter').html(count);
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
});
});
document.getElementById("hiddenField").value=count; // ???
</script>
JSP
Count: <span id="counter"></span> <%-- it works --%>
<form method="post" action="newteamsubmit">
...
<input type="hidden" id="hiddenField" name ="countRows" />
<input type="submit" name ="button1" value=" Submit " />
<input type="submit" name = "button1" value=" Cancel " />
</form>
Servlet
String cr = request.getParameter("countRows"); //I' ve tried also to convert it
// to int, but that's not my problem, since I cannot pass the value as a start
I've spent many hours, trying to figure out how I can access a javascript variable in jsp, but I haven't found any solution.
Thanks in advance.
The count is computed each time the add button or the delete button are clicked. But you only set the hidden field value once, when the page is loaded (and its value is thus hard-coded to 3).
You must set it, as you're doing for the #counter element, in your click handlers:
$('#addButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
$('#deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
Also note that you're repeating exactly the same code in two click handlers here. You should do that only once, for the two buttons:
$('#addButton, #deleteButton').bind('click', function() {
count = document.getElementById("dataTable").getElementsByTagName("tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
or even, since you're using jQuery:
$('#addButton, #deleteButton').bind('click', function() {
count = $("#dataTable tr").length;
$('#counter').html(count);
$('#hiddenField').val(count);
});
document.getElementById('hiddenField').value is not set because it is outside your document.ready. Put it inside your click handler.
Make sure of 2 things -
There is only one element with id "hiddenField" on your page.
Make sure that the following code
document.getElementById("hiddenField").value=count;
is after in the page.
Just make sure that js sets the hiddenField after the element has been loaded.
3. check for any JS errors using Javascript console.
Rest it looks good
The main issue here is that you are trying to access from the server, a variable that only exists at the client. To access that variable you have to send it from the client to the server using AJAX to trigger some form of API in the backend. REST, SOAP or XML-RPC are common technologies used for this sort of thing. The server side code is used for generating the UI and providing it with data from a database or such. Commonly the UI is generated only once, and then the client calls the server asking for more data in response to user actions, like clicking a button.
Imagine a table filled with information about books: title, author, publish date etc. This table can get quite large, and traditionally this table will be split up over several pages and possibly a dynamic filter. To save bandwidth and increase the user experience by not loading the entire page from scratch you can use AJAX to ask the server for just the relevant data. Doing so the page updates dynamically and smoothly for the user.
In your case, you can use this technique to update the server every time the user clicks the button.
If however you are really just looking to update a hidden field in a form with a value as the user performs actions, and the server wont do anything with it except show it you can just use javascript.
Remember also that the request variable contains the data you post to the server when you submit the form. The servlet will get the data after the client has posted it, which is after the JSP has generated the page. The sequence of the code execution is JSP -> Javascript -> Servlet.
Hope this helps!
You can use this way:
document.forms[0].countRows.value = counter
Hope this will help you

dynamically update textbox value from database when combobox value is changed

Here is the situation. I have a drop down menu. The option sin this drop down menu are being populated by fetching some values from the database. To do this following is what i have done.. :-
<select name="product_list" onchange="selectProduct(this.value)">
<option value="none">Select one</option>
<%
List<String> options = new ArrayList<String>();
DynamicCombo comboBox = new DynamicCombo();
options = comboBox.generateComboBox();
Collections.sort(options);
int tempVar = 0;
while (tempVar < options.size()) {
out.print("<option value=\"");
out.print(options.get(tempVar));
out.print("\">");
out.print(options.get(tempVar));
out.print("</option>");
tempVar++;
}
%>
</select>
DynamicCombo is a class that has a method called 'generateComboBox()'. This method simply returns an array list containing all the values that are fetched from the database, which is what i need to show in my drop down box in the front end (jsp page). On my jsp page i simply iterate through this list and print it as options appropriately.
This works absolutely fine.
Now i have another text box on my form, say 'textbox1'. Now the requirement is that this text box value should be updated depending on what the user has selected from the above drop down box.
So for example if the user selects 'prod1'(which is a primary key in the backend database table) option from the drop down box, then the corresponding value ( the product name) should be fetched from the database table and should be updated in the textbox named 'textbox1'.
The other thing is this entire thing is contained in a form which is supposed to be finally submitted to the servlet for further processing.
So how can i achieve this.
i figured out the solution to my own problem. It might not be the most elegant way of doing it, but it does the job pretty well.
So as per my requirement, what i exactly wanted to do was.... insert a value (that will be fetched from the database) into a text box on my form depending on what the user chooses from the drop down box that is already present on my form.
To achieve this, i went about and thought if some how i could nest a form withing my main form, it'd solve my issue. But i discovered that nesting of forms is not allowed. So the next option i thought of was to some how submit the same form without the user clicking on the submit button and also handle it appropriately as an 'incomplete' submit (in the sense that the form is still to be submitted manually by the user by clicking on the submit button) on the server.
So i simply made use of the 'onChange' event of a drop down box. I created an additional hidden field on my form.I wrote a simple javascript function that would simply set the value of the hidden field to the string-"partial Submit" and would submit my main form (say named 'form1') as :-
document.getElementById("hidden_id").setAttribute("value","partial submit");
form1.submit;
The function that does the above will be called whenever (and everytime) the onchange event of the drop down box gets fired.
When the user finally clicks on the submit button on the form to submit the finally completed form, then another javascript function is called that simply sets the value of the hidden field on the form to the string, "final submit" and would submit the form as :-
document.getElementById("hidden_id").setAttribute("value","final submit");
form1.submit;
Now on my server, i checked for the value of this hidden field as :-
if(request.getParameter("hidden_id").equals("partial Submit"))
{
// make a database connection, pass the value user selected from the drop down box
// to a prepared statement that does the query for getting the 'productName' from
// the database, collect the returned string in a variable and set a
// request attribute with this returned value. This value can simply be used in the
// jsp to fill in the value part of the textbox1.
}
else
{
if(request.getParameter("hidden_id").equals("final Submit"))
{
// do the rest of the final processing that needs to be done when user finally
// submits the completed form.
}
else
{
// throw an exception to take care of the possibility that the user might send
// in a 3rd value as a value for the hidden field.
}
}
Since you havent provided the code for selectProduct(this.value) , i presume that it submits the jsp page as when you change the value in the drop down.
If that the case in the servelt, set the value that you want to show in jsp in request object
request.setAttribute("valuetodisplay" ,valuetodisplay);
and now in jsp
<input type="text" value ='<%= request.getAttribute("valuetodisplay")%>' />

How to call a Java method in a different part of a JSP page

Let's say I have an input button.
<input type="button" value="click here />
Then there's other HTML and Java codes.
.
.
.
.
.
Then there's a div tag.
<div>
</div>
and inside this div I want to execute these codes, but Only when I click on that button.
<% `int i = 0;
while(i<3) {
%> <div> I love you </div>
<% i++;} %>`
Java code is executed on the server. Events like clicks happen on the user's browser. So a click cannot call java code directly.
You need to:
either code the filling of the div in pure javascript,
or make an ajax call when the button is clicked, to retrieve the
content of the div from the server.
Probably Onclick event you can set the value of a hidden parameter and in div check for parameter value in script-let using if else but again java code will be executed on server and hence it will be new request to same Action otherwise use Ajax to populate data in div from sever.
you need to use ajax and servlet to acheive this.
servlet would send the code in response.
The success part of ajax would add the returned string to the div.
You would need to assign an id to div.
The ajax syntax would be
$.ajax({
url:"../servletname",
type:"POST",
data:{},
success:function(response){
$("#divid").html(response);
}
});
You need to call the servlet in the jsp using onClick function.

Categories