java.io.FileNotFoundException:<Excel FileName> the system cannot find the file specified - java

I'm getting the following error. I am going to insert the excel sheet data into MYSQL database. When I upload the Excel sheet and press submit button ,the following exception occured.
java.io.FileNotFoundException: studentsdetails1.xls (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
Here is my code. In this I am going to insert the excel file data into database.
index.jsp-
<%# 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>
<form action ="Excel.jsp" method="post" >
<input type="file" name= "excelfile" size="20" id="file" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Excel.jsp-
<%# 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>
<%# page import ="java.util.Date" %>
<%# page import ="java.sql.*" %>
<%# page import ="java.io.*" %>
<%# page import ="java.io.FileNotFoundException" %>
<%# page import ="java.io.IOException" %>
<%# page import ="java.util.Iterator" %>
<%# page import ="java.util.ArrayList" %>
<%# page import ="javax.servlet.http.HttpServletRequest"%>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFCell" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFRow" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFSheet" %>
<%# page import ="org.apache.poi.hssf.usermodel.HSSFWorkbook" %>
<%# page import ="akshay.Exceltest" %>
<%# page import ="org.apache.poi.poifs.filesystem.POIFSFileSystem" %>
<%!
Connection con;
PreparedStatement ps=null;
Statement stmt= null;
public static ArrayList readExcelFile(String fileName)
{
/** --Define a ArrayList
--Holds ArrayList Of Cells
*/
System.out.println(fileName);
ArrayList cellArrayLisstHolder = new ArrayList();
try{
/** Creating Input Stream**/
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext()){
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
ArrayList cellStoreArrayList=new ArrayList();
while(cellIter.hasNext()){
HSSFCell myCell = (HSSFCell) cellIter.next();
cellStoreArrayList.add(myCell);
}
cellArrayLisstHolder.add(cellStoreArrayList);
}
}catch (Exception e){e.printStackTrace(); }
return cellArrayLisstHolder;
}%>
<%
String file = request.getParameter("excelfile");
String fileName=""+file+""; //testExcel.xls Excel File name
//Read an Excel File and Store in a ArrayList
ArrayList dataHolder=readExcelFile(fileName);
//Print the data read
//printCellDataToConsole(dataHolder);
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/<dtatabse>", "name", "password");
stmt =con.createStatement();
String query="insert into students12(id,name,age) values(?,?,?)";
ps=con.prepareStatement(query);
int count=0;
ArrayList cellStoreArrayList=null;
//For inserting into database
for(int i=1;i<dataHolder.size();i++) {
cellStoreArrayList=(ArrayList)dataHolder.get(i);
ps.setString(1,((HSSFCell)cellStoreArrayList.get(0)).toString());
ps.setString(2,((HSSFCell)cellStoreArrayList.get(1)).toString());
ps.setString(3,((HSSFCell)cellStoreArrayList.get(2)).toString());
count= ps.executeUpdate();
//out.print(((HSSFCell)cellStoreArrayList.get(2)).toString() + "\t");
}
//For checking data is inserted or not?
if(count>0)
{
%>
Following deatils from Excel file have been inserted in student table of database
<table>
<tr>
<th>Student's Name</th>
<th>Class</th>
<th>Age</th>
</tr>
<%
for (int j=1;j < dataHolder.size(); j++) {
cellStoreArrayList=(ArrayList)dataHolder.get(j);%>
<tr>
<td><%=((HSSFCell)cellStoreArrayList.get(0)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(1)).toString() %></td>
<td><%=((HSSFCell)cellStoreArrayList.get(2)).toString() %></td>
</tr>
<%}
}
else
{%>
<center> Details have not been inserted!!!!!!!!!</center>
<% }
}catch(Exception e)
{}%>
</table>
</body>
</html>

Add enctype="multipart/form-data" in form like.
<form action ="Excel.jsp" method="post" enctype="multipart/form-data" >
Rest looks fine.

Related

How to display List results in JSP Page?

