Inserting into database from input by clicking a button - java

I have done the entire coding but data isnot getting inserted in the database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection =
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/userinfo?user=root&password=admin");
Statement statement = connection.createStatement() ;
resultset = statement.executeQuery("select * from item") ;
Now this is the part where i have done the connection and i think it is okay because in first part where i display values from database it is working
Now that i have done this in the next part i have taken input values from input boxes
<input type="submit" value="RECEIVE" style="width:100px; height:40px"
name="receive ">
now <%
PrintWriter pw = response.getWriter();
PreparedStatement pst = null;
if(request.getParameter("receive")!=null)
{
String dob=request.getParameter("datepicker");
String supplier=request.getParameter("supplier");
String type=request.getParameter("type");
String quantity=request.getParameter("quantity");
String queryString = "INSERT INTO stock_quantity values(?,?,?,?)";
pst = connection.prepareStatement(queryString);
pst.setString(2,dob);
pst.setString(3,supplier);
pst.setString(4,type);
pst.setString(5,quantity);
int i = pst.executeUpdate();
if(i!=0){
%>
<script language="javascript">
alert("Send sucess");
</script>
<%
}
else{
%>
<script language="javascript">
alert("Enter all data");
</script>
<%
}
}
%>
The data doesnt gets inserted.. Find the problem in the code

Don't make connection with db in first controller(in your case in jsp), just send your data to another controller, and there you can insert it to db. You can use either #Requestparam("param") to get single parameters, or #ModelAttribute("name") to get entire POJO object(where you will have your all parameteres).
So your html file would look like (in thymeleaf) you need to change some of thymeleaf things to jsp:
<form action="#" th:action="#{/save}" th:object="${yourObject}" method="post">
<div>
<label for="quantity">quantity:</label>
<input type="quantity" th:field="*{quantity}">
</div>
<button type="submit">Submit</button>
</form>
And your second controller:
#PostMapping("save")
public String reset(#ModelAttribute(value = "yourObject") YourPOJOClass request) {
//save to DB
}
If you want to accept parameters, not entire object, add name parameter to jsp/html
for example:
<div>
<label for="quantity">quantity:</label>
<input type="quantity" th:field="*{quantity}" name="quantity">
</div>
And in controller you can get this parameter like that:
#PostMapping("save")
public String reset(#RequestParam("quantity") String quantity)

Related

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?

How to pass a value from one jsp to another jsp page?

I have two jsp pages: search.jsp and update.jsp.
When I run search.jsp then one value fetches from database and I store that value in a variable called scard. Now, what I want is to use that variable's value in another jsp page. I do not want to use request.getparameter().
Here is my code:
<%
String scard = "";
String id = request.getParameter("id");
try {
String selectStoredProc = "SELECT * FROM Councel WHERE CouncelRegNo ='"+id+"'";
PreparedStatement ps = cn.prepareStatement(selectStoredProc);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
scard = rs.getString(23);
}
rs.close();
rs = null;
} catch (Exception e) {
out.println(e.getLocalizedMessage());
} finally {
}
%>
How can I achieve this?
Using Query parameter
<a href="edit.jsp?userId=${user.id}" />
Using Hidden variable .
<form method="post" action="update.jsp">
...
<input type="hidden" name="userId" value="${user.id}">
you can send Using Session object.
session.setAttribute("userId", userid);
These values will now be available from any jsp as long as your session is still active.
int userid = session.getAttribute("userId");
Use sessions
On your search.jsp
Put your scard in sessions using session.setAttribute("scard","scard")
//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.
And in your next page you retrieve it using session.getAttribute("scard")
UPDATE
<input type="text" value="<%=session.getAttribute("scard")%>"/>
Use below code for passing string from one jsp to another jsp
A.jsp
<% String userid="Banda";%>
<form action="B.jsp" method="post">
<%
session.setAttribute("userId", userid);
%>
<input type="submit"
value="Login">
</form>
B.jsp
<%String userid = session.getAttribute("userId").toString(); %>
Hello<%=userid%>
How can I send data from one JSP page to another JSP page?
One of the best answer which I filtered out from above discussion.
Can be done in three ways:
using request attributes:
Set the value to send in request attribute with a name of your choice as request.setAttribute("send", "valueToSend") and retrieve it on another jsp using request.getAttribute("send");
using session attributes
Similar to above but using session object instead of request.
using application attributes
Same as 1 and 2 above but using application object in place of request and session.
Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp'
Make three hidden text boxes and a button that is click automatically(using javascript).
//Code to written in 'show.jsp'
<body>
<form action="display.jsp" method="post">
<input type="hidden" name="u1" value="<%=u1%>"/>
<input type="hidden" name="u2" value="<%=u2%>" />
<input type="hidden" name="u3" value="<%=u3%>" />
<button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
<script type="text/javascript">
document.getElementById("qq").click();
</script>
</body>
// Code to be written in 'display.jsp'
<% String u1 = request.getParameter("u1").toString();
String u2 = request.getParameter("u2").toString();
String u3 = request.getParameter("u3").toString();
%>
If you want to use these variables of servlets in javascript then simply write
<script type="text/javascript">
var a=<%=u1%>;
</script>
Hope it helps :)

I want to display the quantity of the selected item of a drop down list in a textbox. The data is stored in database

