Connecting Form data to MySQL using JSP - java

I am trying to store the fields from a form in my web-page to a Database in MySQL using JSP. I do not get any errors but i don't see the data in my database when i hit submit. Please help me identify my problem. I have the following codes:
Sign up - New User
<div id="container">
<form action = "insertData.jsp" method = "post">
<table>
<tr><td>E-mail/username:</td><td><input type="text" name="e-mail"></td></tr>
<tr><td>Password:</td><td><input type="password" name="password"></td></tr>
<tr><td>First Name:</td><td><input type="text" name="fName"></td></tr>
<tr><td>Last Name:</td><td><input type="text" name="lName"></td></tr>
<tr><td>Date Of Birth:</td><td><input type="text" name="dateOfBirth"></td></tr>
<tr><td>Account Type:</td><td><input type="text" name="type"></td></tr>
<tr><td></td><td><input type="submit" value="Submit"></td></tr>
</table>
</form>
</div>
</body>
and my JSP Code
<%
Connection con = null;
String email = request.getParameter("e-mail");
String password = request.getParameter("password");
String firstName = request.getParameter("fName");
String lastName = request.getParameter("lName");
String dob = request.getParameter("dateOfBirth");
String accountType = request.getParameter("type");
String queryText = "insert into user values('" + email + "'+'" + password + "','" + firstName + "','" + lastName + "','" + dob + "','" + accountType + "')";
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project", "root", "B#neswor1");
Statement stat = con.createStatement();
ResultSet rst = stat.executeQuery(queryText);
System.out.println("Data is successfully inserted!");
rst.close();
stat.close();
con.close();
} catch (Exception e) {
}
System.out.println("Success");
%>
Please help me identify what i am missing

The immediate cause of your problem is your insert query:
String queryText = "insert into user values('" + email + "'+'" +
password + "','" + firstName + "','" + lastName + "','" + dob + "','" +
accountType + "')";
If you look closely, there is no comma after the email literal. But you could have avoided this by using a prepared statement:
String sql = "insert into user values (?, ?, ?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(insertTableSQL);
ps.setString(1, email);
ps.setString(2, password);
ps.setString(3, firstName);
ps.setString(4, lastName);
ps.setString(5, dob);
ps.setString(6, accountType);
ps.executeUpdate();
Note that using a statement makes it much easier to see how your query string is being built. It also frees you from ugly string concatenation and escaping, which is error prone.
#duffymo pointed out many other potential problem with your code, some of which though should not necessarily cause it to crash. One other problem I see is that your date of birth field is being treated as a string, which it probably should be a date, and you should be inserting into your database as a date.

There are too many things wrong with this code:
Never, ever write scriptlet code in JSPs.
You have an empty catch block in that scriptlet code. If an exception is thrown you'll never know it.
Close resources in finally blocks.
You don't use PreparedStatement. You are asking for a SQL injection attack.
No XSS check.
No validation of input data.
Learn JSTL if you must use JSP.
Be aware that JSP model is vintage 1998. Modern UIs are done using HTML5, CSS3, and Javascript talking to REST services. The world has changed in the last 20 years. Tutorials exist for old technologies, but it doesn't mean they should be your first thought.

Related

How to pass multiple parameters gained from a mysql table in a java servlet form

