Image wont load in my JSP page from MySQL database - java

I created table in database and I have problem with loading picture from that database. Type of data that I used for img is blob, I have good connection with database, all other data is showing on my jsp page but picture wont load. Data type of img is .jpg, dimensions of picture are 250x250 and size about 14.2 kb
CREATE TABLE `akcija` (
`idakcija` int(11) NOT NULL AUTO_INCREMENT,
`naziv` varchar(45) NOT NULL,
`cena` varchar(45) DEFAULT NULL,
`img` blob,
PRIMARY KEY (`idakcija`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
I load data by following insert query:
INSERT INTO `games1`.`akcija` (`naziv`, `cena`,`img`)
VALUES ('TEST','3500', 'C:\\Users\\mlade\\OneDrive\\Desktop\\New Folder (2)\\WebApplication1\\web\\gallery\\ufc4.jpg');
I also tried by right click on field for img and selecting Load Value from File, and then selecting img that I want. And third option that I tried is right click -> open value in editor -> Load image -> Apply -> and Apply on changes
Here is my JSP page
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#include file="connection.jsp"%>
<!DOCTYPE html>
<html>
<head>
<%#include file="header.jsp" %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<div class="container">
<img class="img-fluid " src="https://gifcdn.com/1h64r34cpd6coj0dhl.gif" alt="mailtimers.com">
</div>
<table class="table table-sm">
<thead>
<tr>
<th scope="col">Ime igrice</th>
<th scope="col">Cena</th>
<th scope="col">Slika</th>
</tr>
</thead>
<% String id = request.getParameter("id");
Blob img = null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = DriverManager.getConnection(connectionUrl + database, userid, password);
statement = connection.createStatement();
String sql = "select * from akcija";
resultSet = statement.executeQuery(sql);
int i = 0;
while (resultSet.next()) {
%>
<tbody>
<tr>
<td><%=resultSet.getString("naziv")%></td>
<td><%=resultSet.getString("Cena")%></td>
<td><img src="<%=resultSet.getBlob("img")%>" width="250" height="250"/></td>
</tr>
</tbody>
<%
i++;
}
} catch (Exception e) {
out.println("Problem");
return;
} finally {
try {
resultSet.close();
statement.close();
connection.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
%>
</table>
</body>
</html>
Data from column naziv and cena is show on jsp page but image wont load. See picture
Picture not loading
Here is screenshots of my project structure. Also screenshots of DB and query that I used to insert data in DB

Related

Image uploading issue in JSP

I want to upload an image file in my project directory folder named Images and store the image name in a database.
The file name has been saved in the database and my image retrieved by the browser properly, but when I check my directory folder named Images it is empty.
My questions is: Where is my file stored and why can't I see the image file in my folder?
This is my Index.jsp file
<%--
Document : index
Created on : Mar 15, 2018, 7:30:15 PM
Author : Lenovo
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form name="form1" method="post" enctype="multipart/form-data" action="insertimage.jsp">
<p>
<input type="file" name="ImageFile" id="ImageFile" />
</p>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</body>
</html>
This is my insertimage.jsp file
<%# page import="org.apache.commons.fileupload.servlet.ServletFileUpload" %>
<%# page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%# page import="org.apache.commons.fileupload.*"%>
<%# page import="java.util.*, java.io.*" %>
<%# page import="java.util.Iterator"%>
<%# page import="java.util.List"%>
<%# page import="java.io.File"%>
<%# page contentType="text/html;charset=UTF-8" %>
<%# include file="getcon.jsp"%> <!-- to connect a database-->
<%
try
{
String ImageFile="";
String itemName = "";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.getMessage();
}
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
String name = item.getFieldName();
String value = item.getString();
if(name.equals("ImageFile"))
{
ImageFile=value;
}
}
else
{
try
{
itemName = item.getName();
File savedFile = new File(config.getServletContext().getRealPath("/") + "Images\\" + itemName);
out.println("File Uploaded.." + itemName);
item.write(savedFile);
}
catch (Exception e)
{
out.println("Error" + e.getMessage());
}
}
}
try
{
st.executeUpdate("insert into test(image) values ('" + itemName + "')");
}
catch(Exception el)
{
out.println("Inserting error" + el.getMessage());
}
}
}
catch (Exception e)
{
out.println(e.getMessage());
}
%>
This is my retrieveimage.jsp file
<%# include file="getcon.jsp"%>
<html>
<head>
<title>View Image Page</title>
</head>
<body>
<table width="100%" border="0">
<!-- main content -->
<%
ResultSet rs=null;
try
{
rs = st.executeQuery("select image from test");
while(rs.next())
{
%>
<table width="70%" height="160" border="1" align="center">
<tr>
<!-- Mention Directory where your images has been saved-->
<td><img src="Images/<%=rs.getString("image") %>" width="115" height="128" /></td>
</tr>
</table>
<%
}
}
catch(Exception e)
{
out.print("" + e.getMessage());
}
%>
</table>
</body>
</html>
This is my connection file
<%#page import="java.sql.*" %>
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample", "root", "root");
Statement st = con.createStatement();
%>
The following has more chance of working.
File savedFile = new File(config.getServletContext().getRealPath("/Images/" + itemName));
savedFile.getParentFile().mkdirs();
...
Not sure whether the server is also Windows; on other systems path names are case-sensitive (Images with capital i).
You could provide a fixed itemName for testing.
The img tag might need to be:
<img src="/Images/ ...