The code for retrieving data from database into Drop Down List.
<%
DataSource data = new MysqlDataSource();
Connection con = data.getConnection("root","system");
System.out.println("Connected to MySQL");
PreparedStatement pre = con.prepareStatement("select * from library.booklist");
ResultSet result = pre.executeQuery();
%>
<tr>
<font color="black" size="5"> <td> Book List : </td> </font>
<td> <select name= "BookList" id="booklist" onchange="show()">
<option> - select - </option>
<%
while (result.next())
{
String name = result.getString("Book");
System.out.println("Output Done");
%>
<option value="<%=name%>"> <%=name%></option>
<%
}
%>
</select></td>
</tr>
<tr>
<%
/* my code for displaying quantity is below but it's not working. I am new to jsp, so don't know how to populate the textbox. */
String value = request.getParameter("BookList");
pre = con.prepareStatement("select Quantity from library.booklist where Book = ? ");
result = pre.executeQuery();
%>
<font color="black" size="5"><td> Quantity : </td>
<%
while (result.next())
{
int quantity = result.getInt("Quantity");
System.out.println("quantity dikha raha hai");
%>
<input name = "Quantity" type = "text" size = "25" readonly = "readonly" value = "<%=quantity%>"> <%=quantity%> </input>
<%
}
%>
</td>
</tr>
Edit
You need to pass your BookList parameter to your prepared statement:
String value = request.getParameter("BookList");
pre = con.prepareStatement("select Quantity from library.booklist where Book = ? ");
pre.setString(1, value); // <------
result = pre.executeQuery();
Otherwise your query does not know which Book to select.
Original
You haven't said what the actual problem is, but your HTML markup has problems that definitely aren't helping.
Don't use the <font> tag. It is not supported in
HTML5.
Your second <font> needs a closing </font>.
You have a closing </td> tag at the end with no opening <td>.
The <input> tag is a void element, meaning it does not accept content between opening and closing tags. Write it as <input type="text" name="Quantity" .../>
Clean up those things and your problem might be fixed, or at least more obvious.

Display not null values in query in jsp

In this portion of the code:
try {
connection = DriverManager.getConnection(
connectionUrl + dbName, userId, password);
statement = connection.createStatement();
String sql = "SELECT text_pub, path_photo FROM publication,publier, consomateur WHERE publication.id_publication=publier.publication_id_publication AND publier.users_id_user=consomateur.code_bar AND consomateur.code_bar = "+idUser+" AND 'path_photo' IS NOT NULL AND 'text_pub' IS NOT NULL";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
%>
<tr bgcolor="#8FBC8F">
<td><%=resultSet.getString("text_pub")%></td>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130"></td>
<%}
%>
I'm trying to select two values from my table, some of the values can be null, for example I can have a value for my column text_pub and not have a value in my column path_photo and vice versa, so in case I have text_pub and don't have path_photo, I want to display only the text_pub, but the probleme is that the value of text_pub is displayed but also the value of path_photo which is null.
PS: I know that treatements like these are better done in servlets, but I really want to make it work in a jsp. Thank you.
Either add a IFNULL check to the sql query:
SELECT IFNULL(text_pub,DEFAULT("")), IFNULL(path_photo,DEFAULT("")) FROM publication,publier,...
or add a check for the return value of resultSet.getString(..)
String text = resultSet.getString("text_pub");
if (text==null) {
text = "";
}
Edit:
in case I have text_pub and don't have path_photo, I want to display
only the text_pub this answer doesn't cover this
<%
while (resultSet.next()) {
String pub = resultSet.getString("text_pub");
if (pub==null) {
pub = "";
}
String photo = resultSet.getString("path_photo");
%>
<tr bgcolor="#8FBC8F">
<td><%= pub %></td>
<%
if (photo!=null) {
%>
<td><img src="images/<%=photo%>" width="150" height="130"></td>
<%
}
}
%>
I know that treatements like these are better done in servlets, but I really want to make it work in a jsp.
You're wrong here. This kind of things are handled in JSP, not in servlet, since logic to present the contents in the view belongs to the View (JSP) and not to the Controller (Servlet). Since you're using scriptlets, you should use an if sentence to validate if you should display the image or not:
while (resultSet.next()) {
%>
<tr bgcolor="#8FBC8F">
<td><%=resultSet.getString("text_pub")%></td>
<td>
<%
if (resultSet.getString("path_photo") != null) {
%>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130">
<%
}
%>
</td>
</tr>
<%
}
%>
If you don't want to display anything if resultSet.getString("text_pub") is null:
while (resultSet.next()) {
if (resultSet.getString("text_pub") != null) {
%>
<tr bgcolor="#8FBC8F">
<td><%=resultSet.getString("text_pub")%></td>
<td>
<%
if (resultSet.getString("path_photo") != null) {
%>
<img src="images/<%=resultSet.getString("path_photo")%>" width="150" height="130">
<%
}
%>
</td>
</tr>
<%
}
}
%>
If you happen to write the code in the right way and use a Servlet to handle the data retrieval from database, fill the data in a List<SomeEntity>, add this list into a request attribute (probably with name "photoList") and forward to the desired JSP, then you could use JSTL to control the flow of the image display:
<c:forEach items="${photoList}" var="photo">
<tr bgcolor="#8FBC8F">
<td>${photo.textPub}</td>
<td>
<c:if test="${not empty photo.pathPhoto}">
<img src="images/${photo.pathPhoto}" width="150" height="130">
</c:if>
</td>
</tr>
</c:forEach>

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