My record is not inserting into database? - java

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();

Related

Can not login after register jsp db

I have a problem with a login on my "website" i always have failed login despite this i write good login and password. It gets the value from data base name "register" and check it. And I have values in "register" in database and I normally write it on my login page and something is going wrong cause it redirecting me on "loginfail.jsp"This is my code:
<%# page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<%# page language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.sql.DriverManager.*" %>
<%
PreparedStatement ps;
Connection conn;
ResultSet rs= null;
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
conn=DriverManager.getConnection("jdbc:derby://localhost:1527/onlineshop","root","root");
Statement st=conn.createStatement();
%>
<%
boolean flag = false;
String LOGIN = request.getParameter ("LOGIN");
String PASSWORD = request.getParameter ("PASSWORD");
%>
<%
String sql = "SELECT LOGIN from REGISTER where LOGIN=? And PASSWORD =?";
try {
ps = conn.prepareStatement(sql);
ps.setString (7,LOGIN);
ps.setString (8,PASSWORD);
rs = ps.executeQuery ();
if (rs.next ()) {
out.println (rs.getString ("LOGIN"));
flag = true;
session.setAttribute("ULOGIN", rs.getString ("LOGIN"));
} else {
request.setAttribute("err", "user name or password error!");
}
rs.close ();
ps.close ();
conn.close ();
} catch (Exception e) {
out.println (e);
}
%>
<%
if (flag) {
%>
<jsp:forward page="loginsucc.jsp" />
<%
}
else {
%>
<jsp:forward page="loginfail.jsp"/>
<%
}
%>
</body>
</html>
The problem in your code is because of using the wrong index in the setString.
Replace
ps.setString (7,LOGIN);
ps.setString (8,PASSWORD);
with
ps.setString (1,LOGIN);
ps.setString (2,PASSWORD);
Check this for an example of using Prepared Statements. Check this for documentation.
[Update]
The rs.next () is returning false in your code. You can validate the following working example:
register.jsp:
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<%
boolean flag = true;
if (flag) {
%>
<jsp:forward page="loginsucc.jsp" />
<%
} else {
%>
<jsp:forward page="loginfail.jsp" />
<%
}
%>
</body>
</html>
loginsucc.jsp
<html>
<head>
<title>Insert title here</title>
</head>
<body>
Login successful
</body>
</html>
Output:

Java not connecting to database

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.

Ajax post from JSP to servlet in Java?

So, here is what I want to achieve. Lets say I have a form and I fill up the details and click on submit. The data will be inserted to the database. Now,my idea is that I want to display the data I just added to the DB using ajax without having to refresh the page. I am learning the idea of working with ajax and so I am a bit lost. Can someone suggest any advise.
The idea is that when I click on submit, there will be two events that will be triggered. One is inserting the data to the db and the other getting the data from the db and displaying it inside the tags.
This is my get method in my servlet.
Home.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html><body>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from apiinfo");
// out.println("<table border=1 width=50% height=50%>");
// out.println("<tr><th>EmpId</th><th>EmpName</th><th>Salary</th><tr>");
while (rs.next()) {
String n = rs.getString("apiname");
String nm = rs.getString("apiendpoint");
int s = rs.getInt("id");
response.getWriter().write(n);
// out.println("<tr><td>" + n + "</td><td>" + nm + "</td><td>" + s + "</td></tr>");
}
// out.println("</table>");
// out.println("</html></body>");
con.close();
}
catch (Exception e) {
out.println("error");
}
}
Home.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>
<div id="ajaxresponse">
</div>
<form>
API Name:<br>
<input type="text" id = "apiname" name="apiname">
API ENDPOINT:<br>
<input type="text" id ="apiendpoint" name="apiendpoint">
<br>
API VERSION:<br>
<input type="text" id="apiversion" name="apiversion">
ACCESSIBLE:<br>
<input type="checkbox" name="source" value="internet"> Internet<br>
<input type="checkbox" name="source" value="vpn"> VPN<br>
<br><br>
<input type="submit" formaction="Home" method="post" value="Submit">
<br>
<input type="submit" name="Submit" value="Submit">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Submit').click(function(event) {
console.log("You clicked me");
$.ajax({
url: "Home",
sucess:function(result){
}
});
});
});
</script>
</body>
</html>
I think you don't need to have two events. You should send ajax call to servlet and get from it properly formatted JSON (with data from DB). In that case, when you will receive data you know that insert was successful. After that in you sucess function you need to parse response from servlet and useing javaScrip set data into elements of you form.
you can achieve this in multiple ways based on your fail over scenarios
please go through this link for better understanding of ajax with servlets. On click of submit button first insert the data into db if this call is success then trigger one more ajax call to get data from db to display please check below sudo code
<script type="text/javascript">
$(document).ready(function() {
$('#Submit').click(function(event) {
console.log("You clicked me");
$.ajax({
url: "Home",
sucess:function(result){
// here call another servlet which will get the data
}
});
});
});
</script>
if the insert call fails you can mention generic message like "insertion failed please try again later"

