Passing Arraylist values from servlet to JSP in java? - java

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>&nbsp&nbsp<p></p></html>");
//out.println("<html>&nbsp&nbsp</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>&nbsp&nbsp<p></p></html>
K<html>&nbsp&nbsp<p></p></html>
432342423<html>&nbsp&nbsp<p></p></html>
<html>&nbsp&nbsp<p></p></html>
100000.0000<html>&nbsp&nbsp<p></p></html>
0<html>&nbsp&nbsp<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.

Related

My code does not show my images saved in blob type database in my jsp file?

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.

Detecting same tags pattern in web page using jsoup java

I am writing a code for detecting matching tags patterns in web page. Here is the example.
<body>
<table width="200" border="1">
<tr>
<td>Name</td>
<td>Place</td>
<td>Animal</td>
</tr>
<p>hello World</p>
<tr>
<td>Jack</td>
<td>New york</td>
<td>Lion</td>
</tr>
<b>Code Works</b>
<tr>
<td>George</td>
<td>Sydney</td>
<td>Tiger</td>
</tr>
<tr>
<td>Tina</td>
<td>Delhi</td>
<td>Cat</td>
</tr>
</table>
<table>
<tbody>
<tr>
<td> </td>
<td>
1
2
3
4
5
</td>
</tr>
</tbody>
</table>
</body>
For above Tag pattern, I need to find the tags which are occurring repeatedly. And to discard those that are not in the pattern like tags b and p. For first table tags tr and td are occurring . For 2nd table 'a' tag is repeated.
This is what I have done till now:
Parsed to DOM tree using Jsoup.
Then used node visitor class to traverse the tree. Using head and tail methods, I can enter and exit tags.
But I am confused about how to proceed further.
Note: The tags pattern are not fixed.Tag pattern will vary depending on web page structure. Any kind of help will be appreciated.
But I am confused about how to proceed further.
Your confusion is propagating and reach us too. However, I'll try to give you an hint.
You can count the tags in your HTML code. If a tag count reaches a certain threshold, you can consider this tag as "repeatedly occuring".
// Load document
String html = ...
Document doc = Jsoup.parse(html);
// Count tags
String tagsSelector = "*";
Map<Element, Integer> tagsCountByType = new Hashmap<>();
for(Element e : doc.select("*")) {
Integer count = tagsCountByType.get(e);
if (count == null) {
tagsCountByType.put(e, new Integer(1));
} else {
tagsCountByType.put(e, new Integer(count.intValue() + 1));
}
}
// Find tag with a count greater than a given threshold
// ...
I didn't test the code. Just take it as an idea, some sort of inspiration.
Another idea, you can narrow down the tagsSelector. For example:
// All elements (tags) under any table directly under body.
String tagsSelector = "body > table *";

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.

HtmlUnit: Extract text from a <span> after an <a> tag

I am trying to extract some Data from a webpage via HtmlUnit. This data is firstnames and lastnames of some of my students. The data is organized like this:
<td width='20%' align='left' valign='top' class='textstyle1'>
<a href='page.html' name='specName' class='seriousClass'>Secondname</a>,
<span class='textstyle2'>Firstname</span></td><td width='15%' align='center'
valign='top' class='textstyle2'> </td>
At the moment I can only extract the secondname like this:
List studentsFieldList = page2.getElementsByName("specName");
for (int i = 0; i<studentsFieldList.size(); i++){
String lastName = ((Node)studentsFieldList.get(i)).getFirstChild().getNodeValue();
}
I cannot get the firstname out. I tryed to use
String firstName = ((Node)studentsFieldList.get(i)).getPreviousSibling().getFirstChild.getNodeValue();
but it does not work. The String is empty, although the debugger shows me the right value in the studentsFieldList Object.
Any help would be highly appreciated.
I was able to resolve it myself. The problem is, that you cannot access the methods of your NodeList deeper than the first Daughter-Node although the code completion of your IDE tells you, that you can.
When I want to get the String firstName in the above example, I have to extract the daughter Node from within the NodeList:
Node firstNameNode = (Node)studentsFieldList.get(i)).getPreviousSiblin();
String firstname = firstNameNode.getFirstChild().getNodeValue();

Error in my struts Action class

I have a JSP where I am showing date and description from database. Every entry has a unique id, but I am not showing on the page(showing checkbox)
These entries are thrown using a "logic:iterate", so the number of rows is always changing based on entries.
Now these fields are shown as a text field so that the user can also update the date or description. A checkbox is to the left so the
user can select what all values they want to update. Remember the logic:iterate above, the checkbox has to be defined using name and
cannot have id.
...
...
<logic:notEmpty name="specialResult" scope="request">
<logic:iterate name="specialResult" id="specialResult" indexId="index">
<tr align="center">
<td width="15%">
<input type="checkbox" name="upisActive" property="upisActive"
value="<bean:write name="specialResult" property="upId"/>"></input></td>
<td width="15%"><input type="text" name="upDate" value="<bean:write name="specialResult" property="upDate"/>"
property="upDate" size="20" class="Date" id="Date"></input></td>
<td width="15%"><input type="text" name="upDesc" value="<bean:write name="specialResult" property="upDesc"/>"
property="upDesc" size="20" id="Desc"/></td>
</tr>
</logic:iterate>
...
My error is that if I have three rows and I want to update third row and select third checkbox. My Action class is retrieving the first row date and desc.
How can I edit my action class to retrieve the value against the checked checkboxes?
public ActionForward class(ActionMapping mapping, ActionForm theForm,
HttpServletRequest request, HttpServletResponse response) throws IOException,
SQLException, ServletException
{
Connection conn = null;
Service Serv = new Service();
List updList = new ArrayList();
Form upForm = (Form) theForm;
String[] values = request.getParameterValues("upisActive");
try
{
conn = getConnection(request, false);
for (int i=0;i<values.length;i++){
VO hdvo = new VO(); //Vo class with getters and setters
val = values[i];
hdvo.setDate(upForm.upDate[i]);
hdvo.setDesc(upForm.upDesc[i]);
updList.add(hdvo);
}
hdServ.updTest(updList, conn);
...
The problem is with how you've set up your page. You have all checkboxes with the same name (standard setup) but you also have the upDate and upDesc fields also set up with the same name.
That means that when you submit your form, on the server you will get (considering your example) a list of 3 upDate values, a list of 3 upDesc values and a list of 3 upisActive checkboxes. Well... not quite!
The problem is your checkboxes and the code you use to read the values to update.
First, checkboxes are not sent on the request if they are not checked. That means that, depending on your selection, on the server you will get a list of upisActive values of length 0, 1, 2 or 3.
Second, you then have this code on the server:
String[] values = request.getParameterValues("upisActive");
...
for (int i = 0; i < values.length; i++) {
...
val = values[i];
hdvo.setDate(upForm.upDate[i]);
hdvo.setDesc(upForm.upDesc[i]);
...
}
In you example, you check the third checkbox and submit your form. That means that String[] values will be of length 1 because only the selected checkbox is send to the server. But the input fields are always sent in 3 upDesc and 3 upDate.
Then you loop-it (once) and extract upForm.upDate[0] and upForm.upDesc[0]. This way, you update the first row by checking the third checkbox.
Other problems:
1) You have used the same identifier in the following code (it's asking for trouble):
<logic:iterate name="specialResult" id="specialResult"...
2) You are using classic inputs and added property attribute to it:
<input type="text" ... property="upDate" />" property="upDate" ...
3) Not sure that the browser guaranties that the fields will be sent in the exact matching order each time, so using a single counter is, I guess, just "hoping" for the same order.
4) Also, read this

Categories