How can I correct the calling URL? - java

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.

Related

Servlet Database URL

I'm trying to have a servlet to connect and interact with a database. I'm very new at this topic, so there probably are a couple of big issues, but the main problem I'm stuck at is how to get the database URL.
This is the servlet (I'm trying to keep it as light as possible)
import java.io.*;
import java.text.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class qaServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String firstName = request.getParameter("question");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/qaDatabase", "root", "");
//^HOW DO I GET THE RIGHT URL?^
PreparedStatement ps = con.prepareStatement("insert into faq values('1','question','sì');");
int i = ps.executeUpdate();
}
catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
First, it is better to use e2.printStackTrace(); instead of System.out.println(e2); when debugging.
Second, as the exception has shown, the actual problem was missing JAR file with JDBC driver, which has to be either in the WEB-INF/lib folder of your application, or in Tomcat's lib folder.
When developing, don't forget to republish your project after adding the driver's JAR file.

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

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

Openshift - No suitable driver found for jdbc:mysql

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.

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