error in your SQL syntax near - java

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 (?, ?, ?, ?)

Related

How to fix HTTP Status 500 - Internal Server Error | Servlet Error

I'm trying to send variables between jsp and servlets, but I got this error that I still can't figure out why. It keeps sending HTTP Status 500 error.
it sending HTTP status 500 eror and java.lang.NullPointerException
but when i test java class in junit it ran fine.
this is jsp:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%#page import="model.StudentDao"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Student</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<h1>Student</h1>
<table class="table">
<tr>
<th>Student ID</th>
<th>Student Name</th>
</tr>
<c:forEach items="${requestScope.students}" var="student">
<tr>
<td><c:out value="${student.getStudentId()}"/></td>
<td><c:out value="${student.getStudentName()}"/></td>
</tr>
</c:forEach>
</table>
</body>
</html>
and this my servlet:
package controller;
import...
#WebServlet("/StudentListServlet")
public class StudentListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public StudentListServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DbConnect dbConnect = new DbConnect();
Connection connection = dbConnect.connect();
StudentDao studentDao = new StudentDao(connection);
ArrayList<Student> students = null;
try {
students = studentDao.findAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("students", students);
request.getRequestDispatcher("student.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
StudentDao :
package model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class StudentDao {
private Connection connection;
public StudentDao(Connection connection) {
super();
this.connection = connection;
}
public ArrayList<Student> findAll() throws SQLException{
ArrayList<Student> students = new ArrayList<>();
Student student = null;
Statement statement = this.connection.createStatement();
String sqlText = "SELECT * FROM student";
ResultSet resultSet = statement.executeQuery(sqlText);
while(resultSet.next()){
student = new Student();
student.setStudentId(resultSet.getString("student_Id"));
student.setStudentName(resultSet.getString("student_Name"));
students.add(student);
}
resultSet.close();
statement.close();
return students;
}
}
DbConnect:
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnect {
private static final String URL = "jdbc:mysql://localhost:3306/university";
private static final String USER = "root";
private static final String PASSWORD = "";
private Connection connection;
public Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(URL, USER, PASSWORD);
if(!this.connection.isClosed())
System.out.println("MySQL Connected");
else
System.out.println("MySQL Connect fail!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return this.connection;
}
public void close() throws SQLException {
this.connection.close();
}
}
Stack Trace :
SEVERE: Servlet.service() for servlet [controller.StudentListServlet] in context with path [/MySQLDemo] threw exception
java.lang.NullPointerException
at model.StudentDao.findAll(StudentDao.java:21)
at controller.StudentListServlet.doGet(StudentListServlet.java:34)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:800)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:800)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1471)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
Sorry for the long post.
anyone with an idea why this get error?
You are not loading the jdbc driver in your servelet
you can the jdbc driver as follows:
String driver = "com.mysql.jdbc.Driver";
// Load the JDBC driver
Class driver_class = Class.forName(driver);

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.

Unable to execute jdbc query on a servlet [duplicate]

This question already has answers here:
How to add JAR libraries to WAR project without facing java.lang.ClassNotFoundException? Classpath vs Build Path vs /WEB-INF/lib
(5 answers)
Closed 6 years ago.
I am trying to create an html page which takes some input and saves that data in oracle database using jdbc and servlet.
This is the HTML file
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="HelloServlet" method="post">
<input type="text" placeholder="ID" name="id">
<input type="text" placeholder="NAME" name="name">
<input type="text" placeholder="SALARY" name="salary">
<input type="submit" value="submit">
</form>
</body>
</html>
Here is javafile contains the servlet
package com.gaurav;
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.jasper.tagplugins.jstl.core.Out;
#WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Set response content type
// Actual logic goes here.
//String name=request.getParameter("name");
//out.println(name);
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url="jdbc:oracle:thin:#localhost:1521:xe";
String user="system";
String pass="inception";
try{
int id=Integer.parseInt(request.getParameter("id"));
String name=request.getParameter("name");
int salary=Integer.parseInt(request.getParameter("salary"));
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(url,user,pass);
String query="INSERT INTO employee VALUES(?,?,?)";
PreparedStatement stm=con.prepareStatement(query);
stm.setInt(1, id);
stm.setString(2, name);
stm.setInt(3, salary);
stm.executeUpdate();
con.close();
}
catch(ClassNotFoundException e){
out.println("class not found ");
}
catch(SQLException e){
out.println("SQL Exception");
}
}
#Override
public void destroy() {
// resource release
super.destroy();
}
}
file hierarchy
whenever i tries to run the above program,it doesn't shows any error but when i write some data and press the submit button it thorws a ClassNotFound Exception.I don't have any idea whats happening.so someone help me.
Stack Trace:
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1285)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1119)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.gaurav.HelloServlet.doPost(HelloServlet.java:50)
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:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:783)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:789)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
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)
It looks like you are using Oracle 10g. From Oracle 9i onwards, support for oracle.jdbc.driver.OracleDriver is deprecated (documentation here). Could you try using oracle.jdbc.OracleDriver instead?
Check if you loaded the correct oracle jar driver on your project.

