Java not connecting to database - java

I'm trying to get my java code to connect to the database. I swear it was connecting a few hours ago and suddenly it's not. I have reinstalled, restarted xampp, eclipse my laptop. I even uninstalled and reinstalled mysql.
Here's my .java file:
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class Connect_db {
// private static final String url = "jdbc:mysql://localhost:3306/sjsu";
// private static final String user = "root";
// private static final String password = "";
//
// public static void main(String[] args) throws Exception {
// java.sql.Connection con = null;
// try {
// Class.forName("com.mysql.jdbc.Driver");
// con = DriverManager.getConnection(url, user, password);
// // commented since doesn't exists in Java 6
// // System.out.println(con.getSchema());
// System.out.println(con.getCatalog());
// } finally {
// con.close();
// }
// }
private static MysqlDataSource ds = null;
public static MysqlDataSource getDataSource(String db_name) {
if (ds == null) {
// db variables set here
getDataSource("jdbc:mysql://localhost:3306", "root", "", 3306);
}
ds.setDatabaseName(db_name);
return ds;
}
private static void getDataSource(String db_url, String db_user, String db_password, int db_port) {
try {
ds = new MysqlDataSource();
ds.setServerName(db_url);
ds.setUser(db_user);
ds.setPassword(db_password);
ds.setPort(db_port);
} catch (Exception e) {
System.out.println("MysqlDataSource err: " + e.getMessage());
e.printStackTrace();
}
}
}
My .jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>atozknowledge.com demo Regjsp</title>
</head>
<body>
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String user=request.getParameter("userid");
session.putValue("userid",user);
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = Connect_db.getDataSource("sjsu").getConnection();
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into users values ('"+user+"','"+pwd+"','"+fname+"', '"+lname+"','"+email+"')");
out.println("Registered");
%>
Home
</body>
</html>
My html:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>atozknowledge.com demo Registration</title>
</head>
<body>
<form action="reg.jsp" method="post">
User name :<input type="text" name="userid" /><br/><br/>
password :<input type="password" name="pwd" /><br/><br/>
First name :<input type="text" name="fname" /><br/><br/>
Last name :<input type="text" name="lname" /><br/><br/>
Email :<input type="text" name="email" /><br/><br/>
<br/><br/>
<input type="submit" />
</form>
</body>
</html>
The error
It used to be able to put the userid, pwd, ... etc in my database and now it can't.

As the error states, it cannot find the class Connect_db. You need to add an explicit import for Connect_db to your JSP, that is add:
<%# page import ="package.of.Connect_db" %>
Querying directly from JSP is a poor choice, your should separate getting the data from displaying the data.
Tomcat also provides support for creating and registering data sources, use that instead of rolling your own. Especially, as MysqlDataSource doesn't provide connection pooling.
And finally, concatenating values into your query string is unsafe, especially with user provided input, as it leaves you open to SQL injection. Instead you should use a prepared statement with parameters. Please take a look at Using Prepared Statements in the JDBC tutorial.

I recommend you instead of giving the my.jsp inn the from action it is better to use a servlet. Maybe it can solve your. Create a new servlet and write your code inside of post method.

Related

Simple Java Web Application: Table Not Loading On Startup

