import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
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 com.mysql.jdbc.PreparedStatement;
/**
* Servlet implementation class Login
*/
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
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
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
Connection conn = null;
String url="jdbc:mysql://localhost:3306/";
String dbName="Tamir";
String driver="com.mysql.jdbc.Driver";
try{
request.setAttribute("message", "");
String nick = request.getParameter("check_name");
String password = request.getParameter("check_password");
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,"root", "tamir");
//admin check
/*
java.sql.PreparedStatement st2 = conn.prepareStatement("SELECT * FROM users WHERE nickname = ? or email = ? and password = ? and admin = T");
st2.setString(1, nick);
st2.setString(2, nick);
st2.setString(3, password);
ResultSet r2=st2.executeQuery();
if(r2.next()) {
request.getSession().setAttribute("admin", nick);
}
*/
//regular check
java.sql.PreparedStatement st = conn.prepareStatement("SELECT * FROM users WHERE nickname = ? or email = ? and password = ?");
st.setString(1, nick);
st.setString(2, nick);
st.setString(3, password);
ResultSet r1=st.executeQuery();
if(r1.next()) {
request.getSession().setAttribute("user", nick);
request.getRequestDispatcher("/tf2main.jsp").forward(request, response);
} else {
request.setAttribute("message", "Username or password are incorrect.");
request.getSession().setAttribute("user", null);
request.getRequestDispatcher("/Login.jsp").forward(request, response);
}
}catch (Exception ex) {
System.out.println("Error");
}
}
}
Hello. So I've made the code above and it is working perfectly, but when I add the comment [which I really need, in order to check if he's an admin... Cruical for me] it just throws the exception for some reason.
The only other souloution I've thought about was redricting to another servlet, doing the same action somehow but that's impossible so I'm kinda stuck, you also can't use ERB.
I've tried everything and nothing works.
Edit: The error being throwed is:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'T' in 'where clause'
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:425)
at com.mysql.jdbc.Util.getInstance(Util.java:408)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2487)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1966)
at Login.doPost(Login.java:68)
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.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
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:100)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
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)
Update the query to be something like:
java.sql.PreparedStatement st2 =
conn.prepareStatement("SELECT * FROM users WHERE nickname = ? or email = ? and password = ? and admin = 'T'");
Note the single quote marks around the T in the query.
Related
Error while submitting a simple form:
package mvc.controller;
import java.io.IOException;
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 mvc.bean.PollBean;
import mvc.dao.PollDAO;
#WebServlet("/pollControll")
public class PollController extends HttpServlet {
private static final long serialVersionUID = 1L;
private PollDAO pd;
public PollController() {
pd = new PollDAO();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equalsIgnoreCase("SelectALL")) {
request.setAttribute("polls", pd.SelectAll());
}
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action.equalsIgnoreCase(("insert"))) {
PollDAO pp = new PollDAO();
PollBean p = new PollBean();
int note = Integer.parseInt(request.getParameter("note"));
String email = request.getParameter("email");
p.setNote(note);
p.setEmail(email);
pp.insert(p);
RequestDispatcher direct = request.getRequestDispatcher("/home.jsp");
direct.forward(request, response);
} else if (action.equalsIgnoreCase("ResetALL")) {
PollBean p = new PollBean();
pd.ResetALL(p);
} else if (action.equalsIgnoreCase("Activated")) {
PollBean p = new PollBean();
pd.Activated(p);
RequestDispatcher direct = request.getRequestDispatcher("/PollAdmin.jsp");
direct.forward(request, response);
} else if (action.equalsIgnoreCase("Deactivated")) {
PollBean p = new PollBean();
pd.Deactivated(p);
RequestDispatcher direct = request.getRequestDispatcher("/PollAdmin.jsp");
direct.forward(request, response);
}
doGet(request, response);
}
}
And here the Stacktrace:
Servlet.service() for servlet [mvc.controller.PollController] in context with path [/Enquete_eduCAPES] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassNotFoundException: java.time.temporal.TemporalField
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1858)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1701)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:320)
at org.postgresql.Driver.makeConnection(Driver.java:406)
at org.postgresql.Driver.connect(Driver.java:274)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at mvc.util.ConexaoDAO.getConnection(ConexaoDAO.java:29)
at mvc.dao.PollDAO.insert(PollDAO.java:40)
at mvc.controller.PollController.doPost(PollController.java:60)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:650)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
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)
What version of Java are you using?
Because according to Java specifications the time/temporal/TemporalField was introduced in version 8, below this version it will not work.
I am trying simple login authentication using servlets and jdbc connection to MySQL database. After executing it on tomcat server I am getting following error:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.leader.prog.Validate.checkUser(Validate.java:13)
at com.leader.servlet.Login1.doPost(Login1.java:42)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2466)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2455)
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)
I am sharing the content of all files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.leader.servlet.Login1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>welcome</servlet-name>
<servlet-class>com.leader.servlet.Welcome</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Home.html</welcome-file>
</welcome-file-list>
</web-app>
Login1.java
package com.leader.servlet;
import java.io.IOException;
import java.io.PrintWriter;
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 com.leader.*;
import com.leader.prog.Validate;
#WebServlet("/Login1")
public class Login1 extends HttpServlet {
/**
* #see HttpServlet#HttpServlet()
*/
public Login1() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("userName");
String pass = request.getParameter("password");
if(Validate.checkUser(user.toString(),pass.toString()))
{
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else
{
out.println("Username or Password incorrect");
RequestDispatcher rs = request.getRequestDispatcher("Home.html");
rs.include(request, response);
}
}
}
validate.java
package com.leader.prog;
import java.sql.*;
public class Validate
{
public static boolean checkUser(String user,String pass)
{
boolean st =false;
try{
//loading driver
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/person","root","password");
PreparedStatement ps =con.prepareStatement
("select * from person where pid=? and password=?");
ps.setString(1, user);
ps.setString(2, pass);
ResultSet rs =ps.executeQuery();
st = rs.next();
}catch(Exception e)
{
e.printStackTrace();
}
return st;
}
}
Please help me to get out of this issue.
Check the availability of mysql driver is in classpath. If you are using IDE(eclipse) try to add it to build path.
You should add Mysql connector library you your project buildpath
You can download library from
http://dev.mysql.com/downloads/connector/j/5.0.html
or
http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm
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.
I have been searching all around for a solution to my problem and the only solution i have found is to add the jar file that i already have. This is done in eclipse EE and is useing tomcat.
I am running a different HTML file which links to this piece of code once a button is pressed, if you want that code feel free to ask, but there is almost nothing on it.
I keep getting the error "java.lang.ClassNotFoundException: com.mysql.jdbc.driver" along with 100 other lines which i'm not sure are conencted.
Here is what i have:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
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;
/**
* Servlet implementation class HelloForm
*/
#WebServlet("/test5")
public class test5 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public test5() {
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
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.driver";
String userName = "root";
String password = "games10";
try {
Class.forName(driver).newInstance();
Connection conn = (Connection) `enter code here`DriverManager.getConnection(url+dbName,userName,password);
Statement stat = conn.createStatement();
//stat.execute("CREATE TABLE test (Name CHAR(20))");
stat.execute("INSERT INTO TEST VALUES('"+request.getParameter("first_name")+"')");
conn.close();
System.out.println("Working");
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
I apolagize if i have posted the code wrong, ive never used this site before and am tired.
As i have said i have imported the "mysql-connector-java-5.1.30-bin.jar" file. All help is accepted with open arms and critisism also.
Thank you for your time
Errors in case it's not actually related to the driver:
java.lang.ClassNotFoundException: com.mysql.jdbc.driver
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1720)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1571)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at test5.doGet(test5.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
After importing the jar, you have to add it to the build path of your project.
right click on jar file -> build path ->add to build path
You've misspelt the class name, but you don't need it. Just remove that line. It's been obsolete for years, since JDBC 4.0.
I found the problem. I needed a uppercase D in String driver = "com.mysql.jdbc.driver";
God I feel stupid now
In a previous piece of code I received the exact same error I listed in the title.
I had a username validator in my code but forgot to include the following code:
password =ESAPI.validator().getValidInput("Login password", password, "Password", 20, false);
After adding that I resolved the issue.
Now in my next java page I have run into the same problem and reviewed the code and have not been able to find what I am missing, if I am in fact missing something.
I had this same error with another piece of code I was working on and was able to resolve it as I had forgot to include another line of code.
For this piece of code however I have gone over it several times and cannot figure what is wrong with it.
Here is the code:
package com.tunestore.action;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.util.MessageResources;
import org.owasp.esapi.ESAPI;
import com.tunestore.util.IWithDataSource;
public class RegisterAction extends Action implements IWithDataSource {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaActionForm daf = (DynaActionForm)form;
ActionMessages errors = new ActionMessages();
ActionForward forward = mapping.getInputForward();
MessageResources resources = getResources(request);
//ESAPI START
if (!ESAPI.validator().isValidInput("Register username", daf.getString("username"), "SafeString", 20, false)) {
//ESAPI END
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.required", resources.getMessage("prompt.username")));
}
//ESAPI START
if (!ESAPI.validator().isValidInput("Register password", daf.getString("password"), "password", 20, false)) {
//ESAPI END
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.required", resources.getMessage("prompt.password")));
}
//ESAPI START
if (!ESAPI.validator().isValidInput("Register confirm password", daf.getString("rptpass"), "password", 20, false)) {
//ESAPI END
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.required", resources.getMessage("prompt.rpt")));
}
if ((null != daf.getString("password")) && (null != daf.getString("rptpass"))) {
if (! daf.getString("password").equals(daf.getString("rptpass"))) {
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.rptpass.nomatch"));
}
}
Connection conn = null;
try {
conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COUNT(*) USERCNT "
+ "FROM TUNEUSER "
+ "WHERE USERNAME = '"
+ daf.getString("username")
+ "'");
rs.next();
if (rs.getInt("USERCNT") > 0) {
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.user.exists"));
} else if (errors.isEmpty()) {
//ESAPI START
String sql = "INSERT INTO TUNEUSER (USERNAME,PASSWORD,BALANCE) VALUES (?, ?, ?)";
PreparedStatement pStmt = conn.prepareStatement(sql);
pStmt.setString(0, daf.getString("username"));
pStmt.setString(1, daf.getString("password"));
pStmt.setDouble(2, 0.00);
pStmt.executeUpdate();
//ESAPI END
ActionMessages msgs = getMessages(request);
msgs.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("user.added"));
forward = mapping.findForward("success");
}
} catch (Exception e) {
e.printStackTrace();
throw e;
} finally {
if (conn != null) {
try { conn.close(); } catch (Exception e) {}
}
}
request.setAttribute("ERRORS.REGISTER", errors);
return forward;
}
}
The code is for a registration form. When someone tries to register though the following error is given in return.
java.sql.SQLException: The column position '0' is out of range. The number of columns for this ResultSet is '3'.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.ColumnMetaData.getColumnType(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.setString(Unknown Source)
at org.apache.commons.dbcp.DelegatingPreparedStatement.setString(DelegatingPreparedStatement.java:132)
at com.tunestore.action.RegisterAction.execute(RegisterAction.java:90)
at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:110)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.tunestore.servlet.PersistenceFilter.doFilter(PersistenceFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:244)
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.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.apache.derby.client.am.SqlException: The column position '0' is out of range. The number of columns for this ResultSet is '3'.
at org.apache.derby.client.am.ColumnMetaData.checkForValidColumnIndex(Unknown Source)
... 34 more
ROOT CAUSE
org.apache.derby.client.am.SqlException: The column position '0' is out of range. The number of columns for this ResultSet is '3'.
at org.apache.derby.client.am.ColumnMetaData.checkForValidColumnIndex(Unknown Source)
at org.apache.derby.client.am.ColumnMetaData.getColumnType(Unknown Source)
at org.apache.derby.client.am.PreparedStatement.setString(Unknown Source)
at org.apache.commons.dbcp.DelegatingPreparedStatement.setString(DelegatingPreparedStatement.java:132)
at com.tunestore.action.RegisterAction.execute(RegisterAction.java:90)
at org.springframework.web.struts.DelegatingActionProxy.execute(DelegatingActionProxy.java:110)
at org.apache.struts.chain.commands.servlet.ExecuteAction.execute(ExecuteAction.java:58)
at org.apache.struts.chain.commands.AbstractExecuteAction.execute(AbstractExecuteAction.java:67)
at org.apache.struts.chain.commands.ActionCommandBase.execute(ActionCommandBase.java:51)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.commons.chain.generic.LookupCommand.execute(LookupCommand.java:304)
at org.apache.commons.chain.impl.ChainBase.execute(ChainBase.java:190)
at org.apache.struts.chain.ComposableRequestProcessor.process(ComposableRequestProcessor.java:283)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1913)
at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:462)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:306)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.tunestore.servlet.PersistenceFilter.doFilter(PersistenceFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:244)
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.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:281)
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 error appears to be pointing to line 90 of my code which is:
pStmt.setString(0, daf.getString("username"));
Yet this line of code looks correct to me. What could I be missing?
Column indexes start at 1 in JDBC
I can't see you calling setString in the code, but the stack trace clearly says execute is calling setString at line #90. Is the code you posted exactly what's running when you get this exception?