I Have a class that find Google search results. And i have a JSP page that i want to show the results in. But i can't do it.
Heres my UrlOku class :
public static void GetUrl() {
final String keyword = "emre varol";
final String url = "https://www.google.com/search?q="+keyword;
try {
final Document document = Jsoup.connect(url).get();
List<String> myList = new ArrayList<String>();
for(Element row: document.select("div[class=g]")) {
final String title = row.select("div[class=TbwUpd NJjxre]").text();
myList.add(title);
}
}
And heres my JSP page :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="urlpaket.Urloku" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:include page="menu.jsp"></jsp:include>
<%
if(session.getAttribute("username")==null){
response.sendRedirect("login.jsp");
}
%>
WELCOME ${username}
<%
Urloku oku = new Urloku();
oku.GetUrl();
%>
<c:forEach items="${myList}" var="item">
<tr>
<td><c:out value="${item.title}" /></td>
</tr>
</br>
</c:forEach>
And there is nothing in the welcome.jsp file.
Any help would be appreciated!
How is myList variable available in you JSP? This needs to be set in pageContext before accessing it using ${myList}.
You can change the signature to public static List GetUrl()
and do something like this
Urloku oku = new Urloku();
List<String> myList = oku.GetUrl();
pageContext.setAttribute("myList ",myList );
Now it should be available.

Store image in h2 database

I am working with Spring MVC architecture and Hibernate using H2 Database.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!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>Add New Product</title>
</head>
<body>
<p>Add New Product !!</p>
<form:form action="addProducttoDB" commandName="product" method="POST" enctype="multipart/form-data">
Product id :<br>
<label>Product Name : </label><form:input path="product_name" value="Product Name"/> <br>
Product Desc : <form:input path="product_desc" value="Product Desc"/><br>
Select Image :<form:input type="file" path=""/><br>
Submit : <input type="submit" value="Add">
</form:form>
</body>
</html>
As in above code - its storing the information about prodouct and adding to Database using action request -> "addProducttoDB" , Model object -> product
And path is the column name, now I would like to save an image along with the details. How can I do that?
You need to do following change
give name to <form:input type="file" path="productImg" name="productImg/>
Declare MultipartFile object in method signature where datastore logic is there
call the save saveMultipartFile method inside the save method
method
private void saveMultipartFile( MultipartFile files)
{
if(!files.isEmpty()){
try {
String fileName = files.getOriginalFilename();
String dirLocation ="Path where you want to save image";
if(!new File(dirLocation).exists()){
File file = new File(dirLocation);
file.mkdirs();
}
byte[] bytes = files.getBytes();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(dirLocation+new File(fileName)));
bufferedOutputStream.write(bytes);
bufferedOutputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Trying to check MySQL database with java, jsp

I am trying to print some data from my database in Mysql using some classes in java and jsp. It's my first time doing this. I googled a lot but nothing helped me. Here is my code:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
<form action="DB_results.jsp">
<input type = "submit" value = "Database">
</form>
</body>
</html>
Draw.java
package DB_draw;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Draw {
ResultSet myRs;
public ResultSet getMyRs() {
return myRs;
}
public void setMyRs() {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/tst","root","");
Statement myStmt = myConn.createStatement();
this.myRs = myStmt.executeQuery("select * from tst.people");
while (this.myRs.next())
{
System.out.println(this.myRs.getString("onoma") + " " + this.myRs.getString("epitheto") + " " + this.myRs.getInt("id"));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
DB_results.jsp
<%#page import="java.sql.ResultSet"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.io.*,java.util.*,java.sql.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%# page import="DB_draw.*" %>
<jsp:useBean id="DB_draw" class="DB_draw.Draw" scope="session" />
<jsp:setProperty name="DB_draw" property="*"/>
<!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>Database</title>
</head>
<body style="background-color:black">
<div style = "color:yellow; font-family:fantasy; font-size:30px">
<%
ResultSet myRs = DB_draw.getMyRs();
if(myRs == null) out.println("Problem");
else
while(myRs.next())
{
out.println(myRs.getString("onoma") + " " + myRs.getString("epitheto") + " " + myRs.getInt("id"));
}
%>
</div>
</body>
</html>
The Problem is that when i try to print the results in DB_results.jsp using variable myRs, myRs == NULL. Why is this happening? I'm using Tomcat-Apache 8.0.
You never call setMyRS(). And even if you did, setMyRS() iterates through the resultset, so myRs.next() would always return false in the JSP.

How to retrieve image from mysql db and show it inside <td> and <img> tag in HTML?

How to retrieve image from mysql db and show it inside tag in HTML and that img tag should be placed inside ? Here s my code:
It displays only the image . Its not showing any content other than image.
Thanks in advance.
<%# 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>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%
try{
//PrintWriter out=response.getWriter();
out.println("Retrieve Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "db";
String userName = "root";
String password = "root";
Connection con = null;
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
%>
<table border='1'>
<tr>
<td>Name:</td><td>
</td>My Name</td>
</tr>
<tr>
<td>Image:</td>
<td width=10px;>
<%
PreparedStatement pre1 = con.prepareStatement("select * from image where id="+8);
ResultSet rs1=pre1.executeQuery();
while(rs1.next())
{byte[] bytearray1 = new byte[4096];
int size1=0;
InputStream sImage1;
sImage1 = rs1.getBinaryStream(2);
response.reset();
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition","filename=logo.jpg");
while((size1=sImage1.read(bytearray1))!= -1 )
{
response.getOutputStream().write(bytearray1,0,size1);
}
response.flushBuffer();
sImage1.close();
rs1.close();
}
out.println("Retrieved Successfully!");
pre.close();
con.close();
}
catch (Exception e){
out.println(e.getMessage());
}
%>
</td></tr>
</table>
</body>
</html>
Images are loaded as separate requests to the request that loaded the html. As such you need to:
establish a URL encoding scheme that you use when specifying the src of the img element.
map a servlet (or similar) to that URL. The servlet loads the image based on the parameters of the URL returning that image in its response.
I found out.
r.jsp:-
<%# 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>
<table border=2>
<tr><th>DISPLAYING IMAGE</th></tr>
<tr><td>hi</td></tr>
<tr><td>
<img src="retrieve.jsp" width=130 height=130>
</td></tr>
</table>
</body>
</html>
retrieve.jsp:-
<%# 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">
</head>
<body>
<%# page import="java.io.*"%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%# page import="java.text.*"%>
<%# page import="javax.servlet.*"%>
<%# page import="javax.servlet.http.*"%>
<%# page import="javax.servlet.http.HttpSession"%>
<%# page language="java"%>
<%# page session="true"%>
<%
try{
//PrintWriter out=response.getWriter();
out.println("Retrieve Image Example!");
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String dbName = "db";
String userName = "root";
String password = "root";
Connection con = null;
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
Statement st = con.createStatement();
PreparedStatement pre1 = con.prepareStatement("select * from image where id="+8);
ResultSet rs1=pre1.executeQuery();
while(rs1.next())
{byte[] bytearray1 = new byte[4096];
int size1=0;
InputStream sImage1;
sImage1 = rs1.getBinaryStream(2);
response.reset();
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition","filename=logo.jpg");
while((size1=sImage1.read(bytearray1))!= -1 )
{
response.getOutputStream().write(bytearray1,0,size1);
}
response.flushBuffer();
sImage1.close();
rs1.close();
}
pre.close();
con.close();
}
catch (Exception e){
out.println(e.getMessage());
}
%>
</body>
</html>

jfreechart in jsp

i want to create a pie chart in jsp using jfree chart, i am using this code
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.awt.*" %>
<%# page import="java.io.*" %>
<%# page import="org.jfree.chart.*" %>
<%# page import="org.jfree.chart.entity.*" %>
<%# page import ="org.jfree.data.general.*"%>
<%
final DefaultPieDataset data = new DefaultPieDataset();
data.setValue("One", new Double(43.2));
data.setValue("Two", new Double(10.0));
data.setValue("Three", new Double(27.5));
data.setValue("Four", new Double(17.5));
data.setValue("Five", new Double(11.0));
data.setValue("Six", new Double(19.4));
JFreeChart chart = ChartFactory.createPieChart
("Pie Chart ", data, true, true, false);
try {
final ChartRenderingInfo info = new
ChartRenderingInfo(new StandardEntityCollection());
final File file1 = new File("../webapps/jspchart/
web/piechart.png");
ChartUtilities.saveChartAsPNG(
file1, chart, 600, 400, info);
} catch (Exception e) {
out.println(e);
}
%>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<IMG SRC="piechart.png" WIDTH="600" HEIGHT="400"
BORDER="0" USEMAP="#chart">
</body>
</html>
The problem is that i am getting this exception "java.io.FileNotFoundException: ../webapps/jspchart/web/piechart.png (No such file or directory) "
any thoughts??
Exception clearly says "java.io.FileNotFoundException: ../webapps/jspchart/web/piechart.png (No such file or directory)"
Here the piechart.png(../webapps/jspchart/web/piechart.png) or web directory is not exists.
Verify these info and fix it.
Fix can be:-
Creating a Web folder under jspchart folder OR
Placing a piechart.png file under Web folder
Then try to compile and run application once again.
i got this.Actually i needed the pie chart to fetch values from a database.
The database's first column is the name and second its value.
The code is:
Table name is chart and database is maj
<%# page import="java.io.*"%>
<<%# page import="java.awt.*" %>
<%# page import="java.io.*" %>
<%# page import="java.sql.*" %>
<%# page import="org.jfree.data.jdbc.JDBCPieDataset" %>
<%# page import="org.jfree.chart.plot.PlotOrientation" %>
<%# page import="org.jfree.chart.JFreeChart" %>
<%# page import="org.jfree.chart.ChartUtilities" %>
<%# page import="org.jfree.chart.ChartFactory" %>
<%# page import="org.jfree.data.general.DefaultPieDataset" %>
<%# page import="org.jfree.chart.*"%>
<%# page import="org.jfree.chart.entity.*"%>
<%# page import="org.jfree.data.general.*"%>
<%# page import="org.jfree.chart.plot.PiePlot;" %>
<%
String query = "SELECT * from chart";
JDBCPieDataset dataset = new JDBCPieDataset("jdbc:mysql://localhost:3306/maj", "com.mysql.jdbc.Driver","root", "password");
dataset.executeQuery(query);
JFreeChart chart = ChartFactory.createPieChart("File System",dataset, true, true, false);
//chart.setBackgroundPaint(new Color(222, 222, 255));
final PiePlot plot = (PiePlot) chart.getPlot();
plot.setBackgroundPaint(Color.white);
plot.setCircular(true);
try {
final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
final File file1 = new File(getServletContext().getRealPath(".") + "/piechart.png");
ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
} catch (Exception e) {
System.out.println(e);
}
%>
<html>
<body>
Heading
<IMG SRC="piechart.png" WIDTH="500" HEIGHT="400" style="border:4px solid orange;" USEMAP="#chart" alt="image">
</body>
</html>
Did you check this path? is the file there? (i bet not).
Copy the file under that directory and your problem will be solved.

Categories

Resources