creating dynamic rows in JSP/Servlets instead of javascript - java

Is there any alternative mechanism creating dynamic rows in JSP/Servlets instead of javascript.
JS Code:-
var table = document.getElementById('table1');
var tr = document.createElement('TR');
var td1 = document.createElement('TD');
var td2 = document.createElement('TD');
var td3 = document.createElement('TD');
var td4 = document.createElement('TD');
var inp1 = document.createElement('INPUT');
var inp2 = document.createElement('INPUT');
var inp3 = document.createElement('INPUT');
inp1.setAttribute("Name", "purpose");
inp1.setAttribute("id", purpose"+reclength);
inp2.setAttribute("Name", "Amount");
inp2.setAttribute("id", "Amount"+reclength);
inp3.setAttribute("Name", "dt");
inp3.setAttribute("id", "dt"+reclength);
var deleteIcon = document.createElement('IMG');
deleteIcon.setAttribute('src', '<%=basePath%>images/cancelIcon.gif');
deleteIcon.onclick = function(){
removeWthDrwls(tr);
}
table.appendChild(tr);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
td1.appendChild(inp1);
td2.appendChild(inp2);
td3.appendChild(inp3);
td3.appendChild(space2);
td3.appendChild(deleteIcon);
but if user has disabled javascript.So what are best ways to provide alternative solution to him/her in java web applications?

ofcourse you can do the same in jsp refer JSP: Creating Dynamic Tables
here example is given how you can create a table in the jsp same way you can create dynamic rows..
Ten columns can be added for each row by nesting another for loop within the TR tag as follows:
<TABLE>
<% for(int row=1; row <= 5; row++) { %>
<TR>
<% for(int col=1; col<=10; col++) { %>
<TD> (<%=col%>, <%=row%>)
</TD>
<% } %>
</TR>
<% } %>
</TABLE>
Each cell contains its row and column numbers as the tuple (col, row).

Related

find the particular value in the table column

i have write the below code for find the particular column value in web table, but if i give the static value in row and column value , driver is identifying the value , but if i get the value through for loop, i am not able to retrieve the values.
WebElement tabledata = driver.findElement(By.id("divAttendanceDetails"));
List<WebElement> Rows = tabledata.findElements(By.xpath("//*[#id='divAttendanceDetails']/table[1]/tbody/tr"));
System.out.println("NoofRowsinthetable" + Rows.size());
String identifyvalue = "Leave Applied";
int leavecount = 0;
for (int getrowvalue=0; getrowvalue < Rows.size()-1;getrowvalue++)
{
List<WebElement> Columns = Rows.get(getrowvalue).findElements(By.xpath("//*[#id='divAttendanceDetails']/table[1]/tbody/tr/td"));
System.out.println("NoofColumnsinthetable" + Columns.size() );
for (int getcolumnvalue =0;getcolumnvalue<Columns.size(); getcolumnvalue++ )
{
String cellvaues = driver.findElement(By.xpath("//*[#id='divAttendanceDetails']/table[1]/tbody/tr["+getrowvalue+"]/td["+getcolumnvalue+"]")).getText();
System.out.println(cellvaues);
if(identifyvalue.equalsIgnoreCase(cellvaues))
{
leavecount = leavecount+1;
System.out.println("Leavecounttilldate" + leavecount );
}
}
}
Please help to resolve the issue
Html Page looks
<div id="newdiv"><table class="ariel" cellspacing="0" cellpadding="3" rules="all" border="1" id="dgResults" style="width:100%;border-collapse:collapse;">
<tbody><tr class="bluerow" align="left" style="font-weight:bold;">
<td style="width:15%;">start Date</td><td style="width:15%;">end Date</td><td style="width:15%;">in Time</td><td style="width:15%;">Out Time</td><td style="width:15%;">totalhours Office</td><td style="width:20%;">Details</td>
</tr><tr class="row2" align="left">
<td>01/01/2015</td><td>01/01/2015</td><td>00:00</td><td>00:00</td><td>00:00</td><td align="left">Holiday</td>
</tr><tr class="row2" align="left">
<td>01/02/2015</td><td>01/02/2015</td><td>00:00</td><td>00:00</td><td>00:00</td><td align="left">Leave Applied</td>
</tr><tr class="row2" align="left">
<td>01/03/2015</td><td>01/03/2015</td><td>00:00</td><td>00:00</td><td>00:00</td><td align="left">Weekend</td>
</tr><tr class="row2" align="left">
<td>01/04/2015</td><td>01/04/2015</td><td>00:00</td><td>00:00</td><td>00:00</td><td align="left">Weekend</td>
</tr><tr class="row2" align="left">
<td>01/05/2015</td><td>01/05/2015</td><td>13:02</td><td>19:01</td><td>04:38</td><td align="left"> </td>
</tr>
</tbody></table></div>
I have faced similar issue and have resolved by using String.format().
String xpath = "//*[#id='divAttendanceDetails']/table[1]/tbody/tr[%s]/td[%s]";
String cellvaues = driver.findElement(By.xpath(String.format(xpath, getrowvalue, getcolumnvalue))).getText();
one issue with yours xpath is its indexes. Xpath indexes starts with 1.
ref: Why do indexes in XPath start with 1 and not 0?
but this can be issue if you have only one row, results for other rows should be displayed.
It will be helpful if you share the HTML and your current output.
Followed the html you have provided. It does not necessarily matches the code you have in original post.
List<WebElement> Rows = driver.findElements(By.cssSelector("#dgResults tr"));
System.out.println("NoofRowsinthetable" + Rows.size());
for (int i = 0; i < Rows.size(); i++)
{
//find the columns in specific row
List<WebElement> Columns = Rows.get(i).findElements(By.cssSelector("td"));
System.out.println("NoofColumnsinthetable" + Columns.size() );
for (int j = 0; j < Columns.size(); j++ )
{
String text = Columns.get(j).getText();
System.out.println(text);
/* adjust as you needed.
if(identifyvalue.equalsIgnoreCase(text))
{
leavecount = leavecount+1;
System.out.println("Leavecounttilldate" + leavecount );
}
*/
}
}
Note: I didn't test the code on my end. May have some syntax issue

HTTP 500 in redirecting to the same jsp

i am having f.jsp which returns a lists of ages(1..100) and genders(m/f) and a button GO and put it in comboboxes and i have f_m.java which is servlet which took the selected items from comboboxes and select an certain item from database and put it in table in f.jsp .. now my problem is when trying to print the table in f.jsp and HTTP 500 appears so what can i do .. here is my code
f.jsp
<% List<String> sex = (List<String>)request.getAttribute("sexList"); %>
<% List<String> age = (List<String>)request.getAttribute("ageList"); %>
<form method ="GET" action="f_m" >
<html>
<body>
<table>
<tr>
<td>Gender:</td>
<td><select name="sex">
<%for(String item : sexList) { %>
<option value="<%=item%>"><%=item %></option><%}%>
</select>
</td>
<td>age:</td>
<td><select name="age">
<%for(String item : maritalStatus) { %>
<option value="<%=item%>"><%=item %></option><%}%>
</select>
</td>
<td><input type="submit" value="Go" name="Go"></td>
</tr>
</table>
</form>
</body>
</html>
and f_m.java
String gender = request.getParameter("sex");
String age = request.getParameter("age");
if(request.getParameter("Go") != null){
// i want to go to f.jsp to print the table
}
You must set the request attributes in the servlet before forwarding to the jsp. I suppose it could be something like :
// prepare the attributes
int ageList = new int[100];
int sexList = new String[]{"m", "f"};
for (int i=0; i<100; i++) { ageList[i] = i + 1; }
// put them in request
request.setAttribute("ageList", ageList);
request.setAttribute("sexList", sexList);
// and forward to the jsp.
request.getRequestDispatcher("f.jsp").forward(request, response);
You have two lists: sex and age. When you are trying to populate the select, you asked:
<%for(String item : sexList) { %>
Where is declared your sexList? May be you want to iterate through sex list? I mean, try:
<%for(String item : sex) { %>
And the same for second list:
<%for (String item : age) {%>
You must be more explicit what are you trying to do in your Servlet. I assume your main scope is to populate two selects in a form depending on two lists: sex and age. After this you want to take 2 selected values and pass them to servlet, the servlet will make a call to a database depending on these two values and will return a row from the table. After this you want to print this row in your f.jsp. If so, get the values from the select (and populate them right, like i mentioned below) in your servlet:
String sex = request.getParameter("sex");
String age = request.getParameter("age");
//method to call database, i.e List<Persons> list = DBHelper.checkSomething(sex, age);
if(...){
RequestDispatcher rd = request.getRequestDispatcher("f.jsp");
request.setAttribute("list", list);
rd.forward(request, response);
}
And i strongly recommend you to print your data based on a View. If you want to know more, read about MVC patterns.

Pass variable from JSP to javascript file

I have an int variable in that gets passed into a jsp file from a java class. I now want to pass this int value from the jsp to a javascript file I have. I am stuck with a coming up with a solution. I have tried the following but still does not work:
javascript:
jQuery(document).ready(function() {
jQuery('div.awsmp-hero-featureSwap').each(function() {
jQuery(this).find('div.hero-featureSwap').each(function() {
var width = 0;
var height = 0;
var count = 1;
var perpage = "${products_per_page}"; // ***** this is the value I want from the jsp*****
var totalcarousel = jQuery('.hero').length;
jQuery(this).find('div').each(function() {
width += jQuery(this).width();
count = count + 1;
if (jQuery(this).height() > height) {
height = jQuery(this).height();
}
});
jQuery(this).width(((width / count) * perpage + 1) + (perpage * 12) + 60 + 'px');
jQuery(this).height(height + 'px');
});
});
JSP:
<c:set var="products_per_page" value="3" />
<c:if test="${not null model.listSize}">
<c:set var="products_per_page" value="${model.listSize}" />
</c:if>
I just want to pass the the "products_per_page" value to the javascript. should be very simple...
you can put your <c:set> block into an HTML element as its value then get the value easily using Javascript or jQuery
example :
<input id="ppp" type="text" value="<c:set var='products_per_page' value='3' />"/>
js:
var products_per_page = document.getElementById("ppp").value;
You can use this, is not very recommendable.... but works..
Hard-coding the value into the html file like this:
<body>
.....
var x = <%= some_value %>;
.....
</body>
I passed the request argument to my onclick handler in js the following way:
<s:submit name="kurierButton" onclick="openKurierWindow('%{#attr.OUTBOUND_KURIER_URL}');" value="%{#attr.OUTBOUND_KURIER}"/>
Try doing it this way->
servlet_file.java
HttpSession session = request.getSession();
session.setAttribute("idList", idList);
.jsp file
<%
HttpSession session1 = request.getSession();
ArrayList<Integer> idList = (ArrayList<Integer>) session1.getAttribute("idList");
%>
.js file
alert("${idList}");

JSP-JSTL table selects only the first row of table

Im new to HTML, Java, Javascript, JSP, and JSTL.
I have a simple JSP page using JSTL as my tag library. When I used javascript to get all the values of the a row by clicking all I can get are the values of the first row even when I click the 2nd, 3rd, or nth row. I want to get only the row I clicked.
in my javascript:
<script type="text/javascript" >
function getTblContents() {
var pName = document.getElementById("pName").innerHTML;
var pAddress = document.getElementById("pAddress").innerHTML;
var pEmail = document.getElementById("pEmail").innerHTML;
alert(pName + " " + pAddress + " " + pEmail);
}
</script>
my jstl code:
<c:forEach var="people" items="${people.data}" varStatus="status">
<tr onMouseOver="this.className='highlight'" onMouseOut="this.className='normal'" onclick="getTblContents();" >
<td id="pName" >${people.name}</td>
<td id="pAddress" >${people.address}</td>
<td id="pEmail" >${people.email}</td>
</tr>
</c:forEach>
the javascript and jsp are on the same page.
Please help. Thanks in advance.
Every id must be unique in html, it is restriction that html sets. So you should add some
uniqe identifier to ids ie. people.id and past that id to javascript function.
<script type="text/javascript" >
function getTblContents(id) {
var pName = document.getElementById("pName-"+id).innerHTML;
var pAddress = document.getElementById("pAddress-"+id).innerHTML;
var pEmail = document.getElementById("pEmail-"+id).innerHTML;
alert(pName + " " + pAddress + " " + pEmail);
}
</script>
<c:forEach var="people" items="${people.data}" varStatus="status">
<tr onMouseOver="this.className='highlight'" onMouseOut="this.className='normal'" onclick="getTblContents('${people.id}');" >
<td id="pName-${people.id}" >${people.name}</td>
<td id="pAddress-${people.id}" >${people.address}</td>
<td id="pEmail-${people.id}" >${people.email}</td>
</tr>
</c:forEach>
The document.getElementById($ID) will return the first element in the dom with the specified id(the first row of your table).
You could try
<tr onMouseOver="this.className='highlight'" onMouseOut="this.className='normal'" onclick="getTblContents(this);" >
and refer to the "this" element instead. like:
var pname = this.pname;
or
var pname = this.pname.innetHTML;
in the javascript. and see if that returns the right row of the table

JSP/Java table issue

I have a table that is populated depending on how many cars are there. If the number of cars is 1 it will give me the 1 row (where 5 attributes are arranged in 5 columns). If the number of cars is 2 it will give me 2 rows(same 5 attributes), & so on. Now I need to split the table into as many cars are there so that there is just one row for every car. I need to do it in JSP and trying to use the tag <c:choose> or <c:if>, but isn't working . Please help
You need <c:forEach> here. With it you can iterate over any List<T> and print the <tr> on every iteration. Assuming that you have populated a List<Car> and put it in the EL scope as ${cars}, here's an example:
<table>
<c:forEach items="${cars}" var="car">
<tr>
<td>${car.make}</td>
<td>${car.model}</td>
<td>${car.type}</td>
<td>${car.color}</td>
<td>${car.price}</td>
</tr>
</c:forEach>
</table>
See also:
Beginning and intermediate JSP/Servlet tutorials
Hidden features of JSP/Servlet
<html>
<head>
<title>Sample code - Traversing an HTML Table with JavaScript and DOM Interfaces</title>
<script>
function start() {
// get the reference for the body
var body = document.getElementsByTagName("body")[0];
// creates a <table> element and a <tbody> element
var tbl = document.createElement("table");
var tblBody = document.createElement("tbody");
// creating all cells
for (var j = 0; j < 2; j++) {
// creates a table row
var row = document.createElement("tr");
for (var i = 0; i < 2; i++) {
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
var cell = document.createElement("td");
var cellText = document.createTextNode("cell is row "+j+", column "+i);
cell.appendChild(cellText);
row.appendChild(cell);
}
// add the row to the end of the table body
tblBody.appendChild(row);
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody);
// appends <table> into <body>
body.appendChild(tbl);
// sets the border attribute of tbl to 2;
tbl.setAttribute("border", "2");
}
</script>
</head>
<body onload="start()">
</body>
</html>

Categories