Display Excel sheet in the Browser? - java

I need to display the newly generated excel (from tables using Apache POI) in a web browser (whatever it is, Firefox, Opera or IE). I've created the JSP file with
contentType="application/vnd.ms-excel"
But I'm not getting it.
Here's my code snippet :
<%#page session="true" contentType="application/vnd.ms-excel" pageEncoding="UTF-8"%>
<%#page import="org.apache.poi.ss.usermodel.CellStyle"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page import="org.apache.poi.ss.usermodel.CreationHelper"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
<%#page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>
<html>
<head>
<%!
int r=0;
HSSFWorkbook book;
HSSFSheet sheet;
HSSFRow row;
CreationHelper createHelper = book.getCreationHelper();
Connection conn;
Statement stmt;
ResultSet rs;
%>
<title>Report</title>
<%
book = new HSSFWorkbook();
sheet = book.createSheet("Report");
%>
</head>
<body>
<%
try {
// Header of the Excel File
row = sheet.createRow(r);
row.createCell(0).setCellValue("Visit ID");
row.createCell(1).setCellValue("Carrier Name");
row.createCell(2).setCellValue("Phone Number");
row.createCell(3).setCellValue("Patient Name");
row.createCell(4).setCellValue("Subscriber ID");
row.createCell(5).setCellValue("Subscriber Name");
row.createCell(6).setCellValue("Chart Number");
row.createCell(7).setCellValue("Date Of Birth");
row.createCell(8).setCellValue("Subscriber Employer");
row.createCell(9).setCellValue("Service Date");
row.createCell(10).setCellValue("Provider Name");
row.createCell(11).setCellValue("CPT Code");
row.createCell(12).setCellValue("Aging Date");
row.createCell(13).setCellValue("Total");
row.createCell(14).setCellValue("Follow Up Notes");
row.createCell(15).setCellValue("Internal Status Code");
CellStyle cellStyle = book.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("MM/dd/yyyy"));
Statement stNotes;
ResultSet rsNotes;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/maintain", "root", "root");
stmt = conn.createStatement();
stNotes = conn.createStatement();
rs = stmt.executeQuery("SELECT b.VisitID, b.CarrierName, b.PhoneNum, b.PatientName, "
+ "b.SubscriberID, b.SubscriberName, b.ChartNum, b.DoB, b.SubscriberEmp, "
+ "b.ServiceDate, b.ProviderName, b.CPTCode, b.BillingDate, b.BalanceAmt "
+ "FROM billing b INNER JOIN followup f ON b.VisitID = f.VisitID GROUP BY VisitID");
while(rs.next()) {
r++;
row = sheet.createRow(r);
row.createCell(0).setCellValue(rs.getString("VisitID"));
row.createCell(1).setCellValue(rs.getString("CarrierName"));
row.createCell(2).setCellValue(rs.getString("PhoneNum"));
row.createCell(3).setCellValue(rs.getString("PatientName"));
row.createCell(4).setCellValue(rs.getString("SubscriberID"));
row.createCell(5).setCellValue(rs.getString("SubscriberName"));
row.createCell(6).setCellValue(rs.getString("ChartNum"));
row.createCell(7).setCellValue(rs.getString("DoB"));
row.createCell(8).setCellValue(rs.getString("SubscriberEmp"));
row.createCell(9).setCellValue(rs.getString("ServiceDate"));
row.createCell(9).setCellStyle(cellStyle);
row.createCell(10).setCellValue(rs.getString("ProviderName"));
row.createCell(11).setCellValue(rs.getString("CPTCode"));
row.createCell(12).setCellValue(rs.getString("BillingDate"));
row.createCell(12).setCellStyle(cellStyle);
row.createCell(13).setCellValue(rs.getString("BalanceAmt"));
rsNotes = stNotes.executeQuery("SELECT Date, InternalStatusCode, FollowUpNote "
+ "FROM followup WHERE VisitID='" + rs.getString("VisitID") + "' ORDER BY Date");
while(rsNotes.next()) {
row.createCell(14).setCellValue(rsNotes.getString("Date") + " - " + rsNotes.getString("FollowUpNote"));
row.createCell(15).setCellValue(rs.getString("VisitID"));
}
}
}
catch(ClassNotFoundException cnf) {
out.print("<br> Error : MySQL Driver not found. <br>");
}
catch(Exception ex) {
out.print("Error : <br>" + ex);
}
%>
</body>
</html>
I'm getting this exception with Tomcat 6.0.26 :
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:156)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
root cause
java.lang.NullPointerException
org.apache.jsp.GetReport_jsp.<init>(GetReport_jsp.java:29)
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
java.lang.reflect.Constructor.newInstance(Constructor.java:513)
java.lang.Class.newInstance0(Class.java:355)
java.lang.Class.newInstance(Class.java:308)
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:145)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
Did I miss something or anything wrong?
Can anybody help me to get rid of this problem?
Thanx in advance.