Displaying null page on running my JSP

I'm trying to retrieve data from mysql. Upon giving the right input, data is not getting displayed. Code inside my jsp is not working too, but catch block executes correctly. Can you suggest me how to solve this problem?
Here is my code:
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.PreparedStatement"%>
<%# page import="java.util.*" %>
<%
Connection con=null;
PreparedStatement pst=null;
ResultSet rs=null;
String url = "jdbc:mysql://localhost:3306/check2allowMultiQueries=true";
%>
<html>
<head>
<link href="cprofile.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form name="view" method="POST">
<%
String z = request.getParameter("code");
String query="Select * from check2 where CODE='"+z+"';";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/check 2", "root", "");
Statement st=con.createStatement();
rs = st.executeQuery(query);
while (rs.next()) {
%>
<table border="1">
<tr>
<td><%=rs.getString("NAME")%></td>>
<td><%=rs.getString("MEDIUM")%></td>
<td><%=rs.getString("CODE")%></td>
<td><%=rs.getString("ADD1")%></td>
<td><%=rs.getString("ADD2")%></td>
<td><%=rs.getString("CK")%></td>
<td><%=rs.getString("FK")%></td>
<td><%=rs.getString("BOARD")%></td>
</tr>
</table>
<%}
} catch(Exception e) {
out.println(e);
}
%>

refreshing mysql table in jsp with a button

I am trying to retrieve the data from a mysql database on a jsp page, When the page loads, it loads the latest data (which is what i want), but then when i click on the refresh button i made it refreshes the table with older data and then the button doesnt work after that (wont refresh the table).
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
<h1>
<strong>test page</strong>
</h1>
<hr />
<canvas id="mycanvas" width="400" height="186"></canvas>
<script src="JavaScript/smoothie.js"></script>
<script src="JavaScript/chart.js"></script>
<script src="JavaScript/basic.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#refresh").click(function(){
$("#heart_rate").load("basic2.jsp")
});
});
</script>
</head>
<body>
<br>
<br>
<button id="refresh">Refresh table</button>
<br>
<br>
<form method="post" name="form">
<table id="heart_rate" border="1">
<tr>
<th>Sensor id</th>
<th>Time stamp</th>
<th>Heart rate</th>
<th>Event time</th>
</tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "Avantidrome";
String driver = "com.mysql.jdbc.Driver";
String un ="root";
String pw="root";
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, un, pw);
String sql = "select * from avantidrome.heartratedata order by timestamp DESC limit 10";
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
%>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
</tr>
<%
}
%>
<%
} catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
once the button is clicked it calls basic.jsp which is just:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<br>
<br>
<form method="post" name="form">
<table id="heart_rate" border="1">
<tr>
<th>Sensor id</th>
<th>Time stamp</th>
<th>Heart rate</th>
<th>Event time</th>
</tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "Avantidrome";
String driver = "com.mysql.jdbc.Driver";
String un ="root";
String pw="root";
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, un, pw);
String sql = "select * from avantidrome.heartratedata order by timestamp DESC limit 10";
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
%>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
</tr>
<%
}
%>
<%
} catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
all it needs to do is for the button to select the newest data from the database and return it to the table whenever it is clicked.
There are two ways to do what you want:
When the user press the refresh button, you simple refresh the page (this should be so fast that he wont notice that the page changed)
Using ajax. So, if choose this option you need to understand that to do this you only need one jsp (the one that loads the page in the begin and has the refresh button), a scrip of javascript that handles the refresh button and uses ajax to get the new data, and a servlet that receives the ajax request and returns an ajax response in json/xml containing the updates.
In my opinion, I prefer the first option, but if you choose to go for the second one, heres another SO post that may help you: How to use Servlets and Ajax?

Categories

Resources