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.
Related
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);
This question already has answers here:
MySQL ERROR 1045 (28000): Access denied for user 'bill'#'localhost' (using password: YES)
(43 answers)
java.sql.SQLException: Access denied for user 'root'#'localhost' (using password: YES)
(1 answer)
Closed 5 years ago.
i am a beginner.when i use hibernate in eclipse,it shows :
ERROR: Access denied for user 'root '#'localhost' (using password:
YES) org.hibernate.exception.GenericJDBCException: Could not open
connection
i am a beginner.please help me,i don't konw what's wrong,and i counld not find a suitable answer throught the Internet or other answers on the stack overflow for my project.
Screenshot:
here is my code:
hibernate.properties:
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://127.0.0.1:3306/db_test
hibernate.connection.username = root
hibernate.connection.password = root
hibernate.show_sql=true
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 映射文件 -->
<mapping resource="product/Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Product.java:
package product;
public class Product {
private int id;
private String name;
private Double price;
private String factory;
private String remark;
public int getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public String getFactory() {
return factory;
}
public void setFactory(String factory) {
this.factory = factory;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
}
Product.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="product.Product" table="product">
<id name="id" column="id" type="int">
<generator class="native"/>
</id>
<property name="name" type="string" length="16">
<column name="name"/>
</property>
<property name="price" type="double">
<column name="price"/>
</property>
<property name="factory" type="string" length="25">
<column name="factory"/>
</property>
<property name="remark" type="string" length="60">
<column name="remark"/>
</property>
</class>
</hibernate-mapping>
HibernateUtil.java:
package com.wgh.hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtil {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal <Session>();
private static SessionFactory sessionFactory = null; //SessionFactory对象
//静态块
static {
try {
Configuration cfg = new Configuration().configure(); //加载Hibernate配置文件
sessionFactory = cfg.buildSessionFactory(new ServiceRegistryBuilder().buildServiceRegistry());
} catch (Exception e) {
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}
/**
* 获取Session
* #return Session
* #throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
/**
* 重建会话工厂
*/
public static void rebuildSessionFactory() {
try {
Configuration cfg = new Configuration().configure(); //加载Hibernate配置文件
sessionFactory = cfg.buildSessionFactory(new ServiceRegistryBuilder().buildServiceRegistry());
} catch (Exception e) {
System.err.println("创建会话工厂失败");
e.printStackTrace();
}
}
/**
* 获取SessionFactory对象
* #return SessionFactory对象
*/
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* 关闭Session
* #throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close(); //关闭Session
}
}
}
servlet: QueryEmployee.java:
package servlet;
import java.io.IOException;
import product.*;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
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.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import com.wgh.hibernate.HibernateUtil;
/**
* Servlet implementation class QueryEmployee
*/
#WebServlet("/QueryEmployee")
public class QueryEmployee extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public QueryEmployee() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request,response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
#SuppressWarnings({ "unchecked" })
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
List<Product> product_list = new ArrayList<Product>();//实例化List信息集合
Session session = null;// 实例化session对象
try {
session = HibernateUtil.getSession();// 获得session对象
String hql = "from Product";// 查询HQL语句
Query q = session.createQuery(hql);// 执行查询操作
product_list = q.list();//将返回的对象转化为List集合
} catch (HibernateException e) {
e.printStackTrace();
} finally {
HibernateUtil.closeSession();// 关闭session
}
request.setAttribute("product_list", product_list);
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
}
index.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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=UTF-8">
<title>Insert title here</title>
<style type="text/css">
table {
border-left:5px solid #ffffff;
border-collapse: collapse;
}
td {
font: normal 12px/ 17px Arial;
padding: 2px;
}
th {
font: bold 12px/ 17px Arial;
padding: 4px;
border-bottom: 1px solid #333;
}
body {
font-size: 14px;
}
#main{
width:500px;
border:solid 1px #000000;
}
</style>
</head>
<body>
<div id="main">
<table>
<tr>
<th width="30px">编号</th>
<th width="30px">书名</th>
<th width="30px" align="center">价格</th>
<th width="80px">生产商</th>
<th width="135px">备注</th>
</tr>
<c:forEach items="${product_list}" var="list">
<tr>
<td align="center">${list.id}</td>
<td>${list.name}</td>
<td>${list.price}</td>
<td>${list.factory}</td>
<td>${list.remark}</td>
</tr>
</c:forEach>
</table>
<form action="QueryEmployee" method="post">
<input type="submit" value="查看" >
</form>
</div>
</body>
</html>
here is the whole error message:
org.hibernate.exception.GenericJDBCException: Could not open connection
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler.extractPhysicalConnection(ConnectionProxyHandler.java:82)
at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler.continueInvocation(ConnectionProxyHandler.java:138)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy8.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:147)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:166)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:145)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1711)
at org.hibernate.loader.Loader.doQuery(Loader.java:828)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
at org.hibernate.loader.Loader.doList(Loader.java:2438)
at org.hibernate.loader.Loader.doList(Loader.java:2424)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2254)
at org.hibernate.loader.Loader.list(Loader.java:2249)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1248)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at servlet.QueryEmployee.doPost(QueryEmployee.java:59)
at servlet.QueryEmployee.doGet(QueryEmployee.java:41)
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:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
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:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457)
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)
Caused by: java.sql.SQLException: Access denied for user 'root '#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:951)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1717)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1276)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2395)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2428)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2213)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:797)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
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:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:193)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:281)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
... 46 more
九月 16, 2017 9:24:26 上午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1045, SQLState: 28000
九月 16, 2017 9:24:26 上午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Access denied for user 'root '#'localhost' (using password: YES)
org.hibernate.exception.GenericJDBCException: Could not open connection
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:304)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:169)
at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler.extractPhysicalConnection(ConnectionProxyHandler.java:82)
at org.hibernate.engine.jdbc.internal.proxy.ConnectionProxyHandler.continueInvocation(ConnectionProxyHandler.java:138)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy8.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:147)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:166)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:145)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1711)
at org.hibernate.loader.Loader.doQuery(Loader.java:828)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:289)
at org.hibernate.loader.Loader.doList(Loader.java:2438)
at org.hibernate.loader.Loader.doList(Loader.java:2424)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2254)
at org.hibernate.loader.Loader.list(Loader.java:2249)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1248)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at servlet.QueryEmployee.doPost(QueryEmployee.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
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:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:80)
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:799)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1457)
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)
Caused by: java.sql.SQLException: Access denied for user 'root '#'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:951)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1717)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1276)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2395)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2428)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2213)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:797)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
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:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:389)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:305)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:193)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:281)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:297)
... 45 more
九月 16, 2017 9:27:26 上午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/my_hibernate] has started
九月 16, 2017 9:27:26 上午 org.apache.catalina.loader.WebappClassLoaderBase clearReferencesJdbc
警告: The web application [my_hibernate] registered the JDBC driver [com.mysql.jdbc.Driver] but failed to unregister it when the web application was stopped. To prevent a memory leak, the JDBC Driver has been forcibly unregistered.
九月 16, 2017 9:27:27 上午 org.apache.jasper.servlet.TldScanner scanJars
信息: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
九月 16, 2017 9:27:27 上午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/my_hibernate] is completed
You don't have mysql server running or your mysql server does not have username=root or password=root, or you do not have access from the host that hibernate is running.
Check your mysql server's user accounts for 'root'.
I have run into a problem that I have been trying to figure out for days:
I added my driver: mysql-connector-java-5.1.40.jar to build path.
web-inf lib folder, apache tomcat lib folder. And also I have it in web app libaries.
However when I just run a main class and run it works, it is something to do with the web app?
This is my code:
This is the servlet class, that I use to connect to my database
package sql;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class RegisterServlet
*/
#WebServlet("/register")
public class RegisterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private DbUtil sql = new DbUtil();
/**
* #see HttpServlet#HttpServlet()
*/
public RegisterServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
String username = request.getParameter("username");
String password = request.getParameter("password");
if (sql.addToAccountToDatabase(username, password, email)) {
System.out.println("Gongratz");
} else {
System.out.println("mhhh ?");
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
}
this is the second class how i make connection
package sql;
import java.sql.*;
public class DbUtil {
public Connection getConnection() {
Connection connect = null;
try {
String url = "jdbc:mysql://hidden:3306/hidden";
connect = DriverManager.getConnection(url, "hidden", "hidden");
return connect;
} catch (Exception e) {
System.out.println("Cannot connect to database");
e.printStackTrace();
}
return connect;
}
public boolean addToAccountToDatabase(String username, String password, String email) {
try {
String query = "INSERT INTO Account (username, password, email) VALUES (?, ?,?)";
PreparedStatement pStat = getConnection().prepareStatement(query);
pStat.setString(1, username);
pStat.setString(2, password);
pStat.setString(3, email);
pStat.executeUpdate();
return true;
} catch (Exception e) {
System.out.println("User already exists");
e.printStackTrace();
return false;
}
}
}
And I get this error:
Cannot connect to database
java.sql.SQLException: No suitable driver found for jdbc:mysql://192.185.227.214:3306/ratekas9_illegalminds
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at sql.DbUtil.getConnection(DbUtil.java:15)
at sql.DbUtil.addToAccountToDatabase(DbUtil.java:34)
at sql.RegisterServlet.doPost(RegisterServlet.java:40)
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:53)
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:199)
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:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
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)
User already exists
java.lang.NullPointerException
at sql.DbUtil.addToAccountToDatabase(DbUtil.java:34)
at sql.RegisterServlet.doPost(RegisterServlet.java:40)
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:53)
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:199)
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:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
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)
mhhh ?
Because the String "jdbc:mysql" doesn't declare the driver Class itself, but only the name registered by a potential driver. You have to force the JVM to load the Driver class with a :
Class.forName("com.mysql.jdbc.Driver").newInstance();
before starting the JDBC connection.
You need 3 steps to solve your problem:
Add this code before connection Class.forName("com.mysql.jdbc.Driver");
Add 'JConnector.jar' into your project and build path.
Don't try enter same person because there is error in stack trace "User all ready exist ".
Adding the JAR file into your CLASSPATH (for compilation needs) / project's BUILDPATH and also under your project's WEB-INF/lib folder (for runtime references, i.e., when you deploy your application to an application server). For further reference, please go through this link
Class.forName("com.mysql.jdbc.Driver");
This is no longer required as per Official Java documentation here, but it is a mandatory step if you are using prior versions of JDBC 4.0.
This question can provide you lot many details on this regards.
Hope all these details help you resolve your issue!
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 (?, ?, ?, ?)
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.