The way you are trying to do it doesn't make any sense. You can't mix HTML with Excel like that. Better create a servlet instead of a JSP page and let this servlet output only the Excel file and nothing else.
Something like this:
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
// ... plus all the other libs you need
public class ExcelServlet extends HttpServlet {
public void doGet (HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException
{
HSSFWorkbook book;
// ...
// fill the book
// ...
res.setContentType("application/vnd.ms-excel");
book.write(res.getOutputStream());
res.getOutputStream().close();
}
}

HSSFWorkbook book;
HSSFSheet sheet;
HSSFRow row;
CreationHelper createHelper = book.getCreationHelper();
You are using the book object before initializing it.

I'd recommend not doing it this way.
Scriptlet code in JSPs is simply wrong.
Putting database access in a page like this isn't good, either.
A better approach would be Spring MVC and its JExcelView.

Here's a tip on how to debug JSP exceptions:
in the stacktrace, this class
java.lang.NullPointerException
org.apache.jsp.GetReport_jsp.<init>(GetReport_jsp.java:29)
is the generated java class for your GetReport.jsp. You can look in the $TOMCAT_HOME/work/<enginename>/<hostname>/<appname> folder to see the actual code generated, and see what exactly is at line 29.

Take a look at WorkbookTag project from SourceForge which does exactly what you need: HTML worksheet rendering using Apache POI... WorkbookTag

Related

Exception org.apache.jasper.JasperException:Unable to compile class for JSP: An error in jsp file:[/index.jsp] conn and DBConnect cannot be resolved

I'm using the latest TomCat version and I've recently installed Eclipse IDE for Java Developers - 2021-03
This is my class:this is my class package
package com.DB;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnect {
private static Connection conn;
public static Connection getConn()
{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/ebook-app","root","password");
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
So this is my jsp code for class:
<%#page import="com.DB.DBConnect.* " %>
<% Connection conn=DBConnect.getConn();//My error in this line.why?
out.println(conn);
%>
I'm getting Error like this:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Unable to compile class for JSP:
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: [33] in the jsp file: [/index.jsp]
Connection cannot be resolved to a type
30: </div>
31:
32: <%#page import="com.DB.DBConnect.* " %>
33: <% Connection conn=DBConnect.getConn();
34: out.println(conn);
35: %>
36:
An error occurred at line: [33] in the jsp file: [/index.jsp]
DBConnect cannot be resolved
30: </div>
31:
32: <%#page import="com.DB.DBConnect.* " %>
33: <% Connection conn=DBConnect.getConn();
34: out.println(conn);
35: %>
36:
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:103)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:213)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:482)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:392)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:362)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:346)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:605)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:400)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:378)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:326)
javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
Apache Tomcat/9.0.43
1st Error page
2nd Error page
Simply, What my problem is ,I'm getting the Error in jsp: line 33;
<% Connection conn=DBConnect.getConn(); //My error in this line.why?
I'm beginner for java,so please explain it in simple and clear way...
Your package com.DB has only one class i.e. DBConnect. You can import till com.DB.* and instead of getting connection object in jsp and printing here in jsp, return the string representation or string value of connection object from one method in your java class and then print it here.

no suitable driver found in jsp but not as java application

