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
Related
I have a login app that needs to connect to a server to check the username and password. I am using netbeans and the jbdc is installed and working in the services tab(thanks stack overflow!). By the jbdc is work I mean that i can execute SQL script through it.
I have set this up with MS Server 16 and MySQL so I am convied it is the code:
Connection method:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
private static final String USERNAME = "root";
private static final String PASSWORD = "mess";
private static final String SQCONN = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection()throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(SQCONN, USERNAME, PASSWORD);
}catch (ClassNotFoundException e) {
}
return null;
}
}
loginmodel:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
Connection connection;
public LogInModel() {
try{
this.connection = dbConnection.getConnection();
}catch(SQLException e){
}
if(this.connection == null){
System.out.println("here");
// System.exit(1);
}
}
public boolean isDatabaseConnected(){
return this.connection != null;
}
public boolean isLogin(String username, String password) throws Exception{
PreparedStatement pr = null;
ResultSet rs = null;
String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
try{
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
boolean bool1;
if(rs.next()){
return true;
}
return false;
}
catch(SQLException ex){
return false;
}
finally {
{
pr.close();
rs.close();
}
}
}
}
I believe the issue is the return null; from the dbConnection file. The if(this.connection==Null) comes back true and the system is exiting.
Thank you in advance.
Your dbConnection class is a bad idea. Why hard wire those values when you can pass them in?
Your application will only have one Connection if you code it this way. A more practical solution will use a connection pool.
Learn Java coding standards. Your code doesn't follow them; it makes it harder to read and understand.
Here's a couple of recommendations:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USERNAME = "root";
public static final String PASSWORD = "mess";
public static final String URL = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
I might write that LogInModel this way:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
private static final String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
private Connection connection;
public LogInModel(Connection connection) {
this.connection = connection;
}
public boolean isLogin(String username, String password) {
boolean isValidUser = false;
PreparedStatement pr = null;
ResultSet rs = null;
try {
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
while (rs.hasNext()) {
isValidUser = true;
}
} catch (SQLException ex) {
e.printStackTrace();
isValidUser = false;
} finally {
dbUtils.close(rs);
dbUtils.close(pr);
}
return isValidUser;
}
}
Here's my guess as to why your code fails: You don't have the MySQL JDBC driver JAR in your runtime CLASSPATH. There's an exception thrown when it can't find the driver class, but you didn't know it because you swallowed the exception.
I am a student learning JSP, and I seem to have this issue in executing a method via an object of a DAO class. When the database connectivity and SQL query is given on the servlet itself it, it will work. But when given in the DAO class and a object is used, it doesn't work. Please help.
import dataaccessobjects.cartDAO1;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class addtoCartServ extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
cartDAO1 newcart = new cartDAO1();
PrintWriter out = response.getWriter();
if (request.getParameter("submit") != null){
//out.println("added to cart");
try {
//out.println("submit not null");
String Uname = (String) request.getSession().getAttribute("Welcome");
String ino = request.getParameter("ino");
String iqnty = request.getParameter("quantity");
String iname = request.getParameter("iname");
if(newcart.addToCart(iname,Uname,ino,iqnty)){
out.println("added to cart");
}
} catch (SQLException ex) {
Logger.getLogger(addtoCartServ.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(addtoCartServ.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
The DAO class
public cartDAO1(){
}
public boolean addToCart(String iname,String username, String ino,String iqnty) throws SQLException, ClassNotFoundException{
boolean flag = false;
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/styleomega","root","");
PreparedStatement ps = conn.prepareStatement("INSERT INTO cart(iname,uname,ino,iqnty) VALUES (?,?,?,?)");
// set the values for parameters
ps.setString(1,iname);
ps.setString(2,username);
ps.setString(3,ino);
ps.setString(4,iqnty);
int rs = ps.executeUpdate();
if (rs==1){
flag = true;
}
return flag;
}
}
You should be import the DAO class package in servlet then access it it will work like
import DAO.cartDao;
If you will not import then how to acces it
I don't understand exactly what is not working? But I have noticed, you're not closing statement and the database connection in your DAO class.
FYI: An example
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = // Retrieve connection
stmt = conn.prepareStatement(// Some SQL);
rs = stmt.executeQuery();
} catch(Exception e) {
// Error Handling
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {};
try { if (stmt != null) stmt.close(); } catch (Exception e) {};
try { if (conn != null) conn.close(); } catch (Exception e) {};
}
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.
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.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
i am a beginner in java i am trying to use mysql database i have downloaded mysql-connector-java-5.1.23-bin.jar file from mysql.com and i have added this jar file to in my build path of my project but there is an error in the following code
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Type mismatch: cannot convert from java.sql.Statement to com.mysql.jdbc.Statement
package com.example.demo;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try
{
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}
}
Wrong classes
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
should be
import java.sql.Connection;
import java.sql.Statement;
In fact, java decouples everything from a specific database engine. One never should need an import of MySQL (or ProgressSQL or ...) classes.
To have those classes available at run-time, the first thing after the try, before getting the connection would be:
Class.forName("com.mysql.jdbc.Driver");
This technique would allow reading all strings from a configuration file, and writing database independent code.
Missing: conn = ...
conn = DriverManager.getConnection(CONN_STR, userName, userpwd);
package com.example.demo;
import java.sql.*;
public class DBConnect
{
private static final String userName = "root";
private static final String userpwd = "sverma";
private static final String CONN_STR = "jdbc:mysql://localhost:3306/phpweb_db";
public static void main(String[] args) throws SQLException
{
Connection conn;
Statement st;
ResultSet rs;
try
{
Class.forName("com.mysql.jdbc.Driver");
DriverManager.getConnection(CONN_STR, userName, userpwd);
st=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = st.executeQuery("select * from user");
rs.last();
System.out.println("No of rows: " + rs.getRow());
// System.out.println("Connected Successfully...");
}
catch (SQLException e)
{
System.err.println(e);
}
finally
{
if (rs != null)
{
rs.close();
}
if (st != null)
{
st.close();
}
if (conn != null)
{
conn.close();
}
}
}