I am new to jsp.I have a table named employee now I want to insert image to datatase using a name as request parameter.The table already have name,age,id,phonenumber,email,password as fields.image is my new field I created now.When updating image field with new blob image it is not showing error but image is not inserting. Here's my try :
// My form to fileupload
<form name="frm" action="Image.jsp" method="post">
<center>Name:<input type="text" name="name"><br></center><br>
<center><br><br> <input type="submit" value="Submit"></center>
</form>
//(Image.jsp )My pgogram to get file from client and store in database
<%# page import="java.sql.*" %>
<%# page import="org.apache.commons.fileupload.*"%>
<%# page import="org.apache.commons.io.output.*"%>
<%# page import="org.apache.commons.fileupload.servlet.*"%>
<%# page import="org.apache.commons.fileupload.disk.*"%>
<%# page import="java.io.*"%>
<%# page import="java.util.*"%>
<html>
<body>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/praveen";
PreparedStatement pstatement = null;
FileInputStream inputStream = null;
int insertQuery = 0;
byte[] b = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "bulbultara");
String sql = "update employee set image=? where name=? ";
pstatement = connection.prepareStatement(sql);
pstatement.setString(2, request.getParameter("name"));
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
List items = sfu.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
b = item.get();
}
}
pstatement.setBytes(1, b);
insertQuery = pstatement.executeUpdate();
pstatement.close();
connection.close();
%>
<input type="submit" value="Login">
</body>
</html>
<% # page import="java.io.*" %>
<% # page import="java.sql.*" %>
<% # page import="java.util.zip.* "%>
<%
String saveFile="";
String contentType=request.ContentType();
if((contentType != null) &&(contentType.indexOf("multipart/form-data")>=0))
{
DataInputStream in= new DataInputStream(request.getInputStream());
int formDataLength=request.getContentLength();
byte dataBytes[]= new byte[formDataLength];
int byteread=0;
int totalbyteread=0;
while(totalbyteread<formDataLength)
{
byteread=in.read(dataBytes,totalbyteread,formDataLength);
totalbyteread =byteread+1;
}
String file= new String(dataBytes);
saveFile=file.subString(file.indexOf("filename=\"")+10);
saveFile= saveFile.subString(0,saveFile.indexOf("\n"));
saveFile=saveFile.subString(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\""));
int lastIndex=contentType.lastIndexOf("=");
String boundry=contentType.subString(lastIndex+1,contentType.length());
int pos;
pos=file.indexOf("filename=\"");
pos=file.indexOf("n\",pos)+1;
pos=file.indexOf("n\",pos)+1;
pos=file.indexOf("n\",pos)+1;
pos=file.indexOf("n\",pos)+1;
int boundrylocation=file.indexOf(boundry,pos)-4;
int startpos=((file.subString(0,pos)).getBytes()).length;
int endpos=((file.subString(0,boundryloction)).getBytes()).length;
File ff= new File(saveFile);
FileOutputStream fileout= new FileOutputStram(ff);
fileout.write(dataBytes,startpos,(endpos-startpos));
fileout.flush();
fileout.close();
%>
<Br><table border="2"><tr><td><b>You have successfully upload the file:</b>
<%out.println(saveFile);%></td></tr></table>
<%
Connection connection = null;
String connectionURL = "jdbc:mysql://localhost:3306/praveen";
PreparedStatement pstatement = null;
FileInputStream inputStream = fis;
ResultSet rs=null;
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "bulbultara");
File f= new File(saveFile);
pstatement=connection.prepareStatement("insert into employee(name of image cloumn) values(?)");
pstatement.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
int s = pstatement.executeUpdate();
if(s>0){
System.out.println("Uploaded successfully !");
}
else{
System.out.println("Error!");
}
}
catch(Exception e){e.printStackTrace();}
}
}
%>
Related
I'm trying to display image from MySQL server on to the browser. But the following code works on Internet Explorer but not working on Chrome and Mozilla Firefox browser.
I'm new to JSP and I've already tried code from this question but didn't work .Displaying image in jsp from database
`<%# include file="connect.jsp" %>
<%#page import="java.sql.*,java.io.*"%>
<%# page import="java.sql.*,java.io.*,java.util.*" %>
<%
try{
int id = Integer.parseInt(request.getParameter("id"));
Statement st=connection.createStatement();
String strQuery = "select image from user where id="+id+"" ;
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next())
{
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next())
{
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
st.close();
response.reset();
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}%>
To retrieve multiple images from the SQL database and display in JSP pages you can do this:
<%
int id = Integer.parseInt(request.getParameter("imgid"));
try {
Connection con=DriverManager.getConnection("jdbc:sqlserver://XXXXX\\SQLEXPRESS14;databaseName=Student;user=XX;password=XXXXX");
Statement st = con.createStatement();
String strQuery = "select image from login_users where id='" + id + "'";
ResultSet rs = st.executeQuery(strQuery);
String imgLen="";
if(rs.next()) {
imgLen = rs.getString(1);
}
rs = st.executeQuery(strQuery);
if(rs.next()) {
byte[] bytearray = new byte[4096];
int size=0;
InputStream sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1) {
response.getOutputStream().write(bytearray,0,size);
}
response.getOutputStream().flush();
response.getOutputStream().close();
response.flushBuffer();
sImage.close();
rs.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
%>
This is my JSP coding, I am using link to redirect to JSP page :
Excel.jsp
<%#page import="java.sql.*"%>
<%#page import="java.sql.SQLException"%>
<%#page import="org.apache.poi.hssf.usermodel.*"%>
<%#page import=" java.io.*"%>
<%
String url = "jdbc:mysql://localhost:3306/";
String dbName = "login";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Class.forName("driver");
Connection con = DriverManager.getConnection("url + dbName", "userName",
"password");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from openstock");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("fisocon");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("iname");
rowhead.createCell((short) 1).setCellValue("wname");
rowhead.createCell((short) 2).setCellValue("catname");
rowhead.createCell((short) 3).setCellValue("class");
rowhead.createCell((short) 4).setCellValue("unit");
rowhead.createCell((short) 5).setCellValue("nname");
int i = 1;
while (rs.next()){
out.println("hai2");
HSSFRow row = sheet.createRow((short) i);
row.createCell((short)
0).setCellValue(Integer.toString(rs.getInt("iname")));
row.createCell((short) 1).setCellValue(rs.getString("wname"));
row.createCell((short) 2).setCellValue(rs.getString("catname"));
row.createCell((short) 3).setCellValue(rs.getString("class"));
row.createCell((short) 4).setCellValue(rs.getString("unit"));
row.createCell((short) 5).setCellValue(rs.getString("nname"));
i++;
}
String yemi = "d:/xls/test.xls";
FileOutputStream fileOut = new FileOutputStream(yemi);
workbook.write(fileOut);
fileOut.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
catch (SQLException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
%>
In this coding, createcell is strikeout. I don't know why it is.
There is no errors in coding. I also add poi 3.14 jar file in library.
My output page displays as empty. Please help me. Thanks in advance.
Page is empty because everything You made is outside of page.
BTW doing such in JSP is the worst idea.
Move this code to servlet, here is tip how to return binary data.
java servlet response returning data
Add
response.contentType = "application/vnd.ms-excel"
and JPS page should only have link
The additional effect: servlet code is more, more friendly to debugging.
This is the code of my index.jsp:
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page import="org.apache.tomcat.jdbc.pool.DataSource"%>
<%#page import="org.apache.tomcat.jdbc.pool.PoolProperties"%>
<%#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>
<div id="query">
<%
PoolProperties p = new PoolProperties();
p.setUrl("jdbc:oracle:thin:#localhost:1521:XE");
p.setDriverClassName("oracle.jdbc.OracleDriver");
p.setUsername("scott");
p.setPassword("tiger");
p.setMaxActive(100);
p.setInitialSize(10);
DataSource datasource = new DataSource();
datasource.setPoolProperties(p);
Connection con = null;
con = datasource.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select 777 from dual");
while (rs.next()) {
System.out.println(rs.getString(1));;
}
rs.close();
st.close();
%>
</div>
</body>
</html>
This is the error im getting for running that code:
I dont understand why this code runs for oracle:
<%
String dcn = "oracle.jdbc.OracleDriver";
Class.forName(dcn);
String serverName = "localhost";
String portNumber = "1521";
String sid = "orcl";
String url = "jdbc:oracle:thin:#" + serverName + ":" + portNumber + ":" + sid;
String username = "scott";
String password = "tiger";
Connection conn = DriverManager.getConnection(url, username, password);
Statement stm = conn.createStatement();
String query = "SELECT * from emp";
ResultSet data = stm.executeQuery(query);
while (data.next()) {
String number = data.getString("EMPNO");
String name = data.getString("ENAME");
%> <%=number%> <%=name%> <br> <%
}
%>
Dispite the fact that I imported the drivers properly. How should i do this in mysql ? Tried replacing driver but doesnt work either.
MYSQL Code:
<div id="query">
<%
String username = "j2ee";
String password = "j2ee123456";
String dbName = "testjava";
String dbHost = "localhost";
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException msg) {
out.println("Error loading driver:" + msg.getMessage());
}
try {
String url = "jdbc:mysql://" + dbHost + ":3306/" + dbName;
Connection Conn = DriverManager.getConnection(url, username, password);
Statement Stmt = Conn.createStatement();
String query = "SELECT * FROM example_autoincrement";
ResultSet rs = Stmt.executeQuery(query);
while (rs.next()) {
int numExp = rs.getInt("id");
String nombre = rs.getString("data");
%> <%=numExp%> <%=nombre%> <%
}
} catch (SQLException e) {
String err1Msg = e.getMessage();
%>
<STRONG><EM> <%=err1Msg%> </EM></STRONG>
<%
}
%>
The error im getting on VPS
Error loading driver:com.mysql.jdbc.Driver No suitable driver found for jdbc:mysql://localhost:3306/testjava
However I dont get this error with XAMPP running same code...
Solved: after putting the mysql driver in the WEB-INF/lib folder had to restart tomcat.
I want to extract data from excel sheet to insert it into a mysql table using jsp, so far i've done this and its printing data into the outpout(using apache poi),what should i add to this code ?
Output :
Name Age Adress
Mark 35 New york,AA
Elise 22 India,bb
Charlotte 45 France,cc
Readexcel.jsp :
<%#page import="java.sql.Statement"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.util.Date"%>
<%#page import="org.apache.poi.ss.usermodel.Cell"%>
<%#page import="org.apache.poi.ss.usermodel.Row"%>
<%#page import="org.apache.poi.xssf.usermodel.XSSFSheet"%>
<%#page import="org.apache.poi.xssf.usermodel.XSSFWorkbook"%>
<%#page import="java.io.File"%>
<%#page import="org.apache.commons.io.FilenameUtils"%>
<%#page import="org.apache.commons.fileupload.FileItem"%>
<%#page import="java.util.Iterator"%>
<%#page import="java.util.List"%>
<%#page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%#page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%#page import="org.apache.commons.fileupload.FileItemFactory"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>PRINT DATA FROM EXCEL FILE</title>
</head>
<body>
<%
try{
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(Exception e){
}
Iterator itr = items.iterator();
while(itr.hasNext()){
FileItem item = (FileItem)itr.next();
if(item.isFormField()){
}else{
String itemname = item.getName();
if((itemname==null || itemname.equals(""))){
continue;
}
String filename = FilenameUtils.getName(itemname);
File f = checkExist(filename);
item.write(f);
try{
XSSFWorkbook workbook = new XSSFWorkbook(item.getInputStream());
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()){
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC:
out.print(cell.getNumericCellValue() + "t");
break;
case Cell.CELL_TYPE_STRING:
out.print(cell.getStringCellValue() + "t");
break;}
}
out.println("");
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}catch(Exception e){
}
finally {
out.close();
}
%>
<%!
private File checkExist(String fileName){
String saveFile = "D:/upload/";
File f = new File(saveFile+"/"+fileName);
if(f.exists()){
StringBuffer sb = new StringBuffer(fileName);
sb.insert(sb.lastIndexOf("."),"-"+new Date().getTime());
f = new File(saveFile+"/"+sb.toString());
}
return f;
}
%>
</body>
</html>
I've created a table in my database named EXCELDATA with the header of the excel sheet :
ExcelData (Name varchar(50),age int,adress varchar(50));
what should i add to this code to get the data from the excel sheet to the mysql table ??
This is my excelimport.jsp file
try{
String name,age,address=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","username","password");
con.setAutoCommit(false);
PreparedStatement pstm = null ;
FileInputStream input = new FileInputStream("C://yourexcelfile.xls");
POIFSFileSystem fs = new POIFSFileSystem( input ); //creating a new poi reference to the given excel file
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Row row;
Statement st=con.createStatement();
for(int i=1; i<=sheet.getLastRowNum(); i++){ //points to the starting of excel i.e excel first row
row = (Row) sheet.getRow(i); //sheet number
if( row.getCell(0)==null) { name = "0";} //suppose excel cell is empty then its set to 0 the variable
else name = row.getCell(0).toString(); //else copies cell data to name variable
if( row.getCell(1)==null) { age = "0"; }
else age= row.getCell(1).toString();
if( row.getCell(2)==null) { address = "0"; }
else address = row.getCell(2).toString();
String sq="INSERT INTO ExcelData(name,age,address) VALUES('"+name+"','"+age+"','"+address+"')";
pstm = (PreparedStatement) con.prepareStatement(sq);//here we are using prepared statement because we are calling this statement for each row
pstm.execute();
System.out.println("Import rows "+i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
}catch(ClassNotFoundException e){
out.println(e);
}catch(SQLException ex){
out.println(ex);
}catch(IOException ioe){
out.println(ioe);
}
%>
i had written a jsp page with database connectivity getting the data from the database and printing it json format. And now i want that json data to be sent to the dojo data grid
Any help?
here is my jsp code
<%# page import="javax.security.auth.Refreshable"%>
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%# page import="org.json.simple.JSONObject"%>
<%# page import="org.json.simple.JSONArray"%>
<%#page import="java.util.LinkedList"%>
<%#page import="java.util.List"%>
<%
JSONObject responseObj = new JSONObject();
List<JSONObject> data = new LinkedList<JSONObject>();
try {
String dbms = "mysql";
String serverName = "localhost";
String portNumber = "3306";
String userName = "root";
String upassword = "";
String databaseName = "testind";
int datacount = 0;
String connectionURL = "jdbc:" + dbms + "://" + serverName
+ ":" + portNumber + "/" + databaseName;
Connection connection = null;
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL,
userName, upassword);
System.out.println("connection::" + connection);
String strQuery = "select * from user";
System.out.println(strQuery);
PreparedStatement st = connection.prepareStatement(strQuery);
ResultSet rs = st.executeQuery();
while(rs.next())
{
datacount++;
JSONObject dataobject = new JSONObject();
dataobject.put("sl",(String.valueOf(datacount)));
dataobject.put("name",rs.getString(1));
dataobject.put("email",rs.getString(2));
dataobject.put("mobi",rs.getString(3));
dataobject.put("add",rs.getString(4));
data.add(dataobject);
System.out.println("name&email::"+rs.getString(1) +","+rs.getString(2));
}
responseObj.put("data",data);
PrintWriter writer = response.getWriter();
System.out.println("{\"identifier\":\"data\",\"label\":\"data\",\"items\":" +responseObj+"}");
//writer.write("{\"identifier\":\"data\",\"label\":\"data\",\"items\":" +responseObj+"}");
writer.write(" "+responseObj+"");
writer.flush();
writer.close();
} catch (Exception e) {
System.out.println(e);
}`enter code here`
%>
here, i am getting the data from the database in the json format as following:
{"data":[{"sl":"1","email":"srinath#gma","name":"shivasrinat","mobi":"9849692921","add":"manikonda"},{"sl":"2","email":"srinath#gma","name":"shivasrinat","mobi":"9849692921","add":"manikonda"}]}
Remove data object in json
for example,
responseObj.put("data", data);
PrintWriter writer = response.getWriter();
System.out.println("{\"identifier\":\"data\",\"label\":\"data\",\"items\":" + responseObj + "}");
writer.write("{\"identifier\":\"Id\",\"label\":\"Organisation\",\"items\":" + responseObj.remove("data") + "}");
//writer.write(" " + responseObj + "");
writer.flush();
writer.close();