Edit and update same textbox - java

I have a database Table where I can edit a value. I want to update the same, below is the code that I have tried.
The table code is as below
<table border="1px">
<tr>
<td><b>DBID</b></td>
<td><b>Query Raised</b></td>
<td><b>Time Raised</b></td>
<td><b>Query Answered</b></td>
<td><b>Time Answered</b></td>
</tr>
<%
try {
ps = con.prepareStatement("Select DBID, Query_Raised, TR, Query_Answered, TA from Scope1 where TR!='null'");
rs = ps.executeQuery();
while(rs.next()) {
%>
<tr>
<td><%=rs.getString("DBID")%></td>
<td><input type="Text" value="<%=rs.getString("Query_Raised")%>" name="Updat"></td>
<td><%=rs.getString("TR")%> </td>
<td><%=rs.getString("Query_Answered")%></td>
<td><%=rs.getString("TA")%></td>
<td><input type="Submit" value="Update"></td>
</tr>
<%
} // while loop ends here
rs.close();
con.close();
} catch(Exception e) {
out.println(e);
}
%>
</table>
and the update query that is used is:
String a = request.getParameter("Updat");
ps = con.prepareStatement("Update Scope1 Set Query_Raised = '" + a + "'");
int i = ps.executeUpdate();
if(i == 1) {
out.print("Done");
} else{
out.print("Erro");
}
I wanted to know the where condition that I should use to update the data in same page.
Thanks

I understand the first code part in the question is a JSP say update.jsp and the second part it seems is your servlet, say UpdateServlet.
So in your update.jsp on every row you have an <input type="text"> and submit button, but the <form> I think is only one which must be outside the <table>, so here goes my solution (choose any one):
Use multiple <form> tags for each row, like
<form action="whatever_action_you_have_which_calls_the_servlet"
name="form<%=rs.getString("DBID")%>"
id="formID<%=rs.getString("DBID")%>">
// Including name and id so that the different forms remain unique
<tr>
<td><%=rs.getString("DBID")%></td>
<td><input type="Text" value="<%=rs.getString("Query_Raised")%>" name="Updat"></td>
<td><%=rs.getString("TR")%> </td>
<td><%=rs.getString("Query_Answered")%></td>
<td><%=rs.getString("TA")%></td>
<td><input type="Submit" value="Update"></td>
</tr>
</form>
So when you click on submit it would submit the <form> for which the submit button was clicked and would submit only the input which was edited and voila! your servlet code also works fine.
You can have both the blocks of code in the same JSP, then use the <form> code snippet as described in point#1 and the second code snippet would be:
String a = request.getParameter("Updat");
if ( (a is not empty) or (a is not null) ) {
ps = con.prepareStatement("Update Scope1 Set Query_Raised = '" + a + "'");
int i = ps.executeUpdate();
if(i == 1) {
out.print("Done");
} else{
out.print("Error");
}
}
...
<form action="whatever_action_you_have_which_will_call_this_JSP" ...>
<tr> ... your code as in point#1
</tr>
</form>
Use ajax and other javascript DOM manipulative methods to accomplish this as said by Endy.
For this you will need to have JSP (to display) & Servlet (to update the code).
This might be a little more effort but you will learn Ajax and will be a little more close to real world.
By far jQuery ajax is the simplest to use.
Note:
Just for the record, I know you might be practicing but if you are planning to use it in a real project then please read ahead.
It is a bad-practice to use scriptlets in JSP (unless really required and that too if it is for view-level logic and not business or data-level logic) and even worse is to use JDBC code inside a JSP. So it would be really great if you could follow f_puras's advice.
If you are wondering why I should listen to your unsolicited advice then here is some food for thought:
How to avoid scriptlets in JSP
Scriptless JSPs
Why JSP = JDBC is bad
Hope this helps.

You can either use AJAX to post the data to a page that handles the updating, then return the result as a callback, see http://api.jquery.com/jQuery.post/.
Other solution is to forward user back to the page with the form after you have processed the submission.
Third solution is to submit the data to the same page and parse/update it there.

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.

Why is the delete function not working in my jsp file?

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?

Refreshing Page With A Parameter in JSP

I have a JSP page in my web application and i want to refresh the page with the parameter of option.
<select class="form-control combobox" name="education" >
<option value="" disabled selected hidden>Choose an education</option>
<option>English</option>
<option>French</option>
<option>Dutch</option>
<option>Spanish</option>
</select>
I want to use this parameter for querying my database again. Forexample;
<%
BookDAO bdao = new BookDAO();
for (TblBooks book : bdao.getAllBooks()) {%>
<tr>
<td><%=book.getTittle()%></td>
<td><%=boek.getAuthor()%></td>
<td><%=boek.getCategory()%></td>
<td><%=boek.getEducation()%></td>
<td><input type='checkbox' name ='chk1' /></td>
</tr>
<% }%>
I can get the parameter with request.getParameter("education") but how can i refresh page and query again with this parameter?
In Javascript, You can ask a web page to reload itself (the exact same URL) by:
location.href = location.href;
You can ask a web page to load a different location using the same mechanism:
location.href = 'http://www.google.com'; // or whatever destination url you want
You can get the value of a select control (which needs to have an id attribute):
var ctrl = document.getElementById("idOfSelectControl");
var selectedOption = ctrl.options[ctrl.selectedIndex].value;
So, if you update your JSP to give the control an id:
<select class="form-control combobox" id="education" name="education" >
you should be able to reload the page:
var educationControl = document.getElementById("education");
var selectedOption = educationControl.options[educationControl.selectedIndex].value;
location.href = "http://mysite.example/mypage?education=" + selectedOption;
By the help of Jason i have solved it. I added an onchange event to my select tag
onchange="changeThePage()"
Then i defined a javascript function.
function changeThePage() {
var selectedOption = "book.jsp?education=" + $("#education option:selected").text();
location.href = selectedOption;
}
Then i got the parameter by
String education = request.getParameter("education");
Then i added String education as parameter to my bdao.getAllBooks(education)) method for to query.
'
<script>
function abc(){
var yourSelect = document.getElementById( "ddlViewBy" );
var val = yourSelect.options[ yourSelect.selectedIndex ].value;
//window.location.href=window.location.href;
alert(val);
window.location.replace("index.jsp?name="+val);
}
</script>
<select id="ddlViewBy" onchange="abc()">
<option>select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<%
String name=request.getParameter("name");
if(name!=null){
%>
<table>
<tr>
<td>author<%=name%></td>
<td>book name<%=name%></td>
</tr>
</table>
<%
}
%>
Hi,
try this, this will be helpful,
when you select a value it will call abc, function and then you are assigning that value in scriptlet..and also page is refreshing. in scriptlet you can access that value using request.getParameter("name").
now you can write your code inside scriptlet..hope helpful for someone.. :)
thanks...

