Export excel from MySQL database using JSP - mysql

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.

Related

Downloading file from mySQL DB via servlet hosted on AWS

I am currently creating a webpage that displays a table with data from an Mysql DB. One of the columns is a file (stored as a BLOB in the DB). The name of the file is an anchor tag that links to my download.java servlet. My download servlet works when deploying locally, however now that I have deployed to an AWS ElasticBeanstalk instance the servlet does not work.
In the log it says the following:
org.apache.coyote.http11.AbstractHttp11Processor.process Error parsing HTTP request header
Note: further occurrences of HTTP header parsing errors will be logged at DEBUG level.
java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
and
/usr/share/tomcat8/Downloads/sdc.png (No such file or directory)
The servlet code:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "dbURL?serverTimezone=" + TimeZone.getDefault().getID();
Connection conn = DriverManager.getConnection(url , "username" , "password");
String fn = request.getParameter("Id");
String selectSQL = "SELECT file FROM Requests WHERE fileID=?";
PreparedStatement pstmt = conn.prepareStatement(selectSQL);
pstmt.setString(1, fn);
ResultSet rs = pstmt.executeQuery();
// write binary stream into file
String home = System.getProperty("user.home");
File file = new File(home+"/Downloads/" + fn);
FileOutputStream output = new FileOutputStream(file);
System.out.println("Writing to file " + file.getAbsolutePath());
while (rs.next()) {
InputStream input = rs.getBinaryStream("file");
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
output.write(buffer);
}
}
RequestDispatcher rd = request.getRequestDispatcher("/requests.jsp");
rd.forward(request, response);
rs.close();
pstmt.close();
} catch (SQLException | IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The servlet should download the file from the Mysql DB to the users download folder. However, this only works locally, on the AWS server it fails. I assume this is because:
String home = System.getProperty("user.home");
returns the home path of the AWS server instance, rather than the path of the users/visitors home path.
Please help me adjust my servlet so that it works on the AWS server
UPDATE: After some research I think that getting the path to the client's download folder is not possible. Now I think I need to make us of a 'save as' dialog box. Any tips on how to do this and resources that could help me do this is appreciated
I was able to get my servlet working using code posted in a question here
My working code now looks like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
try {
// Get Database Connection.
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "dbURL?serverTimezone=" + TimeZone.getDefault().getID();
conn = DriverManager.getConnection(url , "username" , "password");
String fileName = request.getParameter("Id");
System.out.println("File Name: " + fileName);
// queries the database
String sql = "SELECT file FROM requests WHERE fileID= ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, file);
ResultSet result = statement.executeQuery();
if (result.next()) {
// gets file name and file blob data
Blob blob = result.getBlob("file");
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("fileLength = " + fileLength);
ServletContext context = getServletContext();
// sets MIME type for the file download
String mimeType = context.getMimeType(fileID);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
// set content properties and header attributes for the response
response.setContentType(mimeType);
response.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileID);
response.setHeader(headerKey, headerValue);
// writes the file to the client
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
}
else {
// no file found
response.getWriter().print("File not found for the fn: " + fileName);
}
} catch (Exception e) {
throw new ServletException(e);
}
}

My code not displaying image on chrome browser but works find on internet explorer

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();
}
%>

Display multiple Blob files from mySQL

I want to create a gallery in a java web app project. The gallery reads images that are stored as BLOB files in a mySQL DB. This is what I have done but only the first Image in the db displays. Is it possible to read multiple BLOB images from a db or would I be better off creating a gallery from images stored in a folder?
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%
Blob image = null;
Connection con = null;
byte[ ] imgData = null ;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/capture","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("select file from photoentry");
if (rs.next()) {
image = rs.getBlob(1);
imgData = image.getBytes(1,(int)image.length());
}
else {
out.println("Display Blob Example");
out.println("image not found for given id>");
return;
}
// display the image
response.setContentType("image/jpg");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
} catch (Exception e) {
out.println("Unable To Display image");
out.println("Image Display Error=" + e.getMessage());
return;
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>

Query MySQL using JSP and Servlet POST method

I'm not sure if I'm trying to "print" my result correctly. What I'm trying to do is use JSP to take in the variable and then pass it to the servlet where it will query the database and then display the result. I tested querying my database in a different java file and I had no trouble with that. Any advice would be greatly appreciated!
JSP file:
<form method="post" action="HelloServlet"/>
Enter your name:<input name = "exName"/><br>
<input type = "submit" />
</form>
JAVA file (servlet):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
//response.setContentType("text/html; charset=ISO-8859-1");
PrintWriter out = response.getWriter();
java.sql.Connection con = null;
java.sql.PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/masters";
String user = "christine";
String password = "password";
try{
String exName = request.getParameter("exName");
con = DriverManager.getConnection(url, user, password);
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name ='"+exName+"';");
rs = pst.executeQuery();
while (rs.next()){
String name = rs.getString("description_txt");
out.print(exName);
out.print(name);
}
}catch(SQLException ex){
}finally {
try {
if (rs != null){
rs.close();
}
if (pst != null){
pst.close();
}
if (con != null){
con.close();
}
}catch(SQLException ex){
}
}
}
There are few things you need to change in your code.
As #BalusC mentioned do not suppress exception. Write exception to browser using out.println(ex); or throw new ServletException(ex). This will help you in finding the cause of problem.
Add Class.forName("com.mysql.jdbc.Driver"); before DriverManager.getConnection().
As you are already using PreparedStatement use
pst = con.prepareStatement("SELECT * FROM exercise WHERE exercise_name =?");
pst.setString(1, exName);
rs = pst.executeQuery();

How to display an image from the DB in JSP?

I need to retrieve image from MySQL DB.
I got a code snippet from somewhere but could not display the image properly in the jQuery panel.
The code runs in a new JSP page.
Can anyone tell me how to use outputstream effectively in my application?
The code I have is:
<% #page import = "java.sql.*" %>
<% #page import = "java.io.*" %>
<% Blob image = null;
Connection con = null;
byte[] imgData = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/aes", "root", "password");
stmt = con.createStatement();
rs = stmt.executeQuery("select PHOTO from tab_1 where name ='" + name + "'");
if (rs.next()) {
image = rs.getBlob(1);
imgData = image.getBytes(1, (int) image.length());
} else {
out.println("image not found for given id>");
return;
}
// display the image
response.setContentType("image/gif");
OutputStream o = response.getOutputStream();
o.write(imgData);
o.flush();
o.close();
} catch (Exception e) {
out.println("Unable To Display image");
out.println("Image Display Error=" + e.getMessage());
return;
} finally {
try {
rs.close();
stmt.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
%>
JSP is the wrong tool for this. JSP is a view technology. Any whitespace outside the <% %> will also be printed/sent to the response. It's in your case exactly that whitespace which malforms the binary integrity of the image and thus the image ends up being corrupted and unrenderable.
You have basically 2 options.
The simple/lazy way: remove all, I really mean all, whitespace outside <% %> including newlines.
Use the right tool: create a class which extends HttpServlet and move the code which you've there in the JSP into the doGet() method. Finally just call that servlet instead of the JSP.