Openshift - No suitable driver found for jdbc:mysql - java

I am new to Java and Servlet Programming. I am trying to host a simple application which is working successfully in localhost. but when i host it to Openshift, it says No suitable driver found for jdbc:mysql://127.12.204.2:3306/shifar .
All i want to do is to save a string into the database.
Here is my code
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 TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String
HOST = System.getenv("OPENSHIFT_MYSQL_DB_HOST"),
PORT = System.getenv("OPENSHIFT_MYSQL_DB_PORT"),
USERNAME = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME"),
PASSWORD = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD"),
DB_NAME = "shifar";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("userName");
PrintWriter pw = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
pw.println("Error while loading driver: "+e.getMessage());
}
try {
String url = "jdbc:mysql://" + HOST + ":" + PORT +
"/" + DB_NAME;
Connection con = DriverManager.getConnection(url, USERNAME, PASSWORD);
PreparedStatement prep = con.prepareStatement("INSERT INTO names (name) VALUE (?)");
prep.setString(1, name);
int rc = prep.executeUpdate();
pw.println("Name saved !:"+name+" # "+ rc);
} catch (SQLException e) {
pw.println("Error while connecting: "+e.getMessage());
}
}
}
I can't figure out the error :(. The deployment of the application is done through Git as .WAR
Live Preview - (Enter something in the edittext and submit)

Your servlet container needs access to the jar file its way. For instance Tomcat might want something like mysql-connector-java-5.1.35-bin.jar
in the web-inf folder under the application. You need to focus on your classpath and the setup of your servlet container, regardless of what that is.
If you need further assistance hang a question under this with more details.

Related

How can I correct the calling URL?

I am making a basic login based project using Servlets in Eclipse IDE. I have made a jdbc file that first validates the user from the database and then redirects the page to the welcome page, that is an html file.
Everything is saved in their default folders. But everytime I try to execute my project, I get this error - . The called URL here is localhost:8080/Diary/welcome but the called URL should be localhost:8080/Diary/welcome.html.
How can I solve it?
Login.java:
import java.sql.*;
public class Login {
public static boolean validate(String user,String pass){
boolean status=false;
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Diary", "root", "root");
PreparedStatement ps=con.prepareStatement("SELECT * FROM trial WHERE user=? and pass=? and authorized=?");
ps.setString(1,user);
ps.setString(2,pass);
ps.setString(3,"yes");
ResultSet rs=ps.executeQuery();
if(rs.next()){
status=true;
}
}catch(Exception e){System.out.println(e);}
return status;
}
}
LoginServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
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("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String user=req.getParameter("user");
String pass=req.getParameter("pass");
if(Login.validate(user, pass)){
out.println("you are successfully logged in!");
req.getSession().setAttribute("login", "true");
req.getSession().setAttribute("user", user);
res.sendRedirect("welcome.html");
}else{
out.println("<p>Sorry, username or password error</p>");
req.getRequestDispatcher("login.html").include(req, res);
}
out.close();
}
}
You are correctly redirecting to the 'welcome.html' file. There must be an interceptor in your project that removes the '.html' part.

