JSP/Java table issue - java

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>

Related

unable to retrieve the Table th tag value using webdriver with java

From the below html i want to check each row in the table header value and if matched need retrieve the td value
below is my html
<table class="span-5" id="summaryTable" title="Table showing Summary data">
<tbody>
<tr>
<th class="width-40" id="num">
(12) App no:
</th>
<td headers="num">
(11)
<strong>2796179</strong>
</td>
</tr>
<tr>
<th class="noLines alignLeft width35" id="EnglishTitle">
(54) English Title:
</th>
<td class="noLines alignLeft width65" headers="EnglishTitle">
FRAME BIT-SIZE ALLOCATION
</td>
</tr>
<tr>
</tbody>
</table>
i want to collect the each th tag value (i.e (12) App no (54) English Title)
my java code
WebElement summary = driver.findElement(By.xpath("//*[#id='summaryTable']/tbody"));
List<WebElement>rows = summary.findElements(By.tagName("tr"));
for (int i=1;i<=rows.size();i++){
String dc = driver.findElement(By.xpath("//*[#id='summaryTable']/tbody/tr["+i+"]/td/th/a")).getText();
if (dc.equalsIgnoreCase("(12) App no")){
appNo = driver.findElement(By.xpath("//*[#id='summaryTable']/tbody/tr["+i+"]/td/strong")).getText();
}
}
but i'm getting no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id='summaryTable']/tbody/tr[1]/td/th/a"}
Please use the below code for this
WebElement elem = driver.findElement(By.id("summaryTable"));
List<WebElement> lists = elem.findElements(By.tagName("th"));
for(WebElement el : lists){
WebElement element = el.findElement(By.tagName("a"));
String str = element.getAttribute("innerHTML");
System.out.println(str);
}
I think you are making it a bit complicated, can you try bit simpler version?
public String getRequiredDataFromTableFromRow(String header){
WebElement table = driver.findElement(By.id("summaryTable"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
for (WebElement row:rows) {
if(row.getText().contains(header)){
return row.findElement(By.tagName("td")).getText();
}
}
return null;
}
Cells are also arrays within the row, so you need to specify the position to get the text. The th tag is not there within the td tag.
Try the following code:
WebElement summary = driver.findElement(By.xpath("//*[#id='summaryTable']/tbody"));
List<WebElement>rows = summary.findElements(By.tagName("tr"));
for(int i = 1; i <= rows.size(); i++) {
String dc = driver.findElement(By.xpath("//*[#id='summaryTable']/tbody/tr[" + i + "]/th[0]")).getText();
if(dc.equalsIgnoreCase("(12) App no")) {
appNo = driver.findElement(By.xpath("//*[#id='summaryTable']/tbody/tr[" + i + "]/td[0]")).getText();
}
}
Below is basically for getting you the text for each "th" element.
WebElement summary = driver.findElement(By.id("summaryTable"));
List<WebElement>rows = summary.findElements(By.tagName("th"));
for(WebElement row : rows){
row.getText();
}}
In the above code, I am getting the reference using the "id" and using same object reference in order to get the elements list for "th" tag.
In case you want to perform operation on the text been found can be done using the reference of the row element

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.

Oreilly Multipart parser and dynamically created rows (through jquery)

I have 2 jsp's:
createEdit.jsp and save.jsp
Inside createEdit.jsp I have a an html code inside a form and since it includes file upload, I am using encoding type "multipart/form-data". Inside the form I have a table. The requirement is to save the data from the table to the database. I can add row to the table dynamically through Jquery or Javascript.
This is my sample form having table:
<form action="save.jsp" method="post" enctype="multipart/form-data" name="frm">
<table id="tblRating">
<tr><td><input id="e1">Element1</input><input id="e2"></input><td><tr>
</table>
</form>
The javascript code am using for adding rows dynamically to the exisitng table:
function generateRow(){
console.log("Generate the row");
var table = document.getElementById('tblRating');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
console.log(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select":
newcell.childNodes[0].selectedIndex = 'null';
break;
}
}
return false;
}
Inside save.jsp I have a scriplet code (the code is quite old so it has scriplet).
It parses the request using Oreilly Multipart parser and fetches input element one by one.
Sample code for my save.jsp:
MultipartParser parser = new MultipartParser(request, 2 * 1024 * 1024);
String e1Value = ((ParamPart) parser.readNextPart()).getStringValue()); //reads the input elements only
String e2Value = ((ParamPart) parser.readNextPart()).getStringValue());
The issue is when I tried to read the elements through the parser, its able to get the existing rows on the form. But the parser doesn't take up the rows created through javascript.
I have tried printing the form on submit. It has the dynamically created rows. But when I tried to get the data from the parser it doesn't provide the rows created through javascript.
Please help. Thanks in advance.
I'd make sure each input has a unique name="..." attribute by appending the row number and column number to the name (e.g. myInput_2_3 would be the input in row 2, column 3). You can use setAttribute('name', ...) on your newcell to set the input's name.
Finally I am able to get through it.
The issue was not related to the multipart parser. It was the structure of the JSP that was crating an issue. Because of the existing structure the jsp form was not able to take up the Dynamically created elements.
Earlier the jsp structure was like this:
<table align=center border=0 cellpadding=0 cellspacing=0 width=75%>
<form onSubmit="return validate()" action=".." method="post" enctype="multipart/form-data" name="frmEntry">
<tr><td>........</td></tr>
</form>
</table>
The above structure was creating problem. So I just took the table inside of the form.
<form onSubmit="return validate()" action=".." method="post" enctype="multipart/form-data" name="frmEntry">
<table align=center border=0 cellpadding=0 cellspacing=0 width=75%>
<tr><td>........</td></tr>
</table>
</form>
And it worked :)