SQLServerException: The result set has no current row

Running into the following 500 error:
javax.servlet.ServletException:
com.microsoft.sqlserver.jdbc.SQLServerException: The result set has no
current row.
I checked and I even have the rs.next() to push it to the next row.
Not sure why it is not pulling the QtyAvail
My table is called Inventory and it has a primary key of ProductID and an attribute called QtyAvail.
<%#page import="beans.Products"%>
<%#page import="java.lang.String"%>
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="beans.ItemLine"%>
<%# page import ="java.sql.*" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<jsp:useBean id="cart" class="beans.CartItems" scope="session"/>
<% //set up the Producst object
int QtyAvail = 0;
Products product = new Products();
String ProductID = request.getParameter("ProductID");
String productDescription = request.getParameter("Decscription");
String productQty = request.getParameter("ProductQty");
String productPrice = request.getParameter("ProductPrice");
String ProductName = request.getParameter("ProductName");
try{
//ger inv from SQL and make sure we have enough
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://clay.student.ad.fgcu.edu:1433;databaseName=ISM4154PartIteam02;user=4154Team02;password=Fgcu02;");
PreparedStatement ps = conn.prepareStatement("Select QtyAvail from Inventory where ProductID=?");
ps.setString(1, ProductID);
ResultSet rs = ps.executeQuery();
rs.next();
QtyAvail = rs.getInt("QtyAvail");
System.out.println(QtyAvail);
ps.close();
conn.close(); //Close the connections.
//Check that we have enough quantity on hand
`if(Integer.parseInt(productQty) <= QtyAvail) {
//a new LineItem is created and Attributes are set
ItemLine item = new ItemLine();
item.setProduct(product);
product.setProductDescription(productDescription);
item.setProductDescription(productDescription);
product.setProductQuantity(Integer.parseInt(productQty));
item.setProductQuantity(Integer.parseInt(productQty));
product.setProductPrice(Double.parseDouble(productQty));
item.setProductPrice(Double.parseDouble(productPrice));
cart.addItem(item);
//passes page to cart jsp
response.sendRedirect("CustomerCart.jsp");
}
else {
%>
<h3> Sorry! we only have currently" <%out.println(QtyAvail);%> "of <%out.println(ProductName);%> in Inventory </h3>
<h3> Please select a quantity amount we have in Inventory </h3>
<input type="button" name="continue" value="Continue Shopping" onclick="window.location='homePage.html'">
<% }
//}
//catch(Exception e){
//out.println("404 System Not Found");
// }
%>
</body>
</html>

Validate login form on jsp pages

Login Form (index2.html)
<html>
<head>
<title>Login Form</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body bgcolor="96D2C2">
<form name="ask_1" method="get" action="index24.jsp">
Username: <input type="text" name="id11"/> <BR>
Password: <input type="password" name="id22" /> <BR>
<input type="submit" value="Login" /> <BR>
<BR>
</form>
Create an Account
</body>
My JSP code in order to verify the login info and print to user success or not... (index24.jsp)`
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<% int j=0; %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Class.forName("com.mysql.jdbc.Driver");
String myDatabase = "jdbc:mysql://localhost:3306/mydb1?user=root&password=1234";
Connection myConnection = DriverManager.getConnection(myDatabase);
Statement myStatement = myConnection.createStatement();
String id11=request.getParameter("id11");
String id22=request.getParameter("id22");
String sqlString = "SELECT FROM users WHERE username='"+id11+"' AND password='"+id22+"' ";
ResultSet rs = myStatement.executeQuery(sqlString);
if(rs.next()) {
System.out.println("Success"); }
else {
System.out.println("Failed");
}
%>
</body>
</html>
The code given above is giving me the error, "The requested resource is not available.". Any suggestions and improvements to my code or edit are appreciated.
the Connection myConnection = DriverManager.getConnection(myDatabase);
is kind wrong because the getConnection() will not handle the url given as parameter String try to do it like this :
Connection myConnection = DriverManager.getConnection("jdbc:mysql://localhost/mydb1" , "root" , "1234");
you can check the documentation of that method , and dont'forhet to remove this line
String myDatabase = "jdbc:mysql://localhost:3306/mydb1?user=root&password=1234";
Try to close the "try {" block with
} catch (Exception e) {
e.printStackTrace(new java.io.PrintWriter(out));
}
to get more details about the error. It is a simple trick for developing jsps and should be removed in an official version of a web-site.
Also, it may be out of topic, but your code is susceptible to SQL injection. See more here
http://www.w3schools.com/sql/sql_injection.asp
Finally the problem was the server (GlassFish)... i used Apache Tomcat and works properly...

