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.
Related
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.
I need to logout from dahboard.jsp and go to index.jsp but while I'm clicking the logout button it is showing the error message like this,
HTTP Status 404 - /Project/logout
type Status report
message /Project/logout
description The requested resource (/Project/logout) is not available.
Apache Tomcat/6.0.20
the dashboard.jsp and the servlets login and logout are posted below, what might be the error in that.
dashboard.jsp
<div class="ends">
<form action="logout" method="post" >
<input type="submit" value="logout">
</form>
</div>
servlet page login login.java
package com.signin;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import com.db.DBCon;
/**
* Servlet implementation class login
*/
public class login extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uid=request.getParameter("uid");
String pwd=request.getParameter("pwd");
try {
DBCon dbc = new DBCon();
if(dbc.validateLogin(uid, pwd))
{
HttpSession session=request.getSession();
session.setAttribute("userid",uid);
response.sendRedirect("dashboard.jsp");
}
else
out.println("<center><h3>Sign in Failed!</h3><br><a href='index.jsp'>Go to Sign up page</a></center>");
dbc.closeCon();
}
catch(Exception e){ e.printStackTrace(); }
}
}
logout.java
package com.signin;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class logout
*/
public class logout extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session=request.getSession();
session.removeAttribute("userid");
session.invalidate();
response.sendRedirect("index.jsp");
}
}
Check your web.xml file whether you map your logout class correctly. The issue may be there. Otherwise share the full error description and web.
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.
I have a login web application.
Whenever I login, the request must be validated by validate Servlet and it must be forwarded to admin.jsp
Everything is fine except I got this exception java.lang.IllegalStateException.
Code:
package com.suraj.technepbankapplication;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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;
/**
*
* #author Suraj Gautam
*/
#WebServlet(name = "validate", urlPatterns = {"/validate"})
public class validate extends HttpServlet {
DataBean bean = new DataBean();
int count = 0;
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//the form inputted is sent to the Databean Class
settingValue(req.getParameter("userid"), req.getParameter("password"));
try {
if (!isValid(req, resp)) {
req.getRequestDispatcher("/index.jsp").forward(req, resp);
} else if (bean.getUserId().equals("admin")) {
req.getRequestDispatcher("/admin.jsp").forward(req, resp);
} else {
req.getRequestDispatcher("/afterlogin.jsp").forward(req, resp);
}
} catch (SQLException | ClassNotFoundException ex) {
System.out.println(ex.getMessage());
}
}
public boolean isValid(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, ClassNotFoundException {
String userId = req.getParameter("userid");
String password = req.getParameter("password");
if (userId.length() <4 || password.length() < 4) {
return false;
} else {
return loginValidate(req, resp);
}
}
//setting DataBean class Value
public void settingValue(String userid, String password) {
bean.setUserId(userid);
bean.setPassword(password);
}
public boolean loginValidate(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException, ClassNotFoundException {
String url = "jdbc:mysql://localhost/technep";
String user = "root";
String password = "";
String query = "SELECT id, password FROM technep_login";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement preparedStatement = conn.prepareStatement(query);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
//working till here
if (resultSet.getString("id").trim().equals(bean.getUserId()) && resultSet.getString("password").trim()
.equals(bean.getPassword())) {
count = 1;
break;
}
}
if (count == 1) {
return true;
} else {
return false;
}
}
}
The output:
Warning: StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:777)
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:224)
at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:195)
at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:188)
at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:240)
at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:185)
at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:137)
at org.apache.jsp.DBimage_jsp._jspService(DBimage_jsp.java:93)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:111)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:411)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:473)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:377)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPoo l.java:571)
at java.lang.Thread.run(Thread.java:745)
Sorry, this question is unanswerable based on the stacktrace you give: The servlet does not even appear in the stacktrace, so either this servlet can't be the problem or you're omitting the "root cause" stacktrace.
Further, there are a lot more problems with your code and you should really go through a basic tutorial for servlet development. These can't be corrected in a single answer on stackoverflow
The way you use bean as a member of your servlet will result in disaster (race condition). You must not have member variables (state) in a servlet.
You're taking care of authentication yourself - you clearly shouldn't do this, it's a well solved problem
On top, you're obviously storing clear text passwords in the database and you're always enumerating the whole user database instead of just fetching a single value (imagine to have many users...)
From this code I'm assuming that one can also skip the validation by just going to /afterlogin.jsp or /admin.jsp manually.
The parameters to your methods are arguable as well and create a hard to maintain implementation.
This is an incomplete list.
I want to execute an SQL query in JSP. The display must be in JSP code, not in java.
I cannot introduce JSP code in a java page.
package tn.com.tradenet.utilisateur;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Modification extends HttpServlet
{
public void doPost()
{
try
{
String id ="1"; //request.getParameter("userName");
String nom ="mecchlaoui"; //request.getParameter("userName");
String prenom ="fawzia"; //request.getParameter("userName");
String email ="hotmail"; //request.getParameter("password");
String profil ="fawzia"; //request.getParameter("password");
String login ="fawzia"; //request.getParameter("password");
String pass ="1258"; //request.getParameter("password");
ConnectionBD mod = new ConnectionBD();
//String sql="SELECT id FROM utilisateur";
//ResultSet res=mod.execMonSQl(sql);
//while (res.next())
//{
//id = res.getString(1);
//}
mod.execMonUpdate("UPDATE utilisateur SET nom='"+nom+"',prenom='"+prenom+"', email='"+email+"', profil='"+profil+"',login='"+login+"',pass='"+pass+"' WHERE 'id'='"+id+"'");
System.out.println("element ajoutté");}
catch(SQLException s)
{
System.out.println("erreur" +s);
}
}
public static void main(String[] args) {
Modification mdf =new Modification();
mdf.doPost();
}
}
You need to override the real HttpServlet#doPost() method, not to add another one which won't be invoked by the servletcontainer.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Do your job here.
}
And you need to map this servlet in web.xml on a known URL pattern.
<servlet>
<servlet-name>modification</servlet-name>
<servlet-class>com.example.Modification</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>modification</servlet-name>
<url-pattern>/modification</url-pattern>
</servlet-mapping>
With the above <url-pattern> the servlet will listen on URL http://example.com/context/modification.
Finally change the HTML form action URL in your JSP so that it matches the servlet URL.
<form action="modification" method="post">
See also:
Servlets tag info page - How servlets work and a little Hello World
Unrelated to the concrete question/problem, note that you still need to change your servlet code to display some result page in flavor of a JSP. E.g.
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
Also, the main() method inside the servlet makes no sense, remove it. Last but not least, your SQL approach is sensitive to SQL injection attacks. Learn PreparedStatement.