how to display multiple images and data from mysql in jsp - mysql

I am using jsp with mysql in these code. i got only one images at a time but all data retrieved... Can u tell me how to display multiple images in this code?
my data: imagename varchar(),description varchar(),imageid varchar(),category varchar image blob().
index.jsp:
<%#page import="java.io.InputStream"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.io.OutputStream"%>``
<%# page import="java.sql.*" %>
<!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");
Connection con=DriverManager.
getConnection("jdbc:mysql://localhost:3306/rich","root","");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select *from publishers");
while(rs.next())
{
String imgLen=rs.getString(5);
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(5);
int index=readImg.read(rb, 0, len);
System.out.println("index"+index);
stmt.close();
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
%>
</body>
</html>
**basic.jsp:**
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.io.OutputStream"%>
<%# page import="java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
< form action="index.jsp" method="post">
<%
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/rich","root","");
Statement stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("select *from publishers");
while(rs.next())
{
%>
<table border="1">
<tr> <td>
<img src="index.jsp?" /> </td> </tr>
<tr>
<td> <%=rs.getString(1)%> </td>
<td> <%=rs.getString(2)%> </td>
<td> <%=rs.getString(3)%> </td>
<td> <%=rs.getString(4)%> </td>
</tr>
</table>
<%
}
%>
</form>
</body>
</html>

Actually it is not difficult . We will use two jsps files to show images first this page for getting image.
<%# Page import="java.sql.*" %>
<%# Page import="java.io.*" %>
<html>
<%
byte[] imgData = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/try","root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select photo from employee where employee_id=" + request.getParameter("empId"));
while (rs.next())
{
Blob image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());
}
response.setContentType("image/png");
OutputStream o = response.getOutputStream();
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;
}
%>
</html>
and here i getting all ids to get all images
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<html>
<%
try
{
String EmpFirstName;
String EmpSurname;
String EmpId;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/try","root","root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select employee_id,first_name,surname from employee");
while (rs.next())
{
EmpFirstName = rs.getString("first_name");
EmpSurname = rs.getString("surname");
EmpId = rs.getString("EmpId");
<DIV><%=EmpFirstName5> <%=Surname%> </DIV>
<img src="http://localhost/GetImage.jsp?empId=<%=EmpId%>" />
}
rs.close();
stmt.close();
con.close();
}
catch (Exception e)
{
out.println(e.Message);
return;
}
%>
</html>
the code and its explanation taken from
http://stackoverflow.com/users/535152/tom%c3%a1s
thank you very much

Related

SQL update query is not working in Java program

I am trying to update record in MySQL table. But when I execute it, it is not reflecting changes. No error or exceptions occurred. I tried with con.commit() and con.setAutoCommit(false) but no changes reflected. Only Home button is displayed on screen and even alerts in my program not displayed.
This is editnew.jsp
<tr>
<td></td>
<td>
<input type="hidden" value="update" name="update"/>
<input type="submit" value="Update" class="btn btn-primary"/>
</td>
</tr>
This is my editprocess.jsp code
<%#page import="java.io.File"%>
<%#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">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<title>editprocess jsp Page</title>
</head>
<body>
<%
String z_id = request.getParameter("zid");
String first_Name = request.getParameter("firstname");
String last_Name = request.getParameter("lastname");
String mail_i_d = request.getParameter("mailid");
String d_iv = request.getParameter("division");
String de_pt = request.getParameter("department");
...
String iss_uer = request.getParameter("issuer");
String sta_tus = request.getParameter("status");
String file_Name = "";
String folder_Name = "allfiles";
String pa_th = folder_Name + File.separator + file_Name;
Timestamp add_ed_date = new Timestamp(System.currentTimeMillis());
if(request.getParameter("update") != null){
Connection con = null;
PreparedStatement ps = null;
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dmsqms","root","");
String sql = "update dmsfiles set firstname=?,lastname=?,mailid=?,division=?,department=?,costcentercode=?,document_number=?,document_name=?,document_type=?,document_category=?,document_classification=?,authorised_by=?,fromdate=?,todate=?,document_level=?,document_general=?,serial_number=?,revision_number=?,issuer=?,status=?,filename=?,path=?,added_date=? where document_name='"+doc_Name+"'";
ps = con.prepareStatement(sql);
// ps.setString(1,z_id);
ps.setString(1,first_Name);
ps.setString(2,last_Name);
ps.setString(3,mail_i_d);
ps.setString(4,d_iv);
ps.setString(5,de_pt);
ps.setString(6,cost_centercode);
ps.setString(7,doc_num);
ps.setString(8,doc_Name);
ps.setString(9,doc_Type);
ps.setString(10,doc_Category);
ps.setString(11,doc_classification);
ps.setString(12,authorised_by);
ps.setString(13,from_date);
ps.setString(14,to_date);
ps.setString(15,document_level);
ps.setString(16,document_general);
ps.setString(17,serial_number);
ps.setString(18,revision_number);
ps.setString(19,iss_uer);
ps.setString(20,sta_tus);
ps.setString(21,file_Name);
ps.setString(22,pa_th);
ps.setTimestamp(23, add_ed_date);
int i = ps.executeUpdate(sql);
con.commit();
if(i > 0)
{
out.println("alert('Record Updated Successfully');");
}
else
{
out.println("alert('There is a problem in updating Record.');");
}
}
catch(SQLException sql)
{
sql.printStackTrace();
}
}
%>
Home
</body>
</html>