Filter table values on JSP with values from SQL database

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.

Dynamically display multiple images from database to jsp?

Hello fellow stack overflowers.
I am stuck on a certain portion of a project and am looking for some advice.
I have a photo gallery page in jsp that is set up to display all the listings of photo albums and the photos within them based on the user's interest. It is currently set up so that whatever 'photo' option is selected will be redirected to another jsp with the outputstream decoding on that particular page. However, in order to see another photo or image, the user has to go 'back' to the photo galleries page and select another image for a new photo.
Is there a way to set up the galleries page so that all the photos can be dynamically displayed on the page OR is there possibly a way put some direction on the display.jsp page so that the user can simply click from one photo to the next?????
Code is below.
<div id="subSlideshow">
<table>
<tr>
<td id="subpageSlideshow">
<table>
<tr>
<td>
<h1 id="subpageTitle">Galleries</h1>
<form action="gallery" method="get">
<%try{
Connection conn = GalleriesConnection.connect();
Statement st = conn.createStatement();
String sql = "SHOW TABLES IN GALLERIES;";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){%>
<input class="wineDiv" type="submit" name="gallery" value="<%=rs.getString(1).toLowerCase() %>" />
<%}
rs.close();
st.close();
GalleriesConnection.close(conn);
}
catch(Exception e){
}%>
</form>
<td>
</tr>
<tr>
<td>
<h1 id="subpageTitle">Images</h1>
<form action="pictures/display.jsp">
<%try{
Connection conn = GalleriesConnection.connect();
Statement st = conn.createStatement();
String sql = "SELECT PHOTO_NAME FROM "+gallery+" ;";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
String photoName = rs.getString(1);
%>
<input class="wineDiv" type="submit" name="photo" value="<%=photoName %>" />
<% }
rs.close();
st.close();
GalleriesConnection.close(conn);
} catch(Exception e){
}%>
</form>
</td>
</tr>
</table>
</td>
<td id="subpageInfo">
<h1 id="subpageTitle">Click on an image to see a larger view</h1>
<div id="slider">
<script src ="js/slides.js" type="text/javascript"></script>
<img id="1" src="pictures/winery_image1.jpg" />
<img id="2" src="pictures/winery_image2.jpg" />
<img id="3" src="pictures/winery_image3.jpg" />
<img id="4" src="pictures/winery_image4.jpg" />
<img id="5" src="pictures/winery_image5.jpg" />
</div>
<input class="previous" onclick="prev(); return false;" value="Previous Image" />
<input class="next" onclick="next(); return false;" value="Next Image" />
</td>
</tr>
</table>
</div>
All the action on the page is within this div. The first connection command retrieves all the table names in the database and spits the table names out on submit buttons. Additionally, the images currently listed in the subpageInfo are one of the desired spots on where I would like images from the database to be embedded. They make a nice little fadeOut() fadeIn() transition when the next and previous buttons are selected.
The second connection gets all the names of the photos and puts them in the form of submits as well. Selected photo names are sent to this page:
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%
byte[] imgData = null;
%>
<jsp:scriptlet>
String photo = request.getParameter("photo");
</jsp:scriptlet>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:8889/GALLERIES","myusername","mypassword");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT PHOTO FROM PHOTOS WHERE PHOTO_NAME = '"+photo+"';");
while (rs.next()) {
Blob image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());
}
// display the image
response.setContentType("image/png");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
out.println("Unable To Display image");
out.println("Image Display Error=" + e.getMessage());
return;
}
%>
This program does everything it is asked to do, but I am having some difficulty on making it more user friendly. The desired effect is either embed the images in the subpageInfo div or to have some directives on the display.jsp page to go from one image to the next.
As always any and all help is greatly appreciated.
If you want to present a set of pictures I'd go for:
http://lokeshdhakar.com/projects/lightbox2/
Or if you want to do everything yourself, use only one page - use the selection form you mentioned and after sumbition, reload the same page including a decoded image into it. You can setup a javascript so that everytime user selects another picture the form gets submited so user doesn't have to click submit.
But I suggest rethinking the whole thing. What's your goal? Is this approach the best one? I'm usually way too deep in technical stuff that I don't see the solution user expects. That's why I ask random people to help me out.
Also - scriptlets? ew! Use JSTL and prepare everything in the controller. Or use Primefaces, JSF, managed beans and all the stuff that was made for this purpose.

Categories