can't connect to mysql through eclipse - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
i've tried connecting my java servlet project in eclipse with my mysql server, and it gives me this error - java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
now, i've downloaded the latest connector jdbc from the mysql website, and i've put it in my java class path, and turned on the option.
also, i did checked the Driver class really is exist in the jar i downloaded, and it was.
i checked in google for hours for this problem, and couldnt find the solution.
here's my code, hopfully you guys can help me
LoginServlet.java
package androidLogin;
import java.io.IOException;
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.Connection;
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("GET METHOD");
Connection con = DBConnectionHandler.getConnection();
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
DBConnectionHandler.java
package androidLogin;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.mysql.jdbc.Connection;
public class DBConnectionHandler {
Connection con = null;
public static Connection getConnection() {
Connection con = null;
try {
Class.forName("com.mysql.jdbc.Driver");//Mysql Connection
con =(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/loginuser", "host", "13241234");//mysql database
if(con!=null){
System.out.println("connected successfully");
}
} catch (SQLException | ClassNotFoundException ex) {
System.out.println(ex);
// Logger.getLogger(DBConnectionHandler.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("not connected to database");
}
return con;
}
}
please help guys, i'm really desperate.
If you're running your Servlet in tomcat or any other container, make sure that mysql jar is in servlet container class path
Checkout these answers also:
ClassNotFoundException com.mysql.jdbc.Driver
classpath, eclipse and java.lang.ClassNotFoundException: com.mysql.jdbc.Driver

Create a connection to SQL Server DB inside Servlet request Thows "java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver"

Create a connection to SQL from a Java file with main() class defined works fine but calling the method inside a doPost() in Java Servlet throwing Error as
java.lang.ClassNotFoundException:com.microsoft.sqlserver.jdbc.SQLServerDriver
Working Code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Connect{
public static void main(String[] args) throws Exception
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url = "jdbc:sqlserver://localhost;databaseName=UserDB";
Connection con = DriverManager.getConnection(url,"sa","XXXXXXX");
String query =" SELECT * FROM Login";
Statement myStatement = null;
myStatement = con.createStatement();
ResultSet result = myStatement.executeQuery(query);
while(result.next()){
System.out.println("User name = " + result.getString("userID"));
System.out.println("User password = " + result.getString("userPassword"));
}
}
}
Now Working Code inside Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName= request.getParameter("username");
String password= request.getParameter("password");
try {
if( **new DbQuery().isValidLogin(userName, password)**)
{
response.getWriter().println("Welcome " +userName);
}
else{
response.getWriter().println("Please Enter a valid User name and Password");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
In the above code new DbQuery().isValidLogin(userName, password) creates a DB connection and the Class used as
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
On hitting the above line ........ ERROR
please help.
You need to put sqljdbc jar in your application server. For example if you are using tomcat server, go to the directory where you have installed the tomcat, open the LIB directory and make sure you have sqljdbc jar exists over there.
I got the same error while deploying the similar application in Tomcat Server. Put the relevant jdbc jar in the lib folder of Tomcat. It should work fine.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver during Dynamic Web Project creation in java

I am designing a registration page using MVC design pattern. I have made a class file which will input the parameters into the database using sql commands but i am getting
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Here is the code
package src.service;
import java.sql.*;
public class RegisterService {
public void addToDatabase(String name, String id, String email, String password){
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Get a connection to the database
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/chillmaarodb", "root", "rsystems");
// Create a statement
Statement myStatement = myConn.createStatement();
String sql = "insert into userid values(" + id + ", '" + name + "', '" + email + "', '" + password + "')";
myStatement.executeUpdate(sql);
}
catch (Exception e){
e.printStackTrace();
}
}
}
I have imported the driver in my lib folder of the project, imported it in build path, imported it in tomcat server in the folder tomcatv7>lib by creating a lib folder. Still it is showing the same error. Kindly help.
You need to setup the DB Connection in server.xml
follow this tutorial :
http://examples.javacodegeeks.com/core-java/mysql-connector-for-java-how-to-install-in-eclipse-and-tomcat/
and
https://www.mulesoft.com/tcat/tomcat-mysql
as well as you need to download MySQL Connector from:
http://dev.mysql.com/downloads/connector/j/
and copy the jar file to "C:\tomcat7\lib"
You should add MYSQL JDBC LIBRARY to your project
and also import
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
This worked for me---
This solution is only for Dynamic web projects.
Steps--
1)Create a Dynamic Web project
2)I added the "mysql-connector-java-5.1.48-bin" jar in WebContent/WEB-INF/lib folder.
2) Create a tomcat server
3)inside src create a demo servlet--
package com.luv2code.testdb;
import java.io.IOException;
import java.io.PrintWriter;
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 java.sql.*;
/**
* Servlet implementation class TestDbServlet
*/
#WebServlet("/TestDbServlet")
public class TestDbServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// setup connection variables
String user = "springstudent";
String pass = "springstudent";
String jdbcUrl = "jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimezone=UTC";
String driver = "com.mysql.jdbc.Driver";
// get connection to database
try {
PrintWriter out = response.getWriter();
out.println("Connecting to database: " + jdbcUrl);
Class.forName(driver);
Connection myConn = DriverManager.getConnection(jdbcUrl, user, pass);
out.println("SUCCESS!!!");
myConn.close();
}
catch (Exception exc) {
exc.printStackTrace();
throw new ServletException(exc);
}
}
}
4)Just right click and run as run on server select ur tomact server
Remember before all these you need to create ur db schema,
here i have used mysql workbench.
Mysql part is not covered in this answer.
If this does not work, try adding the msql connector jar inside tomcat/lib folder

