Servlet is not working - java

Hey for some reason my sql statement will not work, im trying to delete a product by its id but it just wont happen, any suggestion? the id is an integer and i think its not working because my input type is text and i have it stored as String n.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Admin extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("productid");
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/contact","nbuser", "nbuser");
String query = "delete from product where id = " + n +"";
PreparedStatement stmt;
stmt = con.prepareStatement(query);
stmt.setString(1, n);
int i = stmt.executeUpdate();
if (i > 0) {
response.sendRedirect("index.html");
}else{
response.sendRedirect("Admin.jsp");
}
} catch (ClassNotFoundException | SQLException ey) {
System.out.println(ey);
}
out.close();
}

try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/contact","nbuser", "nbuser");
String query = "delete from product where id = ?";
PreparedStatement stmt;
stmt = con.prepareStatement(query);
stmt.setInt(1, Integer.parseInt(n));
int i = stmt.executeUpdate();
if (i > 0) {
response.sendRedirect("index.html");
}else{
response.sendRedirect("Admin.jsp");
}
}
make above 2 changes.

try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/contact","nbuser", "nbuser");
String query = "delete from product where id = " + n +"";
Statement stmt=con.createStatement();
int i = stmt.executeUpdate(query);
if (i > 0) {
response.sendRedirect("index.html");
}else{
response.sendRedirect("Admin.jsp");
}
} catch (ClassNotFoundException | SQLException ey) {
System.out.println(ey);
}
please try this code,it should works fine

Problem in your code is that product id is Integer type in database but u have set it as String
in your code stmt.setString(1, n); it should be changed to stmt.setInt(1, n) and query format should be like this String query = "delete from product where id = ?";.here is the code for deleting product from database using productId.
String query = "delete from product where id = ?";
PreparedStatement stmt;
stmt = con.prepareStatement(query);
stmt.setString(1, n);
just replace this code it will work...

Found two issues in your code:
You didn't properly set the parameters in the PreparedStatement call.
You didn't close the statement and connection.
Try this:
public class Admin extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("productid");
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/contact","nbuser", "nbuser");
String query = "delete from product where id = ?";
PreparedStatement stmt;
stmt = con.prepareStatement(query);
stmt.setString(1, n);
int i = stmt.executeUpdate();
if (i > 0) {
response.sendRedirect("index.html");
}else{
response.sendRedirect("Admin.jsp");
}
}
catch (ClassNotFoundException | SQLException ey) {
System.out.println(ey);
}
finally{
stmt.close();
con.close();
}
}

Since the field is a text type, it needs surrounding quotes - that's why that didnt work. Calling setString didnt have any effect as there's no placeholder to accept the id value.
Solution: Add a PreparedStatement placeholder:
String query = "delete from product where id = ?";
This approach protects against SQL Injection attacks whereas String concatenation does not.

Related

How to fix 'java.lang.ClassNotFoundException: com.mysql.jdbc.Driver' after adding it to the build path and registered using Class.forName();

I had added mysql-connector-java-8.0.12.jar from build path in Eclipse Jee. I
had also registered that class by adding :
Class.forName("com.mysql.jdbc.Driver");
but still it is giving me this error :
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
This is the code of Student.java Servlet.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
public class Student extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
// business logic
response.setContentType("text/html");
PrintWriter out=response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sem5", "root", "root");
String sql = "insert into p4 values(?,?,?,?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
String enroll = request.getParameter("enroll");
String username = request.getParameter("username");
String password = request.getParameter("password");
String gender = request.getParameter("gender");
String email = request.getParameter("email");
String mobile = request.getParameter("mobile");
String address = request.getParameter("address");
ps.setString(1, enroll.toString());
ps.setString(2, username.toString());
ps.setString(3, password.toString());
ps.setString(4, gender.toString());
ps.setString(5, email.toString());
ps.setString(6, mobile.toString());
ps.setString(3, address.toString());
ps.executeUpdate();
ps.close();
}
catch(Exception ex) {
System.out.println("Exception : "+ ex);
out.println("Error");
}
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException
{
doGet(request,response);
}
}
Thanks in advance...
You need to use com.mysql.cj.jdbc.Driver instead of com.mysql.jdbc.Driver while using MySQL connector 8. Please refer the documentation here.

ClassNotFoundException in Apache Tomcat 8.5.14 [duplicate]

