Insert image through JSP - java

This is my JSP code to insert image into Oracle database but I am not getting any output. Variables are getting values but code is not properly running.
I have used the Blob datatype for image in my database.
This is my JSP page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%#page import="com.sun.xml.internal.bind.CycleRecoverable.Context"%>
<%#page import="java.io.InputStream"%>
<%#page import="java.io.FileInputStream"%>
<%#page import="java.io.File"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.Connection"%>
<!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>
<%
Connection conn = null;
PreparedStatement pstmt = null;
FileInputStream fis = null;
String fname = request.getParameter("pic");
String s1 = request.getParameter("txt1");
String s2 = request.getParameter("txt2");
String s3 = request.getParameter("txt3");
String s4 = request.getParameter("txt4");
String s5 = request.getParameter("options");
String s6 = request.getParameter("rsn");
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
conn = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "ankit", "ankit27");
File image= new File(fname);
//Table name is EmpDetails.
pstmt = conn.prepareStatement("insert into EmpDetails values(?,?,?,?,?,?,?)");
fis = new FileInputStream(image);
pstmt.setBinaryStream(1, fis, fis.available());
pstmt.setString(2, s1);
pstmt.setString(3, s2);
pstmt.setString(4, s3);
pstmt.setString(5, s4);
pstmt.setString(6, s5);
pstmt.setString(7, s6);
int count = pstmt.executeUpdate();
if (count > 0) {
out.println("insert successfully");
} else {
out.println("not successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
I am unable to get any output.

Related

Unable to retreive value from oracle database using JSP, getting java.sql.SQLException: Result set after last row

I have written simple jsp program where I am trying to retrieve username and password from database, here is my jsp program.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import ="java.sql.*" %>
<%# page import ="oracle.sql.*" %>
<%# page import ="oracle.jdbc.driver.*" %>
<%#page import="oracle.jdbc.driver.OracleDriver"%>
<%# page import ="java.util.Date" %>
<!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>
<%
String driver="oracle.jdbc.driver.OracleDriver";
String userid = request.getParameter("username");
String pwd=request.getParameter("password");
Connection con = null;
%>
<%try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:CCB25", "CISADM", "CISADM");
Statement st= con.createStatement();
String query="select * from CMLOGIN where USERID='"+userid+"'";
ResultSet rs=st.executeQuery(query);
String pass1="";
rs.next();
pass1 = rs.getString("password");
if(pass1.equals(pwd))
{
%>
<%String name=request.getParameter("username");
session.setAttribute("nam",name);%>
<jsp:forward page="admin.jsp"></jsp:forward>
<%}
else
{
String msg="Username or password failed";%>
<center> <p style="font-family:verdana;color:red;"><%=msg %>
<jsp:include page="Login.jsp"></jsp:include>
<%}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
and i have javax.servlet.jar and ojdbc7-12.1.0.2.jar in web-inf/lib folder. I am getting java.sql.SQLException: Result set after last row on the following line "pass1 = rs.getString("password");" Could you please guide me what I am doing wrong.
You first need to check if the ResultSet has any rows in it before calling .next(), in order to prevent this exception.
Use this:
if (rs.next){
//read next row
}
if you want to loop through all the rows of the ResultSet, use a while loop:
while(rs.next){
//do something for every row
}
Here is the same cleaned up a little. You'll have to add back in exception handling and closing of the connection/statement/resultset
Hopefully you never have to use this code for real as it's taking in a password from query string in clear then comparing to a clear version in the db.
Password comparison moved to the sql itself.
Always use PreparedStatements to avoid sql injection
Comments are in the code.
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import ="java.sql.*" %>
<%# page import ="java.util.Date" %>
<!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>
<%
String userid = request.getParameter("username");
String pwd = request.getParameter("password");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521/XE", "klrice", "klrice");
//
// USE BINDS ! to avoid sql injection
// push the userid and passwd comparison to the db
// no need to get the password and compare locally
//
String query = "select password from cmlogin where userid=? and password=?";
PreparedStatement st = con.prepareStatement(query);
//
// Binds in the vaules
//
st.setString(1,userid);
st.setString(2,pwd);
ResultSet rs = st.executeQuery();
String pass1;
// .next will advance if the query has any results
//
if ( rs.next() ) {
pass1 = rs.getString("password");
String name =request.getParameter("username");
session.setAttribute("nam",name);
%>
<jsp:forward page="admin.jsp"></jsp:forward>
<%
} else {
String msg="Username or password failed";
%>
<center> <p style="font-family:verdana;color:red;"> <%=msg %>
<jsp:include page="Login.jsp"></jsp:include>
<% } %>
</body>

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>

Resultset rs cannot be resolved

very recently i started learning Java Technology right now I'm working on Servlets while i fetch the data from data base it's not resolving resultset rs
here I attached my code
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<script
type="text/javascript" language="javascript">
javascript:window.history.forward(1);
</script>
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
update
display
logout
<script>
<%
try{
ResultSet rs=null;
String mail=(String)session.getAttribute("mail");
String sql="select * from tempregister where mail=?";
Class.forName("com.ibm.db2.DB2Driver");
Connection con=DriverManager.getConnection("jdbc:db2://localhost:50000/TEMP", "tarun", "12347890");
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1, mail);
rs=ps.executeQuery();
}catch(Exception e){
}
%>
<%
while(rs.next())
{
%>
<%=rs.getString(4)%>
<%
}
}
catch(Exception e)
{
e.printStackTrace();
}%>
</script>
</a>
</body>
</html>
please help me out.. thanks
Your code should be changed at least:
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<script
type="text/javascript" language="javascript">
javascript:window.history.forward(1);
</script>
<%
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-store");
response.setHeader("Expires","0");
response.setDateHeader("Expires",-1);
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
update
display
logout
<%
ResultSet rs = null;
try {
String mail = (String) session.getAttribute("mail");
String sql = "select * from tempregister where mail=?";
Class.forName("com.ibm.db2.DB2Driver");
Connection con = DriverManager.getConnection("jdbc:db2://localhost:50000/TEMP", "tarun", "12347890");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, mail);
rs = ps.executeQuery();
while (rs.next()) {
%>
<%=rs.getString(4)%>
<%
}
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>

