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 :)
Related
This is my HTML page where there will be multiple rows depending on how many data will be in JSON file. The first problem I have is that I have problem with listing down all the color options that can be found in the JSON file. For now it only display only 1 value which is according to the fruit. I do not know what code I should include in the doPost method in Java
<form id="config_form" action="iLoveFruits" method="Post" enctype="multipart/form-data">
<table>
<c:forEach items="${fruits}" var="fruit" varStatus="count">
<tbody>
<tr>
<td><input type="text" name="fruit" id="fruit" value="${fruit.type}"></td>
<td>
<select name="color"><option id="color">${color}</option></select>
</td>
<input type="file" id="image" name="image" var="image" accept=".img,.IMG"/>
<label for="image">Upload</label>
</tr>
</tbody>
<button type="submit" id="submitBtn">Submit</button>
</form>
This is the codes under my doPost method where the file will be uploaded upon pressing the submit button. The issue I am facing is if there is 2 rows for example, whichever "Upload" button I click, it will display the file name under the first row. For example, I want to upload a image for the 3 row of the HTML page, after uploading the image, the name of the file will be shown in the first rather than the third. I do not know how to solve thi s please assist me
for (FileItem uploadItem : uploadItems) {
if (uploadItem.isFormField()) {
String fieldName = uploadItem.getFieldName();
if(fieldName.equals("fruit"))
{
String fruit = uploadItem.getString();
newOutput.put("fruit",fruit);
}
else if(fieldName.equals("color"))
{
String color = uploadItem.getString();
newOutput.put("color",color);
if (cert.toLowerCase().endsWith(".img")) {
File temp = new File(file_dir + File.separator + color);
uploadItem.write(temp);
}
}
}
}
I am trying to get the filename in the textbox according to the row that I am changing
I have a problem that the images registered in my mysql database are not displayed, I have a table and between that table I have a column of photos and I want to list it together with my other columns but I cannot find the solution to the problem below I add code from my ArrayList method and the call in my jsp and the result
Method of my class DAO
public ArrayList<CitaVO> listarCitas(String cliente_idCliente) {
CitaVO citVO = null;
conexion = this.obtenerConexion();
ArrayList<CitaVO> listaCitas = new ArrayList<>();
try {
sql = "SELECT * FROM vwcitasactivas WHERE cliente_idCliente=?";
puente = conexion.prepareStatement(sql);
puente.setString(1, cliente_idCliente);
mensajero = puente.executeQuery();
while (mensajero.next()) {
citVO = new CitaVO(mensajero.getString(1),
mensajero.getString(2), mensajero.getBinaryStream(3),
mensajero.getString(4), mensajero.getString(5),
mensajero.getString(6), mensajero.getString(7),
mensajero.getString(8), mensajero.getString(9),
mensajero.getString(10), mensajero.getString(11),
mensajero.getString(12),cliente_idCliente);
listaCitas.add(citVO);
}
} catch (Exception e) {
Logger.getLogger(ProAgendaDAO.class.getName()).log(Level.SEVERE, null, e);
}
return listaCitas;
jsp where I list the results
<%
CitaVO citVO = new CitaVO();
CitaDAO citDAO = new CitaDAO();
ArrayList<CitaVO> listaCitas = citDAO.listarCitas(idCliente);
for (int i = 0; i < listaCitas.size(); i++) {
citVO = listaCitas.get(i);
%>
<tr>
<td>
<div class="round-img">
<img src="data:image/jpg;base64,<%=citVO.getUsuFoto()%>" alt="" width="50px" height="50px" >
</div>
</td>
<td><%=citVO.getUsuNombre()%> <%=citVO.getUsuApellido()%></td>
<td><%=citVO.getUsuCiudad()%></td>
<td><%=citVO.getCitFecha()%></td>
<td><%=citVO.getProDia()%></td>
<td><%=citVO.getCitDireccion()%></td>
<td><%=citVO.getCitHoraInicio()%></td>
<td><%=citVO.getCitHoraFin()%></td>
<td <%=citVO.getCitEstado()%>><span class="badge badge-primary">Activa</span></td>
<td>
<span><i class="ti-eye color-default"></i> </span>
<span><i class="ti-pencil-alt color-success"></i></span>
<span><i class="ti-trash color-danger"></i> </span>
</td>
</tr>
<%}%>
result of my jsp my images do not appear
Image result
The problem is that the src attribute of an <img> element requires a URL and you are not passing it a URL.
It seems you are attempting to take whatever you got from your database and put that straight into the src attribute in the hope that this would work. If you look at the HTML source of the page you will probably see something like this:
<img src="SomeClassNameHere#18f34fdc" ... >
That's not a URL, that's what you get when you take an object whose class doesn't override .toString() and attempt to convert it to a string.
There are two solutions to this problem:
Convert the image data to base64 and use a data: URL to contain the data. You can then put this URL in the src attribute of the <img> element. See this answer. I don't know how large the images you are attempting to show are (your question hints that they are 50 pixels by 50 pixels), but if they are quite large, this might not be the right approach.
Have a servlet that returns the image data, and write out suitable URLs that call this servlet. For example, you may choose to have your servlet respond to /usuFoto/<id>, where <id> is the clienteId of the image, and for the src attribute you would write out something like src="/usuFoto/<%= cliente_idCliente %>. See this answer for an example of how to write such a servlet.
I am tring to display the values that I placed in an Arraylist in java and pass it to the JSP page and display it in a table row. But the results are displayed in a really bizarre way. Please help me out. I am stuck.
Servlet Code:
ArrayList al = new ArrayList();
while(rs.next())
{
count ++;
String country = rs.getString("CustomerCountry");
String customerid = rs.getString("CustomerID");
String TitleofAccount = rs.getString("TitleofAccount");
String FirstName = rs.getString("FirstName");
String LastName = rs.getString("LastName");
String City = rs.getString("City");
String Address = rs.getString("Address");
String emailid = rs.getString("EmailID");
String typeofid = rs.getString("TypeOfID");
String Idnumber = rs.getString("IDNumber");
String branchid = rs.getString("BranchID");
String cardnumber = rs.getString("CardNumber");
String bankaccntid = rs.getString("BankAccountID");
String currencyid = rs.getString("CurrencyID");
String isspeciallimit = rs.getString("IsSpecialLimit");
String dailylimit = rs.getString("DayTransactionLimit");
al.add(rs.getString("CardNumber"));
al.add(bankaccntid);
al.add(currencyid);
al.add(rs.getString("DayTransactionLimit"));
al.add(isspeciallimit);
JSP page:
<table width="700px" align="center" style="border:1px solid #000000;">
<tr>
<td colspan=4 align="center" style="background-color:teal">
<b>User Record</b></td>
</tr>
<tr style="background-color:lightgrey;">
<td><b>Account No</b></td>
<td><b>Card Number</b></td>
<td><b>CurrencyID</b></td>
<td><b>Daily Limit</b></td>
<td><b>Status Limit</b></td>
</tr>
<%
if (request.getAttribute("al")!=null)
{
ArrayList arr = (ArrayList)request.getAttribute("al");
for(int i=0;i<arr.size();i++) {
out.println(arr.get(i) + "<html>  <p></p></html>");
//out.println("<html>  </html>");
}
}
%>
Output:
[kenya, K, 432342423, , 100000.0000, 0,
kenya, Kumar11, 78788787878, OOOPP, 100000.0000, 0,
kenya, Kb1, 001001000095, KES, 500000.0000, null]
I want the results to be displayed as:
1st row - kenya, K, 432342423, , 100000.0000, 0,
2nd row - kenya, Kumar11, 78788787878, OOOPP, 100000.0000, 0,
3rd row - kenya, Kb1, 001001000095, KES, 500000.0000, null
Always remember that the output of a JSP is the body of a servlet response, which in this case is HTML. It is essential to review the generated output during development and testing, and reviewing only the result of some other program's -- e.g. a web browser's -- processing of that output is insufficient.
I'm inclined to think that the problem would have become immediately evident to you if you had in fact reviewed the HTML emitted by your JSP, which, if it was generated via the JSP code you present, will have looked something like this
<!-- [...] -->
<tr style="background-color:lightgrey;">
<td><b>Account No</b></td>
<td><b>Card Number</b></td>
<td><b>CurrencyID</b></td>
<td><b>Daily Limit</b></td>
<td><b>Status Limit</b></td>
</tr>
kenya<html>  <p></p></html>
K<html>  <p></p></html>
432342423<html>  <p></p></html>
<html>  <p></p></html>
100000.0000<html>  <p></p></html>
0<html>  <p></p></html>
<!-- [...] -->
(Line breaks added for clarity.)
Such code is grotesquely non-conforming, and it moreover exhibits none of the HTML structure that you should expect to use to represent tabular data (i.e. <tr> and <td> elements).
On the other hand, I don't see how the output you present could come from the JSP code you present, whether you're presenting it raw or rendered. The output looks like what you would get from out.println(arr), as opposed to from printing the list elements one at a time.
Additionally, the output seems not to quite correspond to the servlet code, either, in that it appears to contain six data per record, whereas you show the servlet providing only five per record.
In Servlet/Java - Wrap all fields into an object, say "Customer"
Use JSTL inside JSP, refer this sample,
<c:forEach var="customer" items="CustomersList">
<c:out value="${customer.id}" />
<c:out value="${customer.userName}" />
<c:out value="${customer.password}" />
<c:out value="${customer.email}" />
</c:forEach>
CustomersList is the arrayList which you are passing from Servlet to JSP.
i have been working on this for a while and just cant seem to work out how to get the correct table that corresponds to the header it has. the tables are split up into sections which i can retrieve however inside the section is a header with the title of the table. i need to find the section with the header that matches a string and then pull the data from it. I'm fine with getting the data out of the table its just getting the correct section for the table
HTML extract of the section:
<section class="blueTab">
<header><h2>Energy</h2></header> //<----- THE HEADER I NEED TO MATCH TO
<table class="infoTable">
<tr><th>Model</th><th>0-60 mph</th><th>Top Speed</th><th>BHP</th><th></th></tr>
<tr>
<td><p>1.4i 16V Energy 5d</p></td>
<td><p>12.8 secs</p></td>
<td><p>111 mph</p></td>
<td><p>88 bhp</p></td>
</tr>
<tr class="alternate">
<td><p>1.6i 16V Energy 5d</p></td>
<td><p>11.5 secs</p></td>
<td><p>115 mph</p></td>
<td><p>103 bhp</p></td>
</tr>
<tr>
<td><p>1.8i VVT Energy 5d Auto</p></td>
<td><p>10.7 secs</p></td>
<td><p>117 mph</p></td>
<td><p>138 bhp</p></td>
</tr>
<tr class="alternate">
<td><p>1.3 CDTi 16V Energy 5d</p></td>
<td><p>12.8 secs</p></td>
<td><p>107 mph</p></td>
<td><p>88 bhp</p></td>
</tr>
</table>
<div class="fr topMargin">
<div id="ctl00_contentHolder_topFullWidthContent" class="modelEnquiry">
<div id="ctl00_contentHolder_topFullWidthContent" class="buttonLinks">
</div>
<div class="cb"><!----></div>
</div>
</div>
<div class="cb"><!----></div>
</section>
Im guessing i will have to use doc.getElementsByClass("blueTab") in a for loop and for each element see if h2 equals the string im looking for, i am just not sure how to implement this
This should solve your problem
Document doc = Jsoup.parse(input, "UTF-8");
Elements elem = doc.select(".blueTab header h2");
for (Iterator<Element> iterator = elem.iterator(); iterator.hasNext();)
{
Element element = iterator.next();
if (element.text().equals("Energy")) // your comparison text
{
Element tableElement = element.parent().nextElementSibling(); //Your got the expected table Element as per your requirement
}
}
I have a document containing several forms similar to the example posted below. I want to extract all the name/value pairs from the hidden input fields of one of the forms, the form is identified by its name and I don't know in advance how many hidden fields will be present.
I am able to select all the relevant input fields in the document using the selector query: input[type=hidden][name][value]
Is there a way to only select the input fields which has FORM[name=lgo] as parent? Using some kind filter maybe?
<FORM METHOD='POST' onSubmit='javascript:isWaitForm();' ACTION='https://abc-azerty.querty.se/carmon/servlet/action/change_1 ' name='lgo'>
<input type='hidden' name='LogInFlag' value='1'>
<input type='hidden' name='LogInTime' value='2011-07-26 11:10'>
<input type='hidden' name='cCode2' value='SE'>
<a href='javascript:isWaitForm();javascript:document.lgo.submit();' class='linkNone'>Business Monitor</a>
<a href='javascript:isWaitForm();javascript:document.lgo.submit();' class='linkNone'>
<input type='image' src='/images/button_arrow_right.gif' height=19 width=22 border=0 style='float:left;'></A>
</FORM>
Based on this info, at least one of following should work -
doc.select("form[name=lgo] > input[type=hidden]");
Or, you can chain your selects -
doc.select("form[name=lgo]").select("input[type=hidden]");
The select method is available in a Document, Element, or in Elements. It is contextual, so you can filter by selecting from a specific element, or by chaining select calls.
<script type="text/javascript">
var inputs = document.getElementsByName('lgo')[0].getElementsByTagName('input');
for(var i = 0 ; i < inputs.length ; i++){
if(inputs[i].getAttribute('type') == "hidden") {
// This will get the name: inputs[i].getAttribute('name')
// This will get the value: inputs[i].value)
console.log(inputs[i].getAttribute('name') + ": " + inputs[i].value);
}}
</script>