How to achieve separation of concerns without using any framework but Tomcat + Servlets?

I have a code that works fine. The important parts are as follows:
My model class:
package biz.tugay.sakila.model;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:48 */
public class Actor {
private long id;
private String firstName;
private String lastName;
// Getters, setters...
}
My dao class:
package biz.tugay.sakila.dao;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:12 */
import biz.tugay.sakila.model.Actor;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ActorDao {
protected static final Connection connection = DBConnector.getConnection();
public List<Actor> getAllActors() throws SQLException {
List<Actor> allActors = new ArrayList<Actor>();
Statement stmt = connection.createStatement();
String sql = "SELECT * FROM Actor";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
// You get the idea... Setters again..
allActors.add(actor);
}
rs.close();
stmt.close();
return allActors;
}
}
and the DBConnector
package biz.tugay.sakila.dao;
/* User: koray#tugay.biz Date: 25/06/15 Time: 12:35 */
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnector {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/sakila";
static final String USER = "root";
static final String PASS = "";
private static Connection connection = null;
public static final Connection getConnection() {
if (connection != null) {
return connection;
} else {
try {
Class.forName(JDBC_DRIVER);
connection = DriverManager.getConnection(DB_URL, USER, PASS);
return connection;
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
}
throw new UnsupportedOperationException();
}
}
}
My Servlet class:
package biz.tugay.sakila.servlet;
/* User: koray#tugay.biz Date: 26/06/15 Time: 14:31 */
import biz.tugay.sakila.dao.ActorDao;
import biz.tugay.sakila.model.Actor;
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 java.io.IOException;
import java.sql.SQLException;
import java.util.List;
#WebServlet(urlPatterns = "/actors")
public class ActorServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ActorDao actorDao = new ActorDao();
List<Actor> allActors = null;
try {
allActors = actorDao.getAllActors();
req.setAttribute("allActors",allActors);
req.getRequestDispatcher("/actors.jsp").forward(req, resp);
} catch (SQLException e) {
}
}
}
And /actors.jsp will show an HTML table to the user.
I have made this exercise myself with the sakila sample database MySQL provides.
My question is, without using any framework such as Spring or Struts, how can I achieve a better separation? For example, currently ActorServlet depends on ActorDao concretely, can I fix this, if so how? Also ActorDao depends heavily on DBConnector. For example, I want to be able to create a NoSQL connector and use it, but currently I can not I guess?
First step is to abstract out some interfaces. For example, make ActorDao an interface, move the implementation to ActorDaoImpl or whatever. Create an ActorDaoFactory that hands you an ActorDao which is, under the covers, an ActorDaoImpl, but the servlet doesn't need to know that.
Second step is more complex... if you want to only use Tomcat, then injection and the like is out, but you can configure Tomcat to create these new interfaces and put them in JNDI. This process is probably too complex to put in an answer here, but the Tomcat documentation on JNDI is really nice. The process basically involves creating a factory, like I advocated above, and then having Tomcat invoke that factory through configuration.
Once you do this, looking them up from JNDI is as simple as
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our DAO
ActorDao ad = (ActorDao)envCtx.lookup("dao/actor");
Good luck!

Categories

Resources