I am working on a web application using jsp and servlet using oracle.jdbc.OracleDriver.This code,working fine on my PC,but when trying to deploy build of application on other server,i am getting Exception like this.
java.sql.SQLException: Missing defines
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:158)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:206)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:305)
at oracle.jdbc.driver.OracleStatement.prepareAccessors(OracleStatement.java:793)
at oracle.jdbc.driver.T4CResultSetAccessor.getCursor(T4CResultSetAccessor.java:235)
at oracle.jdbc.driver.ResultSetAccessor.getObject(ResultSetAccessor.java:95)
at oracle.jdbc.driver.OracleCallableStatement.getObject(OracleCallableStatement.java:1947)
at org.apache.tomcat.dbcp.dbcp.DelegatingCallableStatement.getObject(DelegatingCallableStatement.java:143)
at cwep.Login.processRequest(Login.java:127)
at cwep.Login.doPost(Login.java:198)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:852)
at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:584)
at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1508)
at java.lang.Thread.run(Unknown Source)
After debugging my application,i found that when I am calling database(Oracle 10g) procedure on server side and getting cursor using callableStatement.registerOutParameter(1,OracleTypes.CURSOR), I am getting above Exception at
callableStatement.execute(); statement.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
static String CNPOOL = "cnpool";//Getting CNPOOL correctly for database connection
CallableStatement cs = null;
static DataSource dataSource;//Declared as global
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
CallableStatement cs = null;
String str = conectionPool;
System.out.println(str);
try {
InitialContext initContext = new InitialContext();
Context context = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) context.lookup(str);
System.out.println(" CxN Pool " + str);
String username = request.getParameter("username");
String password = request.getParameter("password");
ecode = Integer.parseInt(username);
System.out.println(" eCode " + ecode);
try {
con = ConnectionBean.getConnection(dataSource);
System.out.println(" CxN " + con.toString());
} catch (Exception e) {
System.out.println(" Opening the Cxn 1st Time" + e);
}
if(con!=null)
{
System.out.println(" Before Calling proc_user_login " + ecode);
cs = con.prepareCall("{call proc_user_login(?,?,?,?,?)}");
cs.setInt(1, empcode);
cs.setString(2, password);
cs.registerOutParameter(3, Types.NUMERIC);
cs.registerOutParameter(4, Types.NUMERIC);
cs.registerOutParameter(5, Types.VARCHAR);
try {
cs.execute();
} catch (Exception e) {
System.out.println("--------------------After executing first proc----------------------- ");
}
int message = cs.getInt(3);
if (message == 0) {
cs = con.prepareCall("{call proc_get_XXXlist(?,?)}");
cs.setInt(1, empcode);
cs.registerOutParameter(2, OracleTypes.CURSOR);
try {
System.out.println("Before executing XXXList proc ");
cs.execute(); //GETTING EXCEPTION AT THIS STATEMENT
System.out.println("After executing XXXList");
} catch (Exception e) {
System.out.println("exception in After executing secod proc ");
}
ResultSet rset = (ResultSet) cs.getObject(2);
Vector v1 = new Vector();
Vector v2 = new Vector();
Vector v3 = new Vector();
while (rset.next()) {
v1.addElement(rset.getString(1));
v2.addElement(rset.getString(2));
v3.addElement(rset.getString(3));
}
//rset.last();
String[] str1 = new String[v1.size()];
String[] str2 = new String[v2.size()];
String[] str3 = new String[v3.size()];
v1.copyInto(str1);
v2.copyInto(str2);
v3.copyInto(str3);
request.setAttribute("ecode", Integer.toString(ecode));
request.setAttribute("clientid", str1);
request.setAttribute("constring", str2);
request.setAttribute("URL", str3);
RequestDispatcher rd = request.getRequestDispatcher("XXX.jsp");
rd.forward(request, response);
//response.sendRedirect("XXX.jsp");
} else {
response.sendRedirect("index.jsp?val=" + message);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("EEE---" + e);
Utility.log("FinalExceptionToServlet.namelookup:", e.toString(), "SERVER", "E");
}
}
In this code,First database login_usr procedure execute properly,but when trying to execute 2nd procedure,which returns a cursor as outparameter,i'm getting above exception.If same code working fine on my PC,then why it throws exception when trying to execute callablestatement after Serverside deployment.Here I'm using Ojdbc14.jar and classes12.jar.Is there is any .jar missmatch..???
Thanks in advance.
As you have mentioned that the code was running earlier, Here the culprit could be OracleTypes. As its abstract class you need correct and concrete implementation of it which is your Driver.
Verify the version of the JDBC driver and the type of JDBC driver (Thin or OCI) you
Download new jar from oracle site or from here.
Also, try using oracle.jdbc.OracleTypes before looking for drivers.
e.g. cn.registerOutParameter(2, oracle.jdbc.OracleTypes.CURSOR);
Related
I've a servlet that checks username and password from database.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mvs_user", "root", "pass");
if (req.getParameter("usrnm") != null && req.getParameter("pwd") != null) {
String username = req.getParameter("usrnm");
String userpass = req.getParameter("pwd");
String strQuery = "select * from user where username='" + username + "' and password='" + userpass + "'";
System.out.println(strQuery);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(strQuery);
if (rs.next()) {
req.getSession(true).setAttribute("username", rs.getString(2));
res.sendRedirect("adminHome.jsp");
} else {
res.sendRedirect("index.jsp");
}
} else {
res.sendRedirect("login.jsp");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is the browser only displays a blank page and yet I expect it to display "Hello World" in the redirected page. Where could the problem be? Please help me troubleshoot.
You need to properly handle exceptions. You should not only print them but really throw them.
Replace
} catch (Exception e) {
e.printStackTrace(); // Or System.out.println(e);
}
by
} catch (Exception e) {
throw new ServletException("Login failed", e);
}
With this change, you will now get a normal error page with a complete stacktrace about the cause of the problem. You can of course also just dig in the server logs to find the stacktrace which you just printed instead of rethrowed.
There are several possible causes of your problem. Maybe a ClassNotFoundException or a SQLException. All which should be self-explaining and googlable.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
The infamous java.sql.SQLException: No suitable driver found
Unrelated to the concrete problem, your JDBC code is prone to resource leaking and SQL injection attacks. Do a research on that as well and fix accordingly.
I have a jasper report, I put it in the same package as servlets, I need to generate pdf file from it, but the code doesn't work and doesn't gives any error
public void print(String numBac , HttpServletRequest request,
HttpServletResponse response) {
try {
JasperDesign jasperDesign = JRXmlLoader
.load("fiche.jrxml");
String sql = "SELECT * FROM etudiant "
+ "INNER JOIN filiere ON etudiant.code_f=filiere.code_f "
+ "INNER JOIN lieu_nais ON etudiant.code_lieu=lieu_nais.code_lieu "
+ "INNER JOIN montant ON etudiant.code_m=montant.code_m WHERE bac='"
+ numBac + "'";
JRDesignQuery newQuery = new JRDesignQuery();
newQuery.setText(sql);
jasperDesign.setQuery(newQuery);
JasperReport report = JasperCompileManager
.compileReport(jasperDesign);
//JasperPrint print = JasperFillManager.fillReport(report, null, cnx);
//JasperViewer.viewReport(print);
byte[] byteStream;
byteStream = JasperRunManager.runReportToPdf(report, null, cnx);
OutputStream outStream = response.getOutputStream();
response.setHeader("Content-Sisposition", "inline,filename="+DOWNLOAD_FILE_NAME);
response.setContentType(FILE_TYPE);
response.setContentLength(byteStream.length);
outStream.write(byteStream, 0, byteStream.length);
} catch (Exception e) {
e.printStackTrace();
}
}
even if I want to generate jasper preview it doesn't shown up (code in comment)
What is baos for? Do you have to flush/close sos?
You can use bellow code. Here is complete Example using java servlet
Please download bellow jar file..
jasperreports-5.0.1.jar
commons-logging-1.1.2.jar
commons-digester-2.1.jar
commons-collections-3.2.1-1.0.0.jar
commons-beanutils-1.8.3.jar
groovy-all-2.1.3.jar
com.lowagie.text-2.1.7.jar
your database library
You can use like
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String path = "D:\\Software\\iReport-5.0.0-windows-installer\\u\\report4.jrxml";
JasperReport jasReport = JasperCompileManager.compileReport(path);
System.out.println("Jasper Report : " + jasReport);
//Database connection
Connection con = /*Database Connection*/;
System.out.println(con);
//If You have any Paramert use bellow like
Map paramMap = new HashMap();
paramMap.put("id", request.getParameter("id"));
//If You don't have parameter pass null instead of paramMap
JasperPrint jasPrint = JasperFillManager.fillReport(jasReport, paramMap, con);
System.out.println("Jasper Print : " + jasPrint);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/pdf");
JasperExportManager.exportReportToPdfStream(jasPrint, sos);
} catch (JRException ex) {
Logger.getLogger(Tests.class.getName()).log(Level.SEVERE, null, ex);
}
}
First of all, you have a spelling error here:
response.setHeader("Content-Sisposition", "inline,filename="+DOWNLOAD_FILE_NAME);
It should say "Disposition" instead of "Sisposition":
response.setHeader("Content-Disposition", "inline,filename="+DOWNLOAD_FILE_NAME);
Also, try using "attachment" instead of "inline":
response.setHeader("Content-Disposition", "attachment,filename="+DOWNLOAD_FILE_NAME);
And flush and close the outStream:
outStream.flush();
outStream.close();
Hope it helps!
private static final String DB_URL = "jdbc:derby://localhost:1527/ShopDB";
private static final String DB_CLOSE = DB_URL + ";shutdown=true";
private static final String DB_DRIVER = "org.apache.derby.jdbc.ClientDriver";
private static Connection con = null;
public WebshopDAO() {
try {
Class.forName(DB_DRIVER).newInstance();
con = DriverManager.getConnection(DB_CLOSE);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
I created a WebshopDAO object in another class. After that, I called a method in the WebDAO:
public CatalogDTO createCatalogDTO() {
String query = "SELECT * FROM Catalog";
CatalogDTO catalog = new CatalogDTO();
try {
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {
Catalog c = new Catalog();
c.setCName(rs.getString("CName"));
c.setCategoryNr(rs.getInt("CategoryNr"));
c.setSupercategoryNr(rs.getInt("SupercategoryNr"));
catalog.addCatalog(c);
}
} catch (SQLException e) {
e.getMessage();
}
return catalog;
}
So when I call the createCatalogDTO method, I get a NullPointerException. I don't know why. I checked the driver url and the db url and they are correct. I am using servlets for the first time. The class that uses this WebshopDAO is a servlet and I have a bit of a problem using the debugger.
Can you guys tell me the possible mistakes? I am looking for hours but I just can't find it.
EDIT:
Here is what I get:
java.lang.NullPointerException
WebshopDAO.createCatalogDTO(WebshopDAO.java:96)
Navigation.doGet(Navigation.java:28)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
please give me advice! I get form data in servlet and try to update the database, but it doesn't works. There is connection with database (without servlet code any data is properly added in db), but no any exception are thrown. The servlet get parameters - they are available in JSP by EL-expressions. I tried to update the db simply by statement, without using preparedStatement but it didn't help. Here it is the code:
public class ServletClass extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
DBConn dbConn = new DBConn();
String number = req.getParameter("number");
String amount = req.getParameter("amount");
String date = req.getParameter("date");
ArrayList list = dbConn.returnList(number, amount, date);
req.setAttribute("attr", list);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("index.jsp");
requestDispatcher.forward(req, resp);
}
}
public class DBConn {
public ArrayList<InvoicesBean> returnList(String number, String amount, String date) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
ArrayList<InvoicesBean> beanList = new ArrayList<InvoicesBean>();
PreparedStatement preparedStatement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/ved", "root", "1111");
statement = connection.createStatement();
preparedStatement = connection.prepareStatement("insert into invoices values(?, ?, ?);");
preparedStatement.setString(1, number);
preparedStatement.setString(2, amount);
preparedStatement.setString(3, date);
preparedStatement.executeUpdate();
resultSet = statement.executeQuery("SELECT * FROM invoices;");
while (resultSet.next()){
InvoicesBean invoicesBean = new InvoicesBean();
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
beanList.add(invoicesBean);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (resultSet != null) resultSet.close();
if (statement != null) statement.close();
if (connection != null) connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return beanList;
}
}
InvoiceBean-class is just a standard bean class with getters/setters
invoicesBean.setNumber(resultSet.getString("number"));
invoicesBean.setAmount(resultSet.getString("amount"));
invoicesBean.setDate(resultSet.getString("date"));
You can not have the database column names as 'number' or 'date'. they are reserved.
check the column names again.
for checking if this is the error, you can replace the column names by column numbers 1,2,3.
I've a servlet that checks username and password from database.
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mvs_user", "root", "pass");
if (req.getParameter("usrnm") != null && req.getParameter("pwd") != null) {
String username = req.getParameter("usrnm");
String userpass = req.getParameter("pwd");
String strQuery = "select * from user where username='" + username + "' and password='" + userpass + "'";
System.out.println(strQuery);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(strQuery);
if (rs.next()) {
req.getSession(true).setAttribute("username", rs.getString(2));
res.sendRedirect("adminHome.jsp");
} else {
res.sendRedirect("index.jsp");
}
} else {
res.sendRedirect("login.jsp");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
The problem is the browser only displays a blank page and yet I expect it to display "Hello World" in the redirected page. Where could the problem be? Please help me troubleshoot.
You need to properly handle exceptions. You should not only print them but really throw them.
Replace
} catch (Exception e) {
e.printStackTrace(); // Or System.out.println(e);
}
by
} catch (Exception e) {
throw new ServletException("Login failed", e);
}
With this change, you will now get a normal error page with a complete stacktrace about the cause of the problem. You can of course also just dig in the server logs to find the stacktrace which you just printed instead of rethrowed.
There are several possible causes of your problem. Maybe a ClassNotFoundException or a SQLException. All which should be self-explaining and googlable.
See also:
How should I connect to JDBC database / datasource in a servlet based application?
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
The infamous java.sql.SQLException: No suitable driver found
Unrelated to the concrete problem, your JDBC code is prone to resource leaking and SQL injection attacks. Do a research on that as well and fix accordingly.