This question already has answers here:
java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Error [duplicate]
(2 answers)
Connect Java to a MySQL database
(14 answers)
Closed 4 years ago.
This is my simple code to test connectivity with MySQL :
import java.sql.*;
import java.util.*;
public class PreparedStatementTest {
public static void main(String[] args) throws Exception {
String[] str = {"ram", "shyam", "radhe", "lakhan"};
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:shubh", "sa", "shubham");
PreparedStatement ps = con.prepareStatement("insert into shubham_table values(?,?)");
for (int i = 0; i < 4; i++) {
ps.setInt(1, i);
ps.setString(2, str[i]);
ps.executeUpdate();
}
PreparedStatement prs = con.prepareStatement("select *from shubham_table where id=?");
for (int i = 0; i < 4; i++) {
prs.setInt(1, i);
ResultSet rs = prs.executeQuery();
while (rs.next()) {
System.out.print("id = " + rs.getInt(1));
System.out.println("name = " + rs.getString(2));
}
}
rs.close();
prs.close();
ps.close();
con.close();
}
}
This code is working properly and updating my already existing table in database but when I try to create a connection in my web app on Apache it throws ClassNotFoundException. The source code in my application is
import javax.servlet.*;
import java.io.*;
import java.sql.*;
import java.util.*;
public class RegFormServlet implements Servlet {
public void init(ServletConfig sc) throws ServletException {
System.out.println("created");
}
public ServletConfig getServletConfig() {
return null;
}
public void service(ServletRequest req, ServletResponse res) throws
ServletException, IOException {
System.out.println("before con mysql");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:shubh", "sa", "shubham");
String name = req.getParameter("name");
String email = req.getParameter("email");
String address = req.getParameter("address");
Statement st = con.createStatement();
String ddl =
"create table shubham_table3 (name varchar(30),e-mail
varchar(20)
,address varchar
(100))";
st.execute(ddl);
PreparedStatement ps = con.prepareStatement(
"insert into shubham_table
values( ?, ?, ?)
");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, address);
PrintWriter out = res.getWriter();
out.println("You Are Registered Successfully yeah!!!!");
st.close();
ps.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
public String getServletInfo() {
return null;
}
public void destroy() {
}
}
How can I fix this?
You are using Type1 jdbc driver to connect to Mysql database. Please check Tomcat and its jdk version. From Jdk8 onwards Type1 driver is not allowed to use.
Alternatively you can use Mysql Type4 driver to do operation. Here is link
Once downloaded mysql connector driver add it to /WEB-INF/lib folder.
Hopefully It should solve issue.

How to handle if a sql query finds nothing? Using resultset in java

I have found a few answers to this question on this site, but haven't been able to apply it correctly. I'm trying to take a user's input for user name and password and check it against a database to see if its correct. Everything works fine unless the username entered is not in the database. In that case the query doesn't find any rows. I'm doing this with derby in netbeans. So I think I'm just having trouble detecting when the query is sent with an unknown username. Any Suggestions?
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "MyServlet", urlPatterns ={"/echo"})
public class LoginAction extends HttpServlet {
private ResultSet resultSet;
private Connection con;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
try {
out.println("<!DOCTYPE html>");
out.println("<html><head>");
out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
String userName = request.getParameter("username");
String password = request.getParameter("password");
if (userName.length()>0 & password.length()>0){
try{
String url = "jdbc:derby:c:/users/project/.netbeans-derby/";
String db = "loginpass";
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
String user = "user";
String pass = "pass";
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
String statement = "SELECT PASSWORD FROM LOGINPASS WHERE LOGIN = '"+userName+"'";
PreparedStatement prepStatement = con.prepareStatement(statement);
resultSet = prepStatement.executeQuery();
while (resultSet.next()){
if (resultSet.getString("password").equals(password)){
out.println("Login attempt successful!");
out.println("<br><a href='index.jsp'>Back to Login Page</a>");
} else {
out.println("Password incorrect");
out.println("<br><a href='index.jsp'>Back to Login Page</a>");
}
}
con.close();
}catch(Exception e){
out.println("caught...");
e.printStackTrace();
}
} else {
out.println("Login attempt failed");
out.println("<a href='index.jsp'>Back to Login Page</a>");
}
} finally {
out.close();
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
As you expect only one row, you may write:
if (resultSet.next()) {
if (resultSet.getString("password").equals(password)){
out.println("Login attempt successful!");
out.println("<br><a href='index.jsp'>Back to Login Page</a>");
} else {
out.println("Password incorrect");
out.println("<br><a href='index.jsp'>Back to Login Page</a>");
}
} else {
out.println("User doesn't exist");
out.println("<br><a href='index.jsp'>Back to Login Page</a>");
}
And you'd better use parameters to avoid sql injections:
String statement = "SELECT PASSWORD FROM LOGINPASS WHERE LOGIN = ?";
PreparedStatement prepStatement = con.prepareStatement(statement);
prepStatement.setString(1, userName);
resultSet = prepStatement.executeQuery();
Before While(resultSet.next()), type if(resultSet!=null).If the query has no result, the resultSet will be null.
You can check that from the ResultSet object itself . ResultSet#isBeforeFirst() :
Retrieves whether the cursor is before the first row in this ResultSet object.
Note: Support for the isBeforeFirst method is optional for ResultSets with a result set type of TYPE_FORWARD_ONLY
Returns:
true if the cursor is before the first row; false if the cursor is at any other position or the result set contains no rows.
if (!resultSet.isBeforeFirst()) {
out.println("no rows fetched");
out.println("User with this password not found");
out.println("<br><a href='index.jsp'>Back to Login Page</a>");
}

Class Not found exception in servlet connecting mysql

I was trying to connect mysql database in my servlet. Then I'm getting an exception.But when I am testing the database connection from a usual Java class the connection is ok and I getting the data from the database.The exception I'm getting on tomcat server console is:
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver .
The code of my DatabaseHandler.java is:
import java.sql.*;
public class DatabaseHandler {
private Statement stmt;
private Connection con;
String username = "root";
String password = "thunder";
String dbname = "bidderboy";
public DatabaseHandler()
{
this.createConnection();
}
private void createConnection()
{
//create the connection for first time
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/"+dbname , username , password);
stmt = con.createStatement();
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
public int executeUpdate(String sql)
{
int result = 0;
//before update checks if connection is open
try {
if(con.isClosed()) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost/"+dbname , username , password);
stmt = con.createStatement();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
//try to executeUpdate the sql command
try{
result = stmt.executeUpdate(sql);
}
catch(Exception ex){
System.out.println("Couldn't executeUpdate sql command");
}
return result;
}
public ResultSet executeQuery(String sql)
{
ResultSet rs = null;
//before Query checks if connection is open
try {
if(con.isClosed()) {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+dbname , username , password);
stmt = con.createStatement();
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
//try to executeQuery the sql command
try{
rs = stmt.executeQuery(sql);
}
catch(Exception ex){
System.out.println("Couldn't executeQuery sql command");
}
return rs;
}
public void closeConnection()
{
//if connection is open try to close the connection
try {
if(!con.isClosed()) {
con.close();
}
} catch (SQLException ex) {
System.out.println("Failed to close database connection");
}
}
}
The code of my servlet is:
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#SuppressWarnings("serial")
public class UserLogin extends HttpServlet{
public UserLogin()
{
}
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.doPost(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
DatabaseHandler dbh = new DatabaseHandler();
String username="mamun";
String password="1234";
String dbusername="";
String dbpassword="";
String sql = "select * from users where username='"+username+"' and password='"+password+"'";
ResultSet rs = dbh.executeQuery(sql);
try {
while(rs.next())
{
dbusername = rs.getNString(1);
dbpassword = rs.getNString(2);
}
} catch (SQLException e) {}
System.out.println(dbusername+" "+dbpassword);
}
}
And the Code of normal java class from which I'm getting my data is:
import java.sql.ResultSet;
import java.sql.SQLException;
public class DatabaseConnectionTest {
public static void main(String[] args) {
String sql = "Select * from users";
DatabaseHandler dbh = new DatabaseHandler();
ResultSet rs = dbh.executeQuery(sql);
try {
while(rs.next())
{
String n = rs.getNString(1);
String c = rs.getNString(2);
System.out.println("Name: "+n+" Contact: "+c);
}
} catch (SQLException ex) {
System.out.println(ex.toString());
}
}
}
Anybody please explain why I'm getting this class not found exception and What can be the solution. Thanks in advance.
Adding mysql-connector-java-5.1.11-bin.jar file to WEB-INF/lib folder fixed my problem.

servlet request.getParameter cannot be resolved

The following is a servlet for getting parameter from a jsp page.
I am trying to run following code --
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.swing.JFrame;
public class oneServlet extends HttpServlet {
public static Connection getConnection() throws Exception {
String driver = "org.postgresql.Driver";
String url = "jdbc:postgresql://10.1.11.112:5432/pack";
String username = "pack";
String password = "pack";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
return conn;
}
public static void main(String[] args) throws Exception {
String user=request.getParameter("t1");
String pass=request.getParameter("t2");
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String queryTest = "select username,password from login";
pstmt = conn.prepareStatement(queryTest);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && pass.equals(password))
{
JFrame frame = new JFrame("/LoginSuccess.jsp");
}
else
{
System.out.println("Login Failed,Please try Againe");
}
}}
catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
}
}
It's showing error in request.getParameter that " request cannot be resolved. Can anyone help me resolve this.
When you extends HttpServlet, you need to override doGet and doPost() which take HttpServletRequest and HttpServletResponse as parameters.
Example:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
.......
String user=request.getParameter("t1"); //Use request variable to do get...
}
Read more here and here
Servlets doesnt have main() , they are executed by SelvletContainer or Webserver (like tomcat)
In your scenario.
public void doGet(){
String user=request.getParameter("t1");
String pass=request.getParameter("t2");
Connection conn = null;
PreparedStatement pstmt = null;
try {
conn = getConnection();
String queryTest = "select username,password from login";
pstmt = conn.prepareStatement(queryTest);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && pass.equals(password))
{
//JFrame frame = new JFrame("/LoginSuccess.jsp");
request.getRequestDispatcher().redirect("/LoginSuccess.jsp");
}
else
{
System.out.println("Login Failed,Please try Againe");//This will print at the console
}
}}
catch (Exception e) {
e.printStackTrace();
} finally {
pstmt.close();
conn.close();
}
Learn more about servlets

Categories