java.lang.NumberFormatException: null java.lang.Integer.parseInt(Unknown Source)

I am trying to get values from jsp page and want store those values in mysql(xampp) database using java.
The connection is established and successfully logged in but when i tried to get values null pointer exception occurs
MainController.java is
package classes;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
//import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class MainController
*/
#WebServlet("/MainController")
public class MainController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public MainController() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
}
//#SuppressWarnings("null")
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String url= "jdbc:mysql://localhost/meeting_planner";
System.out.println("start");
// boolean stfound = false;
try {
System.out.println("reached controller");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "admin", "admin");
Statement stmt = con.createStatement();
//System.out.println("connection");
String button=request.getParameter("button");
System.out.println(button + request.getParameter("AId"));
if(button.equals("login"))
{
System.out.println("inside if");
String AdminId= request.getParameter("AId");
String password= request.getParameter("Password");
System.out.println(AdminId+" sadia "+password);
if(!(AdminId=="" || password==""))
{
boolean stfound = false;
System.out.println(AdminId+" sadia "+password);
String query = "SELECT AId,Password FROM administrator";
ResultSet rs = stmt.executeQuery(query);
System.out.println(query);
while(rs.next())
{
String dbadminid = rs.getString(1);
String dbadminpwd = rs.getString(2);
if(AdminId.equals(dbadminid) && password.equals(dbadminpwd))
{
HttpSession session = request.getSession(true);
session.setAttribute("userid",dbadminid);
stfound = true;
break;
}
}
if(stfound){
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher ( "/meeting_Id.jsp" ) ;
dispatcher.forward ( request, response ) ;
}
}
else{
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher ( "/index.jsp" ) ;
dispatcher.forward ( request, response ) ;
}
}
if(button.equals("Next"))
{
HttpSession session = request.getSession(true);
String AID =(String) session.getAttribute("aid");
int meetingid = Integer.parseInt(request.getParameter("meeting_id"));
/*String CNM= request.getParameter("CNM");
int CCD = Integer.parseInt(request.getParameter("CCD"));
int CCDD= Integer.parseInt(request.getParameter("CCDD"));
int PID= Integer.parseInt(request.getParameter("PID"));
int STFID=Integer.parseInt(AID);*/
meeting obj=new meeting();
obj.addmeeting(meetingid);
System.out.print("Sadia");
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher ( "/creat_date.jsp" ) ;
dispatcher.forward ( request, response ) ;
}
}catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
and Meeting.java is
package classes;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Statement;
public class meeting {
private int meeting_id;
Connection con=null;
Statement smt = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public meeting()throws ClassNotFoundException//construtor
, SQLException{
// try{
String url = "jdbc:mysql://localhost/meeting_planner";
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, "admin", "admin");
smt = con.createStatement();
//}catch(ClassNotFoundException e1){
//e1.printStackTrace();
}
public void addmeeting(int meeting_id1)throws ClassNotFoundException // from attribute web.xml
, SQLException{
System.out.println("------TRY INSERTION------");
String query = "SELECT meeting_Id FROM meeting";
ResultSet rs = smt.executeQuery(query);
int numCols = rs.getMetaData().getColumnCount()+1;
// STAFF_ID=numCols+1;
String query1 = "INSERT INTO Meeting VALUE ( "+meeting_id+")";
System.out.println(query1);
smt.executeUpdate(query1);
}
}
the name of Next button is "next"
when i print the value of next in this line System.out.println("next"+next);
it print null for next parameter
** EDIT: The problem with NullPointerException was resolved, but now a NumberFormatException is thrown **
Console is like this
start
reached controller
inside if
111 sadia sadia
111 sadia sadia
SELECT AId,Password FROM administrator
start
reached controller
Oct 29, 2014 6:44:57 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [classes.MainController] in context with path [/Meeting1] threw
exception
java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at classes.MainController.doPost(MainController.java:141)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
The index.jsp is
<form method = "post" name="create" action="MainController">
<label for="author">Enter id: </label> <input type="text"
id="AId" name="AId" required="required" />
<div class="cleaner_h10"></div>
<label for="author">Enter_password: </label><input
type="password" name="Password" required="required" />
<div class="cleaner_h10"></div>
<br> <input type="submit"
name="button" " value="login"
style="height: 30px; width: 70px"></a>
</input>
</form>
The meeting_Id.jsp is
<form method="post" name="create" action="MainController">
<label for="author">Enter Meeting Id:</label> <input type="text" id="meeting_id" name="mid" required="required" />
<div class="cleaner_h10"></div>
<div class="cleaner_h10"></div><br>
<input type="submit" name="cancelbutton" value="Cancel" style="height:30px; width:70px">
</input>
<input type="submit" name="button" value="Next" style="height:30px; width:70px">
</input>
</form>
Solution for the original NullPointerException problem
The problem is in here:
//System.out.println("connection");
String button=request.getParameter("button");
System.out.println(button + request.getParameter("AId"));
if(button.equals("login"))
As you can see from your own debug printing, both button and the parameter AId that you print are null.
Therefore, when you try to call button.equals("login") you get a NullPointerException. That's because you can't call a method on a null.
You should always check if your parameters are null before using them. Even if you think that they should never be null - because hackers can try to send stuff to your servlet without the control of your form.
Here is what happens, step by step.
You display index.jsp. You click the button.
MainController runs. Since there is a button parameter that came from index.jsp, everything is OK, and it reaches the code at the end that forwards it into the meeting_Id.jsp which is now displayed on your browser.
You now click the button and send the form in the meeting_Id.jsp back to MainController.
Now, in this invocation, there is no parameter button. Therefore you get the NullPointerException.
You are working in an MVC environment. Every form is sent to the same controller, MainContoller, and MainController is supposed to be smart enough to know which form sent it the request, and handle it accordingly. But yours assumes only index.jsp is calling it. But it doesn't work like this. When you click the next button on meeting_Id.jspa, you are creating a new request, which goes to the same MainController servlet, and causes the error.
You should make sure your forms send some sort of ID that tells MainController which form is using it at the moment, and then the controller can send the request to be processed by the appropriate model. The input you use this for should have the same name and should exist in all the forms you are sending.
Solution for the NumberFormatException
Now you have a similar issue for a different reason. In this line:
int meetingid = Integer.parseInt(request.getParameter("meeting_id"));
You are trying to parse a parameter called meeting_id. The problem is that, again, you are not checking for nulls. You don't actually have such a parameter.
Why? Because this is what your HTML (in meeting_Id.jsp) says:
<input type="text" id="meeting_id" name="mid" required="required" />
As you can see, "meeting_id" is its id, not its name, and getParameter() always works with the input's name.
Beyond that, after you fix this, you must either make sure (with a regex) that the parameter has only numbers in it, or you have to catch NumberFormatException using a try-catch block around the parseInt line.
Always, always, check the parameters that you get from the user. Never assume that they exist, that they are not null, or that they have the values you expect them to have.

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