This is my first time using Java servlets and I'm wanting to make a small picture gallery site. At the moment i'm having issues with how i'm passing parameters. Basically the input hidden field is passing all the parameters, and in the second and last servlet it's always coming up with the same folder name so it can never find different pictures in different folders.
I cannot work out how to fetch something from a mysql table that should be unique for each radio button, and then pass this information to the next servlet. Since it's passing ever folder category at the moment and the only folder i can actually use is the first folder in the category table.
THis is what is in my url for the second servlet
http://localhost:8080/techfore/SelectingPage?ShortName=AntShowcase&CategoryNo=3&ShortName=UMLDiagrams&ShortName=WildArt&ShortName=Traditional&ShortName=DreamweaverImages&ShortName=WindowsWallpaper
This is whats in my url in the last servlet
http://localhost:8080/techfore/PicturePage?PictureName=Redmoondesert.jpg&ShortName=AntShowcase
Database tablets
Categories DB
CategoryNo, ShortName, Description, Folder
Pictures DB
PictureNo, CategoryNo, Shortname, Description, FileName
I need to present a user with a category selection page which the below servlet tries to do.
Statement stmt = con.createStatement();
String query;
ResultSet rs;
// List the categories
query = "SELECT ShortName, Folder, CategoryNo FROM Categories ORDER BY CategoryNo";
rs = stmt.executeQuery(query);
out.println("Please select a category of pictures to explore:");
String URL = "http://localhost:8080/techfore/SelectingPage";
out.println("<form method=\"GET\" action=\"" + URL + "\">");
while (rs.next()) {
String shortName = rs.getString("ShortName");
String folderName = rs.getString("Folder");
int CategoryNo = rs.getInt("CategoryNo");
out.println("<input type = \"radio\" name =\"CategoryNo\" value="+CategoryNo+">"+shortName+"");
out.println("<br>");
out.println("<input type = \"hidden\" name =\"ShortName\" value="+folderName+">");
}
Utilities.oneButtonForm(out, URL, "Let me select a category");
out.println("</form>");
The next servlet should present a list of pictures from that particular category
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs;
query="SELECT Folder FROM Categories WHERE CategoryNo = "+categoryNo+"";
rs = stmt.executeQuery(query);
while(rs.next()) {
shortName = rs.getString("Folder");
}
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
out.println("Folder is:" +shortName);
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs;
// List the categories
query = "SELECT PictureNo, ShortName, Description, FileName FROM Pictures WHERE CategoryNo ="+categoryNo+" ORDER BY PictureNo";
rs = stmt.executeQuery(query);
String URL = "http://localhost:8080/techfore/PicturePage/"+shortName+"";
out.println("<form method=\"GET\" action=\"" + URL+">");
while (rs.next()) {
String pictureName = rs.getString("ShortName");
String fileName = rs.getString("FileName");
out.println("<input type = \"radio\" name =\"PictureName\" value="+fileName+">"+pictureName+"");
out.println("<br>");
}
out.println("<input type = \"hidden\" name=\"ShortName\" value="+shortName+"");
Utilities.oneButtonForm(out, URL, "Let me see th");
out.println("</form>");
out.println("<form action=\"/http://localhost:8080/techfore/WelcomePage\">" +
" <input type=\"submit\" value=\"Let me choose another category\" />\r\n" +
"</form>");
stmt.close() ;
}
The last servlet should display the picture, which exists on another site (I just need to provide the folder and the filename.
out.println("<img src=http://www.uni.site.sc.dk/courses/Pictures/Gallery/"+categoryName+"/"+pictureName+"");
out.println("<form action=/"+referer+">" +
" <input type=\"submit\" value=\"Let me choose another picture\" />\r\n" +
"</form>");
out.println("<form action=\"/http://localhost:8080/techfore/WelcomePage\">" +
" <input type=\"submit\" value=\"Let me choose another category\" />\r\n" +
"</form>");
The main issue is the folder is always the same due to how I'm getting it in the first servlet.

Java JDBC with mySql - passing id from table

Here is the code:
public static Connection getConnection() throws Exception {
String name1 = "Danny";
String city1 = "Wien";
try {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/supermarket??verifyServerCertificate=false&useSSL=true";
String username = "myuser";
String password = "mypass";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, username, password);
String sql = "insert into marketinfo "
+ " (name, country)" + " values (" + name1 + ", " + city1 + ")";
Statement insertie = conn.prepareStatement(sql);
insertie.executeUpdate(sql);
} catch (Exception e) {
System.out.println(e);
}
return null;
}
My error is "Unknown column 'Danny' in 'field list'" .
In Sql database my table contains id, name and city. I want to pass the id field because that id is incremented automatically.
There's alot going on in that code, and as others have suggested you should break it up. But actually performing the query can be done like this:
public class YourClass {
private static final String SQL = "INSERT INTO marketinfo (name, country) VALUES (?,?)";
public void addMarketInfo(String name, String city) {
try (Connection conn = getConnection();
PreparedStatement stmt = conn.prepareStatement(SQL)) {
stmt.setString(1, name);
stmt.setString(2, city);
stmt.executeUpdate();
} catch (SQLException e) {
// This is fine for debugging, but you probably want to log this or throw an exception
// Depends on how the rest of your application is set up
e.printStackTrace();
}
}
}
All your code creating the connection should most likely get moved to another class, and then called by the getConnection() method as in my example.
If you're using JDBC, PreparedStatements are used ALOT. It's worth looking more more examples on how they are used. Among other benefits, they're really helpful for avoiding string concatenation bugs like your original question.
This is the wrong way to do it. You should learn about PreparedStatement and how to bind values to parameters.
But it's worse than that.
Your method is getConnection, but it's also performing the query. Methods should do one thing well.
You don't close any of your resources. Another bad idea.
You print a stack trace to the console. Better to log it.
You hard wire your connection parameters instead of passing them in.
There's no connection pooling here.
seems you missed inner quotes around var name1 and city1
String sql = "insert into marketinfo "
+ " (name, country)" + " values ('"+ name1 +"', '"+ city1 +"')";
but most important you should use parametrized query instead of string concat .
To fix this you need to quote your variables in the SQL:
String sql = "insert into marketinfo "
+ " (name, country)" + " values ('"+ name1 +"', '"+ city1 +"')";
However, this is awful code, and you should not do it like this.
See here for why not: https://www.acunetix.com/websitesecurity/sql-injection/
As a hit, your sql should look like this:
String sql = "insert into marketinfo "
+ " (name, country)" + " values (:name, :city)";
Then, you use a prepared statement to set the values. Code like this is why websites get all their private information stolen.
String or varchar type should be between two quotes 'some string', but this still not secure so to avoid Syntax errors (Like you have now) or SQL Injection it's better to use PreparedStatement :
String sql = "insert into marketinfo (name, country) values (?, ?)";
try(PreparedStatement insertie = con.prepareStatement(sql);){
insertie.setString(1, name1);
insertie.setString(2, city1);
insertie.executeUpdate();
//...
}

