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
Related
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 have a p-table with p-editable column which is a dropdown as follows:
<ng-template pTemplate="body" let-rowData let-columns="columns" let-editing="editing">
<tr style="font-size:10px;" [pEditableRow]="rowData" >
<ng-container *ngFor="let col of columns" [ngSwitch]="col.field">
<td *ngSwitchCase="'dob'" [colSpan] = "1">
{{rowData[col.field] | date: 'dd-MMM-yyyy hh:mm'}}
</td>
<td *ngSwitchCase="'updated'" [colSpan] = "1">
{{rowData[col.field] | date: 'dd-MMM-yyyy hh:mm'}}
</td>
<td *ngSwitchCase="'assignedTo'" [colSpan] = "1" pEditableColumn>
<p-cellEditor>
<ng-template pTemplate="input">
<p-dropdown [options]="assigneList" [(ngModel)]="rowData[col.field]" (onChange)="changeAssigne($event)" ></p-dropdown>
</ng-template>
<ng-template pTemplate="output">
{{rowData[col.field]}}
</ng-template>
</p-cellEditor>
</td>
<td *ngSwitchDefault [colSpan] = "1">
{{rowData[col.field]}}
</td>
</ng-container>
</tr>
</ng-template>
As per primeNg documentation assigneList has a label, value in addition i have an id field that is unique for each row.
My dropdown works perfectly fine foreach row and corresponding element gets selected perfectly. However I have a requirement where onChange of dropDown i have to update the DB.
My onChange function which is changeAssigne(event), currently displays only value. I want the onChange to give me the entire object.
Component.ts code
...///
assigneList : BoardAssigneDTO[] =[];
this.assigneList = this.data.assigneList;
///..
and model is as follows:
export class BoardAssigneDTO {
id : Number = 0;
label : string = '';
value : string = '';
}
So in this case my onChange should have object in the form BoardAssigneDTO which has id, label, value. How can this be done.
Initially i was trying to pass just object as id, Name, Country but dropdown wouldnt work. So followed as per documentation primeNG table edit with dropdown and created label and value pair which is concat of name and country. But my unique key is id and I want to pass this id to the backend. How is this possible. Any suggestions highly appreciated.
This doesn't work as it is for normal dropdowns if it is inside a p-table.
By default p-dropdown value is mapped to value property in option list object.
I have used the below approach to fix achieved this long time back.
Add the event and pass the value and list:
<p-dropdown [options]="assigneList" [(ngModel)]="rowData[col.field]" (onChange)="changeAssigne(assigneList,rowData[col.field])" ></p-dropdown>
Find the object and assign to model in changeAssigne method
changeAssigne(list,value){
// find out the object from list
let selectedItem = list.filter((item)=>{
return item.value === value;
});
console.log(selectedItem);// selected option object
}
I have created a table to display data and there is a checkbox next to each of the data. I want to create a function where if the user click the checkbox of that data and press the delete button, the data will be remove from the table and the database. I have came up with the code but it doesn't remove the data. What is the problem with my code ?
Display on Webpage
HTML
<%
String id = request.getParameter("hiddenID");
String sql1="";
{
sql1 = "select * from exercise1";
PreparedStatement pstmt1=conn.prepareStatement(sql1);
ResultSet rs1 = pstmt1.executeQuery();
while(rs1.next()){
String arm = rs1.getString("Arm");
String time1 = rs1.getString("Time1");
out.println("<tr>");
out.println("<td style = 'width: 20%'>");
out.println(arm);
out.println("</td>");
out.println("<td style = 'width: 5%'>");
out.println(time1);
out.println("</td>");
%>
<td style="width: 5%"><input class="mychkbox" type="checkbox"
value="<%=id%>" form="multipleDele" name="DeleteChkbox" /></td>
<%
out.println("</tr>");
}
conn.close();
}
%>
This is my delete.jsp file
<%
String[] id = request.getParameterValues("DeleteChkbox");
int count=0;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL = "jdbc:mysql://localhost/medicloud?user=root&password=root";
// Step 3: Establish connection to URL
conn = DriverManager.getConnection(connURL);
if (id != null)
{
for(int i=0;i<id.length;i++){
String sqlStr = "DELETE from exercise1 WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setInt(1, Integer.parseInt(id[i]));
//pstmt.setInt(1, Integer.parseInt(id[i]));
int rec=pstmt.executeUpdate();
if (rec==1)
count++;
}
}
//System.out.println(functions);
%>
<form action="exercise.jsp" method="post">
<label><%=count%> record(s) deleted!!</label>
<input type="submit" value="Return" name="ReturnBtn" />
</form>
<%
conn.close();
} catch (Exception e) {
out.println(e);
}
%>
The id you are writing to the checkbox value is not coming from the database results. It is being retrieved in the JSP from a request parameter:
String id = request.getParameter("hiddenID");
... and then being written to every checkbox field:
<input class="mychkbox" type="checkbox" value="<%=id%>" form="multipleDele" name="DeleteChkbox" />
You aren't writing a different id for each checkbox.
As such, it probably is not the id of any of the database records, and therefore none of them are being deleted.
You should be reading the id of each record in your while loop when building the HTML.
I suspect you need something like this:
<input class="mychkbox" type="checkbox" value="<%=rs1.getString("id")%>" form="multipleDele" name="DeleteChkbox" />
Your image has three columns: arm exercises, number of times and action. The DeleteChkboox field will only tell you if the field is selected or not for a particular row. You need to get the ids that have been selected for deletion. Unchecked checkboxes will not show up in an array of checkboxes so your form has to take this into account. It needs to look something like
<form action = "...">
<input type="submit" value="delete">
<input type="submit" value="assign">
<table>
<c:forEach items="${ records }" var="r">
<tr>
<td>
${ r.exercise }
</td>
<td>
${ r.times }
</td>
<td>
<input type="checkbox" value="${ r.id }" name="userAction">
</td>
</tr>
</c:forEach>
</table>
</form>
Then you need to change your jsp so that you get the ids of the selected rows. Change the jsp part that iterates your ids to
<%
// get array of ids
String[] ids = request.getParameterValues("userAction");
int count=0;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL = "jdbc:mysql://localhost/medicloud?user=root&password=root";
// Step 3: Establish connection to URL
conn = DriverManager.getConnection(connURL);
if (ids != null) {
for(int i=0; i < ids.length; i++) {
String sqlStr = "DELETE from exercise1 WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setInt(1, Integer.parseInt(ids[i]));
int rec=pstmt.executeUpdate();
if (rec==1) {
count++;
}
}
}
}
%>
That aside, it's generally not the best of ideas to be running sql updates in jsps if you can help it. Consider moving this logic to a controller class and using the jsp layer for presentation only.
EDIT
As per your comment "it's not working", instead of looking at this particular problem (why doesn't the code you wrote remove the data) you have to look at the bigger picture: what is the problem you are trying to accomplish?
It looks something like this, in plain English:
Show a user a set of records
Allow the user to mark the records they'd like to delete (array of checkboxes); allow the user to submit this information (the record ids)
Process (delete) the submitted ids
Step 1
Iterate over a list of records in jsp, inside a <form> element
For each record, create a checkbox whose value is that record's id
Step 2
Add a delete button allowing the user to submit the form of ids
Step 3
Process the submitted information: get the list of ids submitted in the request, iterate over it and delete the records one by one
Which step are you stuck on?
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'm trying to make an servlet-based application that gets values from a SQL database and presents them in a dynamically created table on a JSP, which is already working. The next step is to create some sort of filter that only exhibits the table lines that have a certain value in one of its columns. My idea was to add a dropdown menu and select the lines with that item in the "Problem" column. I believe that to be a bit straightforward. The catch is that the values to fill in that dropdowm menu are in a table "Problem" on the SQL database; and each of its rows have the id and name attributes. Currently, I'm trying to go with the name attribute and trying to compare it with the "Problem" column that is obtained from my query (SQL Server 2008 R2) (
SELECT h.[name], c.[department], p.[name] AS problem, it.[name] AS interaction, ip.[title], ip.[date]
FROM [Database].[dbo].[Input] ip, [Database].[dbo].[Interaction] it, [Database].[dbo].[Problem] p, [Database].[dbo].[HelpdeskUser] h, [Database].[dbo].[Costumer] c
WHERE h.[id] = ip.[user_id]
AND it.[id] = ip.[interaction_id]
AND c.[id] = ip.[costumer_id]
AND p.[id] = ip.[problem_id]
ORDER BY date DESC";
), but, obviously, I'm hitting my head against the wall because this isn't working. So I'd like to ask you if you can help me somehow with this and if I'm overlooking something obvious that could unlock this whole process.
ViewInputServlet.java
public class ViewInputServlet extends GenericServlet {
public static final String PROBLEMS = "problems";
public static List<Problem> problems;
private void setProblems(HttpServletRequest req, HttpServletResponse resp) throws EmptyResultSetException {
Session session = HibernateUtilities.getSessionFactory().openSession();
if (ProblemDAO.hasRecords(session)) {
problems = ProblemDAO.selectProblems(session);
req.setAttribute(PROBLEMS, problems);
}
}
}
ViewInput.jsp
<% List<Problem> problems = (List<Problem>) request.getAttribute(ViewInputServlet.PROBLEMS); %>
<div class="innerField">
<table class="datatable" id="tableResults">
<thead>
<tr>
<th>NAME</th>
<th>DEPARTMENT</th>
<th>PROBLEM</th>
<th>TITLE</th>
<th>DATE</th>
</tr>
</thead>
<% for (Issue issue : (List<Issue>) request.getAttribute(ViewInputServlet.LIST)) {%>
<tr>
<td><%=issue.getName()%></td>
<td><%=issue.getDepartment()%></td>
<td id="prob_type"><%=issue.getProblem()%></td>
<td><%=issue.getTitle()%></td>
<td><%=issue.getDate()%></td>
</tr>
<%}%>
</table>
<div class="label">Show by Problems: </div>
<div class="field">
<div class="ui-widget">
<select name="<%=ViewInputServlet.PROBLEMS%>" id="chooseProblems">
<%if (problems != null) {
for (Problem problem : problems) {%>
<option value="<%=problem.getName()%>"><%=problem.getName()%></option>
<%}
}%>
</select> <input type="button" value="Reset" id="btn_reset" />
</div>
</div>
</div>
(the column "Problem" is the key here: it's the one I want to filter values by, and that's why I've given it an ID, in a previous attempt that failed)
Functions.js
$("#chooseProblems").change(function () {
$("#tableResults").find("td").each(function () {
if ($(this).text !== $("#chooseProblems").val())
$(this).hide();
else
$(this).show();
});
});
If there's some more info you require or doubts on my reasoning, ask away :)
Could there be a problem with your string comparison in java script. should you be using match method instead of !==.
Also when you say $(this).text or $(this).hide or $(this).show , you are actually referring to column of row not the row.