how to delete single recodrs from multiple row records like gridview in jsp page

I am trying to edit and delete a single record from multiple records.Here below is my sample record displaying on jsp page,
I can edit the record for each row easily using below code,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.util.List" %>
<%# page import="java.util.Iterator" %>
<%#page import="java.sql.ResultSet"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src="jquery1.11.0.min.js"></script>
</head>
<body>
<script type="text/javascript">
function editRecording(task_id) {
//alert(task_id)
url = "EditRecord";
window.location="/RTTSchecking/"+url+"?task_id="+task_id;
}
</script>
<table align="center" border="1px" width="80%" >
<thead>
<tr>
<th>User_Id</th>
<th>Class</th>
<th>Subject</th>
<th>Chapter</th>
<th>Planned_Features</th>
<th>Planned_Date</th>
</thead>
<%Iterator itr;%>
<%List data = (List) request.getAttribute("TaskData");
for(itr = data.iterator(); itr.hasNext();)
{
%>
<tr>
<% String s = (String) itr.next();
%>
<td style="background-color: yellow;">
<input type="text" name="tid" value="<%=s %>"></td>
<td><input type="text" name="tid" value="<%=itr.next() %>"></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><input type="button" value="edit" name="<%=s%>" onclick="editRecording(this.name);"></td>
<td><input type="button" value="delete" name="<%=s%>" onclick="deleteRecording(this.name);"></td>
<% } %>
</tr>
</table>
</body>
</html>
EditREcord(servlet):
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
String a=request.getParameter("task_id");
convty = new Connectivity();
con = convty.setConnection();
st = con.createStatement();
query = "select * from task_table where task_id='"+a+"'";
rset = convty.getResultSet(query, con);
}
catch(Exception e) {
}
finally {
request.setAttribute("EditData", rset);
RequestDispatcher dd= request.getRequestDispatcher("editdata.jsp");
dd.forward(request, response);
out.close();
//out.println(""+tid);
}
}
Above code working fine.But my problem is, i want to delete record based on User_id, Class, Subject, Chapter and Planned_Date so how can i get these values from single row (which want to delete row)?
how to achive this below code?,
<script type="text/javascript">
function deleteRecording(User_id,Class,Subject,Chapter,Date) {
//alert(task_id,Class,Subject,Chapter,Date)
url = "EditRecord";
window.location="/RTTSchecking/"+url+"?user_id="+User_id+"&Tclass="+Class+"&subject="+Subject+"&chapter="+Chapter+"&date="+Date;
</script>
once if i achieved above code then i can easily delete selected single record from multiple rows using below code,
try {
String uid=request.getParameter("user_id");
String class=request.getParameter("Tclass");
String sub=request.getParameter("subject");
String chap=request.getParameter("chapter");
String date=request.getParameter("date");
convty = new Connectivity();
con = convty.setConnection();
st = con.createStatement();
query = "delete from task_table where User_id='"+uid+"' and class='"+class+"' and subject='"+sub+"' and chapter='"+chap+"' and date='"+date+"'";
st.executeUpdate(query);
}
catch(Exception e) {
}
Note : I can do delete records using delete from task_table where User_id='"+uid+"';
but how to do with query = "delete from task_table where User_id='"+uid+"' and class='"+class+"' and subject='"+sub+"' and chapter='"+chap+"' and date='"+date+"'";
I hope someone will help me out.
Once you delete data from database that means it's deleted.
You just need to reload that page again on click of delete.
I hope you've found the solution to your problem by now. But in case you haven't, I ran into the same problem today, and after many experiments, I came up with the following syntax for deleting a row using multiple criteria:
" DELETE FROM table_name WHERE " +
" first_db_field_name = '" + matching_variable_name + "'" +
" and next_db_field_name = '" + next_matching_variable_name + "'" +
" and last_db_field_name = '" + last_matching_variable_name + "'";

importing values from java class to jsp

I am a novice in jsp. i am trying to access values from my java class into my jsp page. i went thru a lot of pages and implemented a lot of stuff and i thing i made it all into a mess.
this is my dao class method
public DisplayDO Display(DisplayDO disDo)throws Exception
{
System.out.println("inside dao display");
Connection conn = null;
try{
conn = DbConnection.getConn();
}
catch(Exception e)
{
e.printStackTrace();
}
Statement statement = null;
try{
statement = conn.createStatement();
}
catch(SQLException e)
{
e.printStackTrace();
}
System.out.println("dbconnection established");
int userid=disDo.getUserid();
try
{
System.out.println("inside dao try");
System.out.println("userid = "+userid);
String str= "Select address_id from user where user_id =910";
//+userid;
PreparedStatement ps= conn.prepareStatement(str) ;
ResultSet rs=ps.executeQuery(str);
int address1=0;
while (rs.next())
{
address1= rs.getInt(("address_id"));
}
int addressid = 0;
addressid = address1;
System.out.println("values of addressid= "+ addressid +"address1= "+ address1);
System.out.println("query execution successfull");
str="select name,street_name,city,gender,reg_date from user,address,registeration where user.address_id="+addressid+" && address.address_id= "+addressid+" && registeration.user_id="+userid+" ;";
rs=ps.executeQuery(str);
UserDO user = new UserDO();
RegDO regDO = new RegDO();
AddressDO addressDO = new AddressDO();
while(rs.next())
{
user.setName(rs.getString("name"));
System.out.println("name= "+rs.getString("name"));
addressDO.setStreetname(rs.getString("street_name"));
System.out.println("street_name= "+rs.getString("street_name"));
addressDO.setStreetname(rs.getString("city"));
System.out.println("city = "+rs.getString("city"));
regDO.setGender(rs.getString("gender"));
System.out.println("gender = "+rs.getString("gender"));
regDO.setReg_date(rs.getString("reg_date"));
System.out.println("reg_date = "+rs.getString("reg_date"));
System.out.println("date using getter"+regDO.getReg_date());
}
}
catch(Exception e)
{
e.setStackTrace(null);
}
return disDo;
}
THis code is working perfectly and i am getting the values in the console..
the following code is my jsp page.
<%#page import="java.lang.String" %>
<%#page import="java.io.*" %>
<%#page import="com.quinoid.e_tender.databean.RegDO"%>
<%#page import="com.quinoid.e_tender.databean.AddressDO"%>
<%#page import="com.quinoid.e_tender.databean.UserDO"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org /TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Your Values</h1>
<%
System.out.print("inside display_1");
UserDO user=(UserDO)request.getAttribute("name");
out.println(user);
AddressDO add=(AddressDO)request.getAttribute("add");
RegDO reg=(RegDO)request.getAttribute("reg");
String name,street_name,city,gender,reg_date;
name=(String)request.getAttribute("user");
/*street_name=add.getStreetname();
city=add.getCity();
gender=reg.getGender();
reg_date=reg.getReg_date();
*/%>
<!-- <script type="text/javascript">
/*document.getElementById("name").innerHTML =(String)request.getAttribute("name");
document.getElementById("street_name").innerHTML = add.getStreetname();
document.getElementById("city").innerHTML = add.getCity();
document.getElementById("gender").innerHTML = reg.getGender();
document.getElementById("reg_date").innerHTML = reg.Reg_date(); */
</script> -->
<form name="innerHTML" method ="post">
<table border="1">
<tr>
<th> Name </th>
<th>Street Name</th>
<th> City </th>
<th> Gender </th>
<th>Registration date</th>
</tr>
<tr>
<td id=name> </td>
<td id=street_name> </td>
<td id=city> </td>
<td id=gender> </td>
<td id=reg_dae> </td>
</tr>
</table>
</form>
</body>
</html>
Iam trying to display the values of "name","street_name","city","gender","reg_date" in the table and failed miserably..
This is the result in my console
the servlet is in user display
In display method
userid= 910
inside dao display
dbconnection established
inside dao try
userid = 910
values of addressid= 118address1= 118
query execution successfull
name= anjana
street_name= nagar
city = tvm
gender = F
reg_date = 1990-08-15
date using getter1990-08-15
exiting display method
inside display_1
inside display_1
do help.. thanks in advance..
Set this attribute in 'request' in your servlet before forwarding to the jsp page.
UserDO user=(UserDO)request.getAttribute("name");
out.println(user);
AddressDO add=(AddressDO)request.getAttribute("add");
RegDO reg=(RegDO)request.getAttribute("reg");
String name,street_name,city,gender,reg_date;
name=(String)request.getAttribute("user");
set these values as
request.setAttribute("name",userDo); //UserDo instance.
request.setAttribute("add",addressDo);//AddressDO instance. and so on...
And then forward it
request.getRequestDispatcher("xxxx").forward(request,response);//xxxx is jsp page you are forwarding.
And get the value in jsp using
<%=xxx%>//xxx is the reference as **name**, **city**..
try with following code,
document.getElementById("street_name").innerHTML = '<%=add.getStreetname()%>';
document.getElementById("city").innerHTML = '<%=add.getCity()%>';
document.getElementById("gender").innerHTML = '<%=reg.getGender()%>';
document.getElementById("reg_date").innerHTML = '<%=reg.Reg_date()%>';
You must set your attributes to the request object and than forward the servlet class to JSP, where you can getAttribute from the Request object as it is an implicit object in the JSP.
But when getAttribute is called you must cast it to appropriate Object type.
And Make sure you are not using Redirect mechanism, otherwise your Request object will be null because it is a new object for JSP. Only in Forward Mechanism the request object is copied to the new request object on JSP.
You can use the examples available on Net and as well
Pradeep Kr Kaushal example.
I have written this to just let you inform about Forward and Redirect mechanism effects on Request object.
You are not calling you dao class Display method anywhere.
In your dao class, change the method like so (method names in java start with a lowercase letter by convention):
public DisplayDo display() throws Exception { ...
At the end of the method, after populating them from the ResultSet, initialize a DisplayDo object and set the userDo, addressDo and regDo objects:
DisplayDO displayDo = new DisplayDO();
displayDo.setRegDo(regDO);
displayDo.setAddressDi(addressDO);
displayDo.setUserDo(userDO);
In your jsp, add the import for your dao class (assuming it is called DisplayDao):
<%#page import="com.quinoid.e_tender.dao.DisplayDao"%>
Add this to your jsp to create a new DisplayDao and access its display() method:
<% DisplayDao displayDao = new DisplayDao();
DisplayDo displayDo = displayDao.display();
UserDO userDo = displayDo.getUserDo();
...
%>
You can then output values like this:
<td id="name"><%= userDo.getName() %></td>

Categories