AJAX JSP displaying output data in a table

trying to display data from server in the page in a table. but unfortunately it is not working. I can display it using out.println. Code samples are attached. Thank you very much.
ajax1 handles the ajax part and ajax2 is the file for java code.
...
Ajax1.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$("#users").change(function(){
var value = $(this).val();
$.get("ajax2.jsp",{q:value},function(data){
$("#javaquery").html(data);
});
});
});
</script>
</head>
<body>
<select id = "users">
<option value="">Select Account ID</option>
<option value="calicut">calicut</option>
<option value="kochi">kochi</option>
<option value="Admin">Admin</option>
</select>
<br />
<div id="javaquery"><b>Name will be displayed here</b></div>
</body>
</html>
Ajax2.jsp
<%#page import="java.text.SimpleDateFormat"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.util.*,java.sql.*,java.io.*" %>
<%#page import="javax.servlet.*" %>
<%#page import="javax.servlet.http.*" %>
<%# page import="java.sql.*" %>
<%# page import="java.util.*" %>
<%# page import="java.io.*" %>
<%# page import="javax.sql.*" %>
<%# page import="javax.naming.*,javax.swing.*,java.sql.Date.*,java.text.SimpleDateFormat.*,java.util.Date.*" %>
<html> <head> <meta http-equiv="Content-Type"
content="text/html; charset=UTF-8"> <title></title> </head>
<body>
<%
InitialContext ctx;
DataSource ds;
Connection conn;
ResultSet rs;
Statement stmt;
String name = "";
String ename="";
try {
ctx=new InitialContext();
ds=(DataSource) ctx.lookup("java:app/jdbc/SalesDB");
conn=ds.getConnection();
String q = request.getParameter("q");
stmt = conn.createStatement(); //Create Statement to interact
rs = stmt.executeQuery("select * from employees where Username='"+q+"'");
while (rs.next()) {
name = rs.getString("Role_")+rs.getString("username");
ename=rs.getString("username");
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
Name:<%out.print(name);%>
eName:<%out.print(ename);%>
</body> </html>
.............................................
.................................................
<script>
$(document).ready(function(){
$("#users").change(function(){
var value = $(this).val();
$.get("AjaxServlet",{q:value},function(data){
$("#javaquery").html(data);
});
});
});
</script>
Remove java code from 2nd jsp and add it to a servlet called "AjaxServlet" with url mapping "/AjaxServlet"
AjaxServlet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String q = request.getParameter("q"); //q value
InitialContext ctx;
DataSource ds;
Connection conn;
ResultSet rs;
Statement stmt;
String name = "blank name";
String ename="";
try {
ctx=new InitialContext();
ds=(DataSource) ctx.lookup("java:app/jdbc/SalesDB");
conn=ds.getConnection();
String q = request.getParameter("q");
stmt = conn.createStatement(); //Create Statement to interact
rs = stmt.executeQuery("select * from employees where Username='"+q+"'");
while (rs.next()) {
name = rs.getString("Role_")+rs.getString("username");
ename=rs.getString("username");
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(name); // Write response body.
}
More info on how to do ajax with servlets here:
How to use Servlets and Ajax?

com.mysql.jdbc.Driver cannot be found by de Server

I have a web application that has been working for ages now.. suddenly I get this message when I am trying to login:
javax.servlet.ServletException: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
As I said before it has been working for over 3 years now… but the people who does the hosting for me have not been able to do anything… I have my driver on the WEB-INF folder and everything… can the folder’s permissions cause this problem? I have them set as 0744…any idea?
This is the screen shot of the WEB-INF folder:
I managed to login to the web application but the login jsp file is not working because the connection is not happening… here is the code:
<%# page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<%# page language="java" session="true" %>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Accesando a Vecinet</title>
</head>
<body>
<%
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/etoolsco_VecinetSM?user=etoolsco&password=xxxx");
ResultSet rsdoLogin = null;
PreparedStatement psdoLogin=null;
String uname=request.getParameter("j_username");
String upass=request.getParameter("j_password");
String message="User login successfully ";
%>
<% try
{
String sqlOption="SELECT * FROM logins where"
+" usuario=? and clave=?";
psdoLogin=conn.prepareStatement(sqlOption);
psdoLogin.setString(1,uname);
psdoLogin.setString(2,upass);
rsdoLogin=psdoLogin.executeQuery();
if(rsdoLogin.next())
{
session.setAttribute("usuario",rsdoLogin.getString("usuario"));
session.setAttribute("clave",rsdoLogin.getString("clave"));
session.setAttribute("nombre",rsdoLogin.getString("nombre"));
session.setAttribute("apellido",rsdoLogin.getString("apellido"));
session.setAttribute("role",rsdoLogin.getString("role"));
session.setMaxInactiveInterval(7200);
response.sendRedirect("Vecinetspace.jsp?error="+message);
}
else
{
response.sendRedirect("error.jsp?error=");
}
}
catch(Exception e)
{
e.printStackTrace();
}
try{
if(psdoLogin!=null){
psdoLogin.close();
}
if(rsdoLogin!=null){
rsdoLogin.close();
}
if(conn!=null){
conn.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>
This is the same login.jsp code for the application that is working:
<%#page contentType="text/html"%>
<%#page pageEncoding="UTF-8"%>
<%# page language="java" import="java.sql.*" errorPage="" %>
<%# page language="java" session="true" %>
<html>
<head><title>Login to CRD</title>
</head>
<body>
<%
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost/etoolsco_labsmb?user=etoolsco&password=xxx");
ResultSet rsdoLogin = null;
PreparedStatement psdoLogin=null;
String uname=request.getParameter("j_username");
String upass=request.getParameter("j_password");
String message="User login successfully ";
%>
<% try
{
String sqlOption="SELECT * FROM logins where"
+" usuario=? and clave=?";
psdoLogin=conn.prepareStatement(sqlOption);
psdoLogin.setString(1,uname);
psdoLogin.setString(2,upass);
rsdoLogin=psdoLogin.executeQuery();
if(rsdoLogin.next())
{
session.setAttribute("usuario",rsdoLogin.getString("usuario"));
session.setAttribute("clave",rsdoLogin.getString("clave"));
session.setAttribute("nombre",rsdoLogin.getString("nombre"));
session.setAttribute("apellido",rsdoLogin.getString("apellido"));
session.setAttribute("role",rsdoLogin.getString("role"));
session.setMaxInactiveInterval(600);
response.sendRedirect("BMRspace.jsp?error="+message);
}
else
{
response.sendRedirect("error.jsp?error=");
}
}
catch(Exception e)
{
e.printStackTrace();
}
try{
if(psdoLogin!=null){
psdoLogin.close();
}
if(rsdoLogin!=null){
rsdoLogin.close();
}
if(conn!=null){
conn.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</body>
</html>

Display image in asp div

My problem is that, after i was able to display my medium blob in mysql database in my jsp, i cannot position the image with my css.
What i want is to position it inside a div that has a fixed width and height.
<%#page import="java.io.OutputStream"%>
<%#page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Statement stmnt = null;
ResultSet rs = null;
OutputStream o = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/uShare";
String username = "root";
String password = "";
PreparedStatement ps;
Blob image = null;
byte[] imgData = null;
try {
Class.forName(driver).newInstance();
Connection con = DriverManager.getConnection(url, username, password);
stmnt = con.createStatement();
rs = stmnt.executeQuery("select foto from utilizadores where idUtilizador = 13");
if (rs.next()) {
image = rs.getBlob("foto");
imgData = image.getBytes(1, (int) image.length());
out.println("encontrou imagem");
}
//mostra
response.setContentType("image/gif");
o = response.getOutputStream();
o.write(imgData);
%>
<div style="float: right; width: 20%; height: 20%;">
<%
o.flush();
%>
</div>
<%
o.close();
stmnt.close();
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
%>
</body>
</html>
Thank you to all.
Sorry for the late answer but the site doesn't let me reply within 8 hours.T hanks to everyone. I found a temporary solution, and because this is for academic purposes only it´s ok.
The solution is. When i want to display a image in a ing tag, i always have to give the tag the url.
There are two possibilities:
you cam pass the image through servlet;
Or like the one i did, i displayed the image in a Jsp page then i grab it on the other jsp with the first jsp url.
Jsp for display the image:
<%#page import="java.io.OutputStream"%>
<%#page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<link href="css/master.css" rel="stylesheet" type="text/css">
</head>
<body>
<%
Statement stmnt = null;
ResultSet rs = null;
OutputStream o = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/uShare";
String username = "root";
String password = "";
PreparedStatement ps;
Blob image = null;
byte[] imgData = null;
try {
Class.forName(driver).newInstance();
Connection con = DriverManager.getConnection(url, username, password);
stmnt = con.createStatement();
rs = stmnt.executeQuery("select foto from utilizadores where idUtilizador = 13");
if (rs.next()) {
image = rs.getBlob("foto");
imgData = image.getBytes(1, (int) image.length());
out.println("encontrou imagem");
}
//mostra
response.setContentType("image/jpeg");
o = response.getOutputStream();
o.write(imgData);
o.flush();
response.flushBuffer();
stmnt.close();
con.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
%>
</body>
</html>
And then the end user jsp
<%#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>
<img src="testeImagem.jsp" alt="foto" style="width: 200px; height: 200px">
</body>
</html>
Of course this is just an example.
Thanks to all, and sorry for my bad english.
set image width as 100% so that it will get fit inside a fixed length of div

Pagination using java

This is code for pagination in java i tried to implement. i have 20 records with columns emp_id and emp_name which i want to display using 4 pages i.e (5 records per page) using my sql workbench but code is not executing indicating many errors plz solve this
<%# page import ="java.io.*, java.sql.*, java.util.*" %>
<%!
Connection con = null;
ResultSet rs = null;
ResultSet rs1 = null;
int start_row_count, end_row_count, no_of_page, pages;
String page_name="paging.jsp";
%>
<html>
<head>
</head>
<body>
<table border="1" style="width:80%;">
<%
try
{
String pages1=request.getParameter("pages");
if(pages1!=null)
{
pages=Integer.parseInt(pages1);
}
if(pages==0)
pages=1;
if(pages==1)
{
start_row_count=1;
}
else
{
start_row_count=(pages-1)*5;
}
end_row_count=pages*5;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/shelu", "root", "mysql");
String sql="select * from emp limit" + start_row_count +"5";
Statement st = con.createStatement();
rs = st.executeQuery(sql);
while(rs.next())
{%>
<tr>
<td><%=rs.getInt("emp_id")%></td>
<td><%=rs.getString("emp_name")%></td>
</tr>
<%
}
rs.close();
rs1=st.executeQuery("select count(*) from emp");
int total=0;
if(rs1.next())
total=rs1.getInt(1);
if(total%5==0)
no_of_page=total/5;
else
no_of_page=total/5+1;
%>
<tr>
<%
for(int i=1;i<=no_of_page;i++)
{
out.println("<a href='"+page_name+"?pages="+i+"'>"+i+"</a>");
}
%>
</tr>
<%
} catch(Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
If you are looking at server side pagination, Displaytag is what you should be using.