SQL syntax in JAVA forms getText();

Just looking for a little help,
Created an application in JAVA and using a jTable to gather data from myphp database, I am using Insert, update and delete SQL commands so the user is able to manipulate data in the table.
Delete works perfectly, however I am having some trouble with my update and insert commands, just wondering if anyone can see if im using the ("'+) incorrectly, im not as eagle eyed as someone more experienced so just seeing if anyone can shed some light :)
Thanks!
INSERT CODE :
String query = "INSERT INTO `supplier`(`Company Name`, `Contact`, `Address`, `Postcode`, `Phone`) VALUES ('"+jTextField_SupplierCompany.getText()+"','"+jTextField_SupplierContact.getText()+"',"+jTextField_SupplierAddress.getText()+"','"+jTextField_SupplierPostcode.getText()+"',"+jTextField_SupplierPhone.getText()+")";
UPDATE CODE:
String query = "UPDATE `supplier` SET `Company Name`='"+jTextField_SupplierCompany.getText() + "',`Contact`='"+jTextField_SupplierContact.getText() + "',`Address`="+jTextField_SupplierAddress.getText() + "',`Postcode`="+jTextField_SupplierPostcode.getText() + "',`Phone`="+jTextField_SupplierPhone.getText() + " WHERE `ID` = "+jTextField_SupplierID.getText();
ERROR:
The error is throwing is the misuse of the WHERE clause in the "UPDATE" statement... May be obvious to some however cant get my head around it.
To avoid these type of syntax errors, or any SQL Injection, you can use PreparedStatement instead, it is so simple and so helful :
String query = "INSERT INTO `supplier`(`Company Name`, `Contact`, `Address`, `Postcode`, `Phone`) "
+ "VALUES (?, ?, ?, ?, ?)";
try (PreparedStatement pstm = conn.prepareStatement(query)) {
pstm.setString(1, jTextField_SupplierCompany.getText());
pstm.setString(2, jTextField_SupplierContact.getText());
pstm.setString(3, jTextField_SupplierAddress.getText());
pstm.setString(4, jTextField_SupplierPostcode.getText());
pstm.setString(5, jTextField_SupplierPhone.getText());
pstm.executeUpdate();
}
Your error happen because you forgot to close your String with '' check your query and you will see :
+"', " + jTextField_SupplierAddress.getText() + "'
//--^--------------------------------------------^
You Missed the Single quote in query
use this for insert
String query = "INSERT INTO supplier(Company Name, Contact, Address, Postcode, Phone) VALUES ('"+jTextField_SupplierCompany.getText()+"','"+jTextField_SupplierContact.getText()+"','"+jTextField_SupplierAddress.getText()+"','"+jTextField_SupplierPostcode.getText()+"','"+jTextField_SupplierPhone.getText()+"')";
Use this for update
String query = "UPDATE 'supplier' SET 'Company Name='"+jTextField_SupplierCompany.getText() + "',Contact='"+jTextField_SupplierContact.getText() + "',Address='"+jTextField_SupplierAddress.getText() + "',Postcode='"+jTextField_SupplierPostcode.getText() + "',Phone='"+jTextField_SupplierPhone.getText() + "' WHEREID` = '"+jTextField_SupplierID.getText()+"'";

data can not save into mysql properly

I am trying to make login time and logout time web application in jsp netbeans. While i try to save logout time into mysql database the date & time save correctly but user name and password both save as null. Please help me to save user name and password correctly to table.
Here is my logout code:
`<%# page import ="java.sql.*" %>
`<%String url="jdbc:mysql://localhost:3306/mysql";`
` String user="root";`
` String password="";`
`Class.forName("com.mysql.jdbc.Driver");`
`Connection con = DriverManager.getConnection(url, user, password);`
`Statement st = con.createStatement();`
`String uname1= request.getParameter("first_name");`
`String pwd = request.getParameter("pass");`
`session.setAttribute("fname", uname1);`
`session.setAttribute("pass", pwd);`
`int i = st.executeUpdate("insert into logut values ('" + uname1 + "','" + pwd + "',now())");`
`if (i > 0) `
`{out.write("<script type='text/javascript'>\n");`
`out.write("alert(' Logout Successfully!!! ');\n");`
`out.write("setTimeout(function({window.location.href='index.jsp'},1000);");`
`out.write("</script>\n");`
`}`
%>`
My database save like this: id= null pass=null and date and time save correctly. help me out. Thank you advance.
There is a typo in your statement. I guess you mean the table logout
"insert into logut values ('" + uname1 + "','" + pwd + "',now())"
But aside this you really have to consider prepared statements.
String insertTableSQL = "INSERT INTO DBUSER"
+ "(USER_ID, USERNAME, CREATED_BY, CREATED_DATE) VALUES"
+ "(?,?,?,?)";
PreparedStatement preparedStatement = dbConnection.prepareStatement(insertTableSQL);
preparedStatement.setInt(1, 11);
preparedStatement.setString(2, "username");
preparedStatement.setString(3, "password");
preparedStatement.setTimestamp(4, getCurrentTimeStamp());
// execute insert SQL statement
preparedStatement .executeUpdate();
Why prepared Statements:
difference-between-statement-and-preparedstatement
which-is-faster-statement-or-preparedstatement

Inserting user data from JSP into postgres database

I created a registered form of user information with JSP. I want to insert user data into a table with userinfo in postgre database after submitting form. But instead of adding data into this table, it gives me errors. Please help me!
<%
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String email = request.getParameter("email");
String user = request.getParameter("uname");
String pwd = request.getParameter("pass");
String pwd2 = request.getParameter("pass2");
Class.forName("org.postgresql.Driver");
Connection con = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/UserInformation", "postgres", "123456789");
PreparedStatement st = con.prepareStatement("insert into userinfo(firstname, lastname, email, username, password) VALUES ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "'");
//ResultSet rs;
int i = st.executeUpdate();
if (i > 0) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
%>
The output is:
org.postgresql.util.PSQLException: ERROR: syntax error at end of input
Position: 142
(This is a comment, but i can't comment because don't have 50 points)
You must know, that scriptlets are a bad practice when you work with JSP. When code keep in mind the software development principles, like DRY (don't repeat yourself), SRP (single responsibility principle) and more. You have mixed your views with domain model, never do that. The only thing that you get when doing this is:
Poor scalability
Poor maintenance
Spaghetti code
So, you need to re-structure your application by adding some layers (controllers and model).
Create a access data abstract layer for communication with your data (eg., dao, repository).
Create a controller for yours views.
Use JSTL in your views to avoid scriptlets.
You have an sql syntax error remove the comma and single quotation(,') at the end of your insert query
int i = st.executeUpdate("insert into userinfo(firstname, lastname, email, username, password, city, province, country) VALUES ('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "','" + city + "','" + province + "','" + country + "'");
In addition use PreparedStatement instead of Statement to avoid sql injection.

Categories

Resources