So I'm starting a web application and I want to use JSP pages (I've used them before) to access dynamically to the database and retrieve data from different tables.
I have by now a basic DatabaseHelper class, an App class that only tests the DB helper connection and a simple query, and a jsp file. The problem I'm facing is that the Database connection works great if run from the App.java class, but if I run it from the JSP file it will throw a SQLException saying it didn't find a suitable driver. (I'll leave code and error message below)
I've tried different options I've read here in StackOverflow and other pages: I put the driver in the server's classpath, in the WEB-INF/lib, in the project's build path as external JAR (this one works for the Java app class mentioned before)...
And here is the environment:
Database: Microsoft SQL Server 2017
Driver: sqljdbc42.jar
Server: Glassfish 4.0
IDE: Eclipse Oxygen.3
So any hint on how can I solve this problem and use the Database helper from the jsp file will be happily welcome.
Thanks!
Error message:
[2018-03-28T12:39:48.883+0200] [glassfish 4.0] [SEVERE] [] [pl.mais.db.DBHelper] [tid: _ThreadID=21 _ThreadName=http-listener-1(3)] [timeMillis: 1522233588883] [levelValue: 1000] [[
java.sql.SQLException: No suitable driver found for jdbc:sqlserver://localhost;databaseName=campus_db;user=******;password=*****
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:270)
at pl.mais.db.DBHelper.open(DBHelper.java:41)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:58)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:748)
]]
App.java
package pl.mais.general;
import pl.mais.db.DBHelper;
public class App {
public static void main (String[] args) {
DBHelper db = new DBHelper();
db.open();
db.testSelectFaculties();
db.close();
}
}
DBHelper.java
package pl.mais.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author sergi
*
*/
public class DBHelper {
// JDBC driver name and database URL
private final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
private final String DB_URL = "jdbc:sqlserver://localhost;databaseName=campus_db;";
// Database credentials
private static final String DB_USER = "*****";
private static final String DB_PASS = "*****";
private Connection conn = null;
private Statement stmt = null;
public DBHelper() {
try {
Class.forName(JDBC_DRIVER);
} catch (Exception e) {
e.printStackTrace();
}
}
public void open() {
try {
String connectionUrl = DB_URL + "user=" + DB_USER + ";password=" + DB_PASS;
//System.out.println("Connecting to database...");
conn = DriverManager.getConnection(connectionUrl);
//System.out.println("Creating statement...");
stmt = conn.createStatement();
} catch (SQLException ex) {
Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void close() {
try {
stmt.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(DBHelper.class.getName()).log(Level.SEVERE, null, ex);
}
}
public String[] testSelectFaculties() {
try {
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT * FROM faculties";
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
ArrayList<String> results = new ArrayList<String>();
// Iterate through the data in the result set and display it.
while (rs.next()) {
results.add(rs.getString(1) + " - " + rs.getString(2));
System.out.println(rs.getString(1) + " - " + rs.getString(2));
}
return (String[])results.toArray();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
index.jsp
<%#page import="pl.mais.db.DBHelper"%>
<%# 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>
<%
DBHelper db = new DBHelper();
db.open();
String[] faculties = db.testSelectFaculties();
db.close();
for (int i = 0; i < faculties.length; i++) {
%>
<h2>
<%=
faculties[i]
%>
</h2>
<%
}
%>
</body>
</html>
Making the JDBC Driver JAR Files Accessible:
To integrate the JDBC driver into a GlassFish Server domain, copy the JAR files into the domain-dir/lib directory, then restart the server. This makes classes accessible to all applications or modules deployed on servers that share the same configuration.
Source: Oracle documentation.

error in your SQL syntax near

I need help. I'm developing app for uploading text files. For this moment I encountered error which I cannot clearly understand. Here is my code:
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Servlet based API for querying text file</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">
</head>
<body>
<h3>Please choose file</h3>
<div class="container">
<form action="TextProccessing" method="post"
enctype="multipart/form-data">
<div class="form-group">
<label for="browseTxt">Upload file:</label>
<input type="file" name="browseTxt" id="browseTxt" value="select text file">
<p class="help-block">
<b>Note:</b> Please choose .txt file only
</p>
</div>
<BUTTON class="btn btn-default" type="submit">Upload</BUTTON>
</form>
</div>
<h2>Place for text</h2>
<div class="container"></div>
</body>
</html>
TextProccessing
package com.controller;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#MultipartConfig(maxFileSize = 16177215)
public class TextProccessing extends HttpServlet {
private static final long serialVersionUID = 1L;
private final static String RESULT_PAGE = "/result.jsp";
private final String dbURL = "jdbc:mysql://127.0.0.1:3306/textfilesdb";
private final String dbUser = "root";
private final String dbPassword = "root";
// for this moment
private String file_Name_test = "file_Name_test";
private String file_size_test = "file_size_test";
private String fileCreationDate_test = "fileCreationDate_test";
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream inputStream = null;
Part filePart = request.getPart("browseTxt");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPassword);
// constructs SQL statement
String sql = "INSERT INTO files(file_Name, file_size, fileCreationDate, text_file) values (?, ?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, file_Name_test);
statement.setString(2, file_size_test);
statement.setString(3, fileCreationDate_test);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(4, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
getServletContext().getRequestDispatcher(RESULT_PAGE).forward(request, response);
}
}
}
it seems ok but I have such error stacktrace
browseTxt 1189 text/plain
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MySQL server version for the right syntax to use near '?le_Name,
file_size, ?leCreationDate, text_file) values ('?le_Name_test',
'file_' at line 1 at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown
Source) at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
Source) at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:400) at
com.mysql.jdbc.Util.getInstance(Util.java:383) at
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847) at
com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783) at
com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447) at
com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594) at
com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545) at
com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
at
com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
at com.controller.TextProccessing.doPost(TextProccessing.java:68) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:648) at
javax.servlet.http.HttpServlet.service(HttpServlet.java:729) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
And my DB structure
create database TextFilesDB;
use TextFilesDB;
CREATE TABLE files ( id int(11) NOT NULL AUTO_INCREMENT,
file_Name varchar(45) NOT NULL, file_size varchar(45) DEFAULT
NULL, fileCreationDate varchar(45) DEFAULT NULL, text_file
mediumblob, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf16
It seems that you have some format problem with the columns names. Can you try to replace
INSERT INTO files(file_Name, file_size, fileCreationDate, text_file) values (?, ?, ?, ?)
by
INSERT INTO files(file_Name, file_size, fileCreationDate, text_file) values (?, ?, ?, ?)

Calling Java method that calls another Java method from JSP

So I am trying to call a Java method in LoginCheckAction.java from LoginCheckAction.jsp. The method in the prior calls a method in LoginCheckBO.java which is an interface implemented by LoginCheckBOImpl. I am getting an error.
LoginCheckAction.jsp
<%# page import="action.LoginCheckAction" %>
<%# page import="bo.LoginCheckBO" %>
<%# page import="bo.impl.LoginCheckBOImpl" %>
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
LoginCheckAction ls = new LoginCheckAction();
// ls.printSomething(username);
ls.startBo(username);
%>
LoginCheckAction.java
package action;
import bo.LoginCheckBO;
import bo.impl.LoginCheckBOImpl;
public class LoginCheckAction{
LoginCheckBO bo = new LoginCheckBOImpl();
public LoginCheckAction(){
super();
}
public void printSomething(String username){
System.out.println(username);
}
public void startBo(String username){
bo.printSomethingBO(username);
}
}
LoginCheckBO.java
package bo;
public interface LoginCheckBO{
public void printSomethingBO(String username);
}
LoginCheckBOImpl.java
package bo.impl;
import bo.LoginCheckBO;
public class LoginCheckBOImpl implements LoginCheckBO{
public void printSomethingBO(String username){
System.out.println(username);
}
}
The error is in LoginCheckAction.jsp and I don't understand why I am getting that error. Can someone please explain? Here is the error:
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /jsp/LoginCheckAction.jsp at line 10
7:
8: LoginCheckAction ls = new LoginCheckAction();
9: // ls.printSomething(username);
10: ls.startBo(username);
11: %>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
root cause
java.lang.NullPointerException
action.LoginCheckAction.startBo(LoginCheckAction.java:26)
org.apache.jsp.jsp.LoginCheckAction_jsp._jspService(LoginCheckAction_jsp.java:65)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)