I'm developing a simple application with Eclipse and Apache in which i display a table created with MySQL pertaining to products (with columns id, name and price) using Java, JSP and HTML. I also have a text box with a button which allows to filter the table showing only the products which have a bigger price than the one inserted on the text box.
Everything seems to be working fine including the filter. However, when i run the application for the first time, the full table isn't displayed like it should. It only displays when i use the filter. I'm not sure but there seems to be some conflict between the scriptlet for the filter elements and the table because if i comment the scriptlet for the filter elements in the JSP file, the table loads on startup like it should.
This is the code for JSP class which loads the table and the search elements (with some Bootstrap styling):
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.Connection,java.sql.ResultSet,java.sql.DriverManager,project1.components.DBConnector, project1.components.Filter"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Product</title>
<style type="text/css">
<%#include file="bootstrap/css/bootstrap.css" %>
<%#include file="bootstrap/css/bootstrap-theme.css" %>
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="bootstrap/js/jquery.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
</head>
<body>
<%
DBConnector dbc = new DBConnector();
Connection conn = dbc.connect();
String query = "select * from product";
%>
</body>
<form method="post">
<div class="col-xs-2 col-xs-offset-5">
<input type="text" class="form-control" name="value" value=<%=request.getParameter("firstinput")%>>
<br><br>
<input type="submit" class="form-control" name="submit" value="Filter">
<%
if(!request.getParameter("value").isEmpty()){
String val = request.getParameter("value");
Filter ft = new Filter();
query = ft.filterByValue(val);
}
%>
</div>
<br></br>
<table class = 'table table-hover'>
<tr>
<td>Id</td>
<td>Name</td>
<td>Product</td>
</tr>
<%
try
{
ResultSet rs = dbc.obtainTable(query);
while(rs.next())
{
%><tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getFloat("PRICE") %></td>
</tr> <%
}
%>
</table>
<%
rs.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</form>
</html>
The Java class which connects to the database and obtains data with a given query to be loaded on the table defined in the previous JSP file:
package project1.components;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnector {
String url = "jdbc:mysql://localhost:3306/products?autoReconnect=true&useSSL=false";
String user = "root";
String pass = "root";
public Connection connect() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
return (Connection) DriverManager.getConnection(url,user,pass);
}
public ResultSet obtainTable(String query) throws ClassNotFoundException, SQLException{
Connection cn = this.connect();
Statement stmt= (Statement) cn.createStatement();
return stmt.executeQuery(query);
}
}
And finally, the filter itself defined in Java:
package project1.components;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Filter {
public String filterByValue(String val) throws ClassNotFoundException, SQLException{
int num = Integer.parseInt(val);
String query = null;
if(num >= 0){
query = "select * from product where price >" + val;
}
else{
query = "select * from product";
}
return query;
}
}
Any help would be really appreciated.
Could you please replace the following:
if(!request.getParameter("value").isEmpty()){
by:
if(request.getParameter("value")!=null && !request.getParameter("value").trim().isEmpty()){
and see the results?

I need to create a system where user can login and logout. I am using netbeans and MYSQL database and GlassFish server 4.0

I know it is a simple task but don't able to find out what is the problem.
I made one login.jsp which is starting page.
LoginAction.jsp which will validate the user
I think there is some problem with ReqestDispatcher.
I am trying to find out solution from past 2 days and I am exhausted please help me.
All the table names and their field names are correct.
This is LoginAction.jsp
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="DataBase.DBCONNEction"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.Connection"%>
<%#page import="javax.servlet.RequestDispatcher"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String uname = request.getParameter("name");
String pass = request.getParameter("pass");
String unam, upass;
Connection con = null;
PreparedStatement prst = null;
Statement stm = null;
DBCONNEction DBC = null;
con = DBC.getConnection();
stm = con.createStatement();
RequestDispatcher rd = request.getRequestDispatcher("/welcome.jsp");
ResultSet rs = stm.executeQuery("select password from details where username = '" + uname + "'");
if (rs.next()) {
if (rs.getString("password").equals(pass)) { //If valid password
session.setAttribute("User", uname);
}else {
request.setAttribute("Error", "Invalid password.");
rd = request.getRequestDispatcher("/login.jsp");
}
}
else {
request.setAttribute("Error", "Invalid user name.");
rd = request.getRequestDispatcher("/login.jsp");
}
rd.forward(request, response);
%>
</body>
</html>
This is login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Knowledge Repository System</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="header">
<h1>Knowledge Repository System JSP</h1>
<form id="search" action="loginAction.jsp" method="POST">
<label>Username <input type="text" name="name" id="s-user" style="width:90%;" required></label>
<label>Password<input type="password" name="pass" id="s-pass" style="width:90%;" required></label>
<input type="submit" class="submit" value="Submit">
</form>
</div>
Admin Panel
<div class="nav">
<h2 style="font-size: 36px"><strong>Sign Up</strong></h2>
<form action="details" method="POST">
<signup>
<p><input type="text" name="name" required placeholder="Username"></p>
<p><input type="password" name="pass" required placeholder="password"></p>
<p><input type="text" name="email" required placeholder="xyz#abc.com"></p>
<p><input type="submit" value="Sign Up" align="center"></p>
</signup>
</form>
</div>
</body>
</html>
This is DBCONNEction.java
package DataBase;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBCONNEction {
private static String URL = "jdbc:mysql://localhost:3306/repository";
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String pass = "myserver";
private static String user = "root";
static Connection con = null;
static {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
return con;
}
}

My record is not inserting into database?

I'm trying to insert my data into database using Textbox, Sometime it inserts the data in only using Internet Explorer but not in Mozilla firefox.
It's strange.....
My data sometime gets uploaded but only using Internet Explorer and sometimes it stops working. Please help what's that mean?
Here is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" >
$(function() {
$(".update_button").click(function() {
var boxval = $("#content").val();
var dataString = 'content='+ boxval;
if(boxval=='')
{
alert("Please Enter Some Text");
}
else
{
$.ajax({
type: "POST",
url: "demo.jsp",
data: dataString,
cache: false
});
}
});
});
</script>
</head>
<body>
<div>
<form method="post" name="form" action="">
<h3>What are you doing?</h3>
<textarea name="content" id="content" ></textarea><br />
<input type="submit" value="Update" name="submit" class="update_button" />
</form>
</div>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/poststatus", "root", "1234");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from messages order by msg_id desc");
while(rs.next()){
String msg=rs.getString("msg");
%>
<ol id="update" class="timeline"><%=msg %></ol>
<%
}
}
catch(Exception e){
e.printStackTrace();
}
%>
</body>
</html>
and here is my demo.jsp:
<%# page import="java.sql.*" errorPage="" %>
<%
String content=request.getParameter("content");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/poststatus", "root", "1234");
Statement st=con.createStatement();
int i=st.executeUpdate("insert into messages(msg) values('"+content+"')");
}
catch(Exception e){
e.printStackTrace();
}
%>
And yes, I can fetch my data from database ..as you could see my code. But i'm unable to insert data..
Surely, Help would be appreciated!
EDITED:
Here is my created table:
create database if not exists poststatus;
use poststatus;
create table messages(
msg_id INT auto_increment,
msg VARCHAR(1000) NOT NULL,
primary key(msg_id)
);
The update button that sends the AJAX request is also the form's submit button, so when you click it, it begins submitting the form, which navigates away from the current page, cutting off the code before it can run the AJAX request.
Modify the beginning of your click handler to:
$(".update_button").click(function(e) {
e.preventDefault();
Calling preventDefault() on the event will prevent the form from submitting, giving your AJAX function the chance to run.
Additionally, there is a serious problem in the Java code; because the value is inserted with string concatenation, it creates a blatant SQL injection vulnerability, and also will not work if someone innocently types an apostrophe. Change:
Statement st=con.createStatement();
int i=st.executeUpdate("insert into messages(msg) values('"+content+"')");
to:
PreparedStatement st = con.prepareStatement("insert into messages(msg) values(?)");
st.setString(1, content);
int i = st.executeUpdate();

Error : No suitable driver found for database on AWS RDS

My code is as below, I have a MySQL DB on AWS RDS. I have also already included the mysql-connector-java-5.1.31-bin.jar in my build path.
My code is as below :
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.sql.*"%>
<%# page import="java.util.Scanner "%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome Customer to Online Mall</title>
</head>
<body>
<%
final String host = "jdbc:mysql://mySqlPath/ShopSystem";
final String uName = "myusername";
final String uPass = "mypassword";
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
//#SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
String Cust_address, Cust_email, Cust_contact;
Connection con = DriverManager.getConnection( host, uName, uPass );
//View all shops
Statement stmt5 = con.createStatement();
ResultSet rs2 = stmt5.executeQuery("SELECT * FROM ShopSystem.Shop");
while(rs2.next())
{
System.out.print("s_id = "+rs2.getInt(1)+"\t");
System.out.print("s_name = "+rs2.getString(4)+"\t");
System.out.print("s_location = "+rs2.getString(3)+"\t");
System.out.println();
}
sc.close();
}
catch(SQLException err)
{
System.out.println(err.getMessage());
}
%>
</body>
</html>
I am getting the following error :
Aug 01, 2014 5:31:46 PM org.apache.jasper.compiler.Compiler removeGeneratedFiles
WARNING: Failed to delete generated Java file [C:\Users\Documents\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\local host\ShopSystem-AWSJavaWebProject\org\apache\jsp\WelcomeCustomer_jsp.java]
No suitable driver found for jdbc:mysql://mySqlPath/ShopSystem
Please help.
Thank you in advance.
Your this line seems to be incorrect.
final String host = "jdbc:mysql://mySqlPath/ShopSystem";
It should be something like this :
jdbc:mysql://localhost/ShopSystem
or
jdbc:mysql://{YOUR_IP}/ShopSystem // e.g. "jdbc:mysql://192.168.15.102/ShopSystem"

redirects not working in jsp

i have created a jsp page view.jsp and corresponding to that i have created a servlet admin.java
code of both below...
when i click on register a blank page appears...redirects are not working. please help me in resolving this
view.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="admin">
username <input type="text" name="username" value="" />
password <input type="text" name="password" value="" />
<input type="submit" name="register" value="register" />"
</form>
</body>
</html>
admin.java
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class admin extends HttpServlet {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/inventory";
static final String USER = "root";
static final String PASS = "root";
Connection conn = null;
Statement stmt = null;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
String user = req.getParameter("username");
String pass = req.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "select * from admins";
//String sql = "select * from admins WHERE username='"+user+"' AND
password='"+pass+"'";
ResultSet rs = stmt.executeQuery(sql);
PrintWriter pw = res.getWriter();
//res.setContentType("text/html");
while (rs.next())
{
if((user.equals(rs.getString(0))) && (pass.equals(rs.getString(1))))
{
//String n=rs.getString("username");
//String p=rs.getString("password");
res.sendRedirect("loginsuccess.jsp");
}
else
{
res.sendRedirect("loginfailure.jsp");
}
}
pw.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Use RequestDispatcher instead of sendRedirect():
RequestDispatcher reqDispatcher = req.getRequestDispatcher("path/loginsuccess.jsp");
reqDispatcher.forward(req, res);
Read more about RequestDispatcher.
Read the difference between RequestDispatcher and sendRedirect, and whento use both of them.
Try this
getServletContext().getRequestDispatcher("/loginsuccess.jsp").forward(request, response);
sample code :
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
request.setAttribute("error", "Unknown login, please try again."); // Set error.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}
you should try that method, but my suggestion as:
I think you should not close the statement, result set and connection,.
And then you should check the if condition. if maybe your condition have an error the page like empty. so should check that..
source from : https://stackoverflow.com/a/2048640/3242978
When you click 'register' button it submits the form as a HTTP POST request. You need to implement doPost() instead.

Categories

Resources