How to redirect the code below after delete to a previours web page?

After the delete below how can this page be redirected to the previours page and do a refresh to not show the data deleted?
I tried some options like:
<%
String redirectURL = "Index.jsp";
response.sendRedirect(redirectURL);
%>
but did not work. Should it just work with complete urls?
am I doing this right also or this is not the best practice?
Thanks you!
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page language="java"%>
<%#page import="java.lang.*" import="org.postgresql.*"
import="java.sql.*"%>
<!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></title>
</head>
<body>
<%
try {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/postgres";
Connection connection = DriverManager.getConnection(url,
"postgres", "admin");
String strquery = "DELETE FROM projects WHERE project = '"
+ request.getParameter("project") + "'";
Statement st = connection.createStatement();
//System.out.println("Connecting to database...");
ResultSet rs = st.executeQuery(strquery);
System.out.println(strquery);
pageContext.forward("Index.jsp");
rs.close();
st.close();
} catch (Exception e) {
System.out.println(e);
}
%>
</body>
</html>

how to retrieve multiple blob images from mysql using jsp [duplicate]

This question already has answers here:
How to retrieve and display images from a database in a JSP page?
(6 answers)
Closed 6 years ago.
I am trying to retrieve few blob images from mysql database using java. Now , the problem is that I'm able to get only one image at a time, the other images are not getting displayed.
Below is my jsp code , where I'm doing this(just for demonstration purpose):
<?xml version="1.0" encoding="UTF-8" ?>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%# page language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%# page import="java.util.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>MindDotEditor posted Data</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="robots" content="noindex, nofollow" />
<link href="../sample.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="../fckeditor.gif" type="image/x-icon" />
</head>
<body>
<%
String url = "jdbc:mysql://localhost:3306/grandsho_register";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(url,"root","root");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT image FROM user ");
int i = 1;
if(rs.next()) {
Blob len1 = rs.getBlob("image");
int len = (int)len1.length();
byte[] b = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index = readImg.read(b, 0, len);
System.out.println("index" +index);
stmt.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(b,0,len);
response.getOutputStream().flush();
}
} catch(Exception ex) {
out.println(ex);
} finally {
rs.close();
stmt.close();
con.close();
}
%>
<br>
<center><input type="button" value="Print" onclick="window.print();return false;" /> </center>
</body>
</html>
Can anyone suggest how can i display multiple images on jsp page?
Instead of if(rs.next()) {} you have to use while(rs.next()){}

Categories