Very little Jdbc issue

Can anyone please tell me to use which jdbc driver to connect with oracle 9.0.1.1?
i'm using jdk1.6.
i've used classes12 and ojdbc6 but they are causing errors.
Following is my code
Following bean's database related code is working in simple Java application but when i use it within JSF page it is giving Java null pointer exception error.
Thanks in advance.
Bean class:
import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
#ManagedBean
#SessionScoped
public class Db implements Serializable{
int eId;
public int geteId() {
return eId;
}
public void seteId(int eId) {
this.eId = eId;
}
public static Connection getConnection() throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:#localhost:1521:globldb3";
String username = "scott";
String password = "tiger";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public String addEmployee() throws Exception{
Connection conn = null;
PreparedStatement pstmt = null;
try {
int a = this.eId;
conn = getConnection();
String query = "INSERT INTO c(n) VALUES(?)";
pstmt = conn.prepareStatement(query);
pstmt.setInt(1,a);
pstmt.executeUpdate(); // execute insert statement
return "success";
} catch (Exception e) {
e.printStackTrace();
return "failure";
} finally {
pstmt.close();
conn.close();
}
}
}
Following is my JSF page
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<body>
<h:form>
<p>Enter value <h:inputText value="#{db.eId}"/> </p>
<p> <h:commandButton value="Add record" action="#{db.addEmployee}"/> </p>
</h:form>
</body>
</html>
Following exception is comeing while using ojdbc6.jar.
java.sql.SQLException: ORA-03120: two-task conversion routine: integer overflow
Following is stack trace of above exception
java.sql.SQLException: ORA-03120: two-task conversion routine: integer overflow
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:440)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:837)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:445)
at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:191)
at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:523)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:207)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1010)
at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1315)
at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3576)
at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3657)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1350)
at erpJavaFiles.Employee.addEmployee(Employee.java:113)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:787)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1252)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:108)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:558)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:379)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:243)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:259)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:237)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
try ojdbc14.jar. it will work definetely.
You should not be using classes12.jar; that's for JDK 1.2. ojdbc6.jar is what you want; that's appropriate for JDK 6.
Check the value of a and the data type of column n in table c. Ensure column n has a set length, i.e. NUMBER(10,0) vs just NUMBER.
I would try the query in SQL Developer too. If you don't already have it you can get it here.
There's Oracle bug 5671074 in some 9i versions that causes this exception when server and client have different "endianness".
Are you sure it's not your case?

Categories