Adding td element to next tr of rowspan td

I have below html,
<!DOCTYPE html>
<html>
<body>
<table border="1">
<tr>
<th>Month</th>
<th>Savings</th>
<th>Savings for holiday!</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
<td rowspan="2">$50</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
</body>
</html>
I want to generate below html using jsoup,
<tr>
<th>Month</th>
<th>Savings</th>
<th>Savings for holiday!</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
<td rowspan="2">$50</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
<td>$50</td>
</tr>
I have currenty written this piece of code through which i can get the rowspan cell and its associated td index
final Elements rows = table.select("tr");
int rowspanCount=0;
String rowspanString ="";
for(Element row : rows){
int rowspanIndex = 0;
for(Element cell: row.select("td")){
rowspanIndex++;
if(cell.hasAttr("rowspan")){
rowspanCount = Integer.parseInt(cell.attr("rowspan"));
rowspanString = cell.ownText();
cell.removeAttr("rowspan");
}
}
}
Possible HINT: For condition,
cell.hasAttr("rowspan")
Get row-index, like;
int index = row.getIndex();
and then get next Row by index+1, like;
Element eRow = rows.get(index+1);
then append td-Element to this row, this would be your next row to rowspan-row.
After coding everything, I found the solution. Below is the code,
for (Element row : rows) {
int cellIndex = -1;
if(row.select("td").hasAttr("rowspan")){
for (Element cell : row.select("td")) {
cellIndex++;
if (cell.hasAttr("rowspan")) {
rowspanCount = Integer.parseInt(cell.attr("rowspan"));
cell.removeAttr("rowspan");
Element copyRow = row;
for (int i = rowspanCount; i > 1; i--) {
nextRow = copyRow.nextElementSibling();
Element cellCopy = cell.clone();
Element childTd = nextRow.child(cellIndex);
childTd.after(cellCopy);
}
}
}
}
}
It duplicates the rowspan cell to all the following rows that should contain it. As well removes the attribute rowspan for removing any further discrepancy.
You can append this row simply with this code:
Elements rows = table.select("tr > td[rowspan=2]");
for (Element row : rows) {
row.parent().nextElementSibling().append("<td>$50</td>");
}

creating dynamic rows in JSP/Servlets instead of javascript

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).

Categories