Problem with insert data into Derby database
I use jsp and servlet, but I have try so many time but still can not insert data into database, it only shows
List of students with score:
and nothing else, it should insert user input into database, database connection is set, id data type is number , marks is int, name is varchar. No error in program I also add javaDB Driver to Libraries, I just do not understand what is wrong.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Score</title>
</head>
<body>
<h1>Welcome to Student Score Application</h1>
<form method="post" action="Result.jsp">
<input type="submit" value="View Data">
</form>
<br>
<form method="post" action="servletAdd">
ID:<input type="text" name="ID"><br>
Name:<input type="text" name="name"><br>
Marks:<input type="text" name="marks"><br>
<input type="submit" value="Add">
<input type="reset" value="Clear">
</form>
</body>
</html>
Result.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Result</title>
</head>
<body>
<h1>List of students with score:</h1>
<%#page import="java.sql.*"%>
<%
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/abc","abc","abc");
Statement stmt = con.createStatement();
String sql = "SELECT * FROM ABC";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String id = rs.getString("id");
String name = rs.getString("name");
int marks = rs.getInt("marks");
out.println("ID: "+ id);
out.println("Name: "+name);
out.println("Marks: "+marks);
%><br>
<%
}
//STEP 6:
rs.close();
stmt.close();
con.close();
%>
</body>
</html>
servletAdd.java
import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;
public class servletAdd extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String JDBC_DRIVER = "org.apache.derby.jdbc.ClientDriver";
String DB_URL = "jdbc:derby://localhost:1527/abc";
String USER ="abc";
String PASS ="abc";
Connection conn = null;
Statement stmt = null;
String id = request.getParameter("ID");
String name = request.getParameter("name");
int marks = Integer.parseInt(request.getParameter("marks"));
try{
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection("jdbc:derby://localhost:1527/abc",USER,PASS);
stmt = conn.createStatement();
String sql = "INSERT into ABC values"+"("+ "'"+ id +"'"+ ","+ name + ","+ "'"+ marks+"'"+")";
stmt.executeUpdate(sql);
stmt.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
response.setContentType("text/html;charset=UTF-8");
response.sendRedirect(request.getContextPath()+"/Result.jsp");
}
}
Related
This question already has answers here:
Calling a servlet from JSP file on page load
(4 answers)
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 1 year ago.
I am trying to send data from the InformationServlet servlet to the information.jsp file it redirects to.
The InformationServlet is the following:
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
#WebServlet(name = "Information", value = "/Information")
public class InformationServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
RequestDispatcher dispatcher = request.getRequestDispatcher("administration.jsp");
dispatcher.forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String email = request.getParameter("email");
request.setAttribute("myemail",email);
request.getRequestDispatcher("information.jsp").forward(request, response); // forward the email to the .jsp
}
}
and the information.jsp is:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.sql.SQLException"%>
<%-- Database information --%>
<%
String id = request.getParameter("userid");
String driver = "com.mysql.cj.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "employees";
String userid = "root";
String password = "password";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
%>
<html>
<head>
<title>information</title>
</head>
<body>
<% String member_email = (String)request.getAttribute("myemail");
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement = connection.prepareStatement("Select surname, name, email, phone, CV from member left join resume on memberEmail = email where email = ?");
statement.setString(1, member_email);
resultSet = statement.executeQuery();
resultSet.next();
%>
<div id="table">
<a action="Information" method="post" class="table-row">
<span class="table-cell" name="surname"> <%=resultSet.getString("surname") %> </span>
<span class="table-cell" name="firstname"> <%=resultSet.getString("name") %> </span>
<span class="table-cell" name="email"> <%=resultSet.getString("email") %> </span>
<span class="table-cell" name="phone"> <%=resultSet.getString("phone") %> </span>
<span class="table-cell" name="cv"> <%=resultSet.getString("cv") %> </span>
</div>
<%
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
Basically the .jsp file retrieves some information from the database "employees" depending on the "myemail" parameter passed from the servlet. I've searched it up a lot online and from what I found this is the correct way of establishing a communication between the two file types, yet the member_email variable in the scriplet of the "information.jsp" file is null somehow. This is my first attempt of building a web application, so the usage of servlets/jsps is rather new to me, so maybe I have an obvious mistake.
Also in case it is needed, the "administration.jsp" the "InformationServlet" listens from is the following:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%-- Database information --%>
<%
String id = request.getParameter("userid");
String driver = "com.mysql.cj.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "employees";
String userid = "root";
String password = "password";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
%>
<html>
<head>
<title>Administration Page</title>
<link rel="stylesheet" href="css_files/initial.css">
</head>
<body>
<h1>Administration Page</h1>
<%
try{
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select surname, name, email from member";
resultSet = statement.executeQuery(sql);
//each row will be filled with looping throw the table in the database
while(resultSet.next()){
%>
<div id="table">
<form method="post" action="information.jsp" class="table-row">
<span class="table-cell" name="surname"> <%=resultSet.getString("surname") %> </span>
<span class="table-cell" name="firstname"> <%=resultSet.getString("name") %> </span>
<span class="table-cell" name="email"> <%=resultSet.getString("email") %> </span>
<button type="submit">Navigate to user information</button>
</form>
</div>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
which is working as intended.
Running into the following 500 error:
javax.servlet.ServletException:
com.microsoft.sqlserver.jdbc.SQLServerException: The result set has no
current row.
I checked and I even have the rs.next() to push it to the next row.
Not sure why it is not pulling the QtyAvail
My table is called Inventory and it has a primary key of ProductID and an attribute called QtyAvail.
<%#page import="beans.Products"%>
<%#page import="java.lang.String"%>
<%#page import="java.util.List"%>
<%#page import="java.util.ArrayList"%>
<%#page import="beans.ItemLine"%>
<%# page import ="java.sql.*" %>
<%#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>
<jsp:useBean id="cart" class="beans.CartItems" scope="session"/>
<% //set up the Producst object
int QtyAvail = 0;
Products product = new Products();
String ProductID = request.getParameter("ProductID");
String productDescription = request.getParameter("Decscription");
String productQty = request.getParameter("ProductQty");
String productPrice = request.getParameter("ProductPrice");
String ProductName = request.getParameter("ProductName");
try{
//ger inv from SQL and make sure we have enough
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://clay.student.ad.fgcu.edu:1433;databaseName=ISM4154PartIteam02;user=4154Team02;password=Fgcu02;");
PreparedStatement ps = conn.prepareStatement("Select QtyAvail from Inventory where ProductID=?");
ps.setString(1, ProductID);
ResultSet rs = ps.executeQuery();
rs.next();
QtyAvail = rs.getInt("QtyAvail");
System.out.println(QtyAvail);
ps.close();
conn.close(); //Close the connections.
//Check that we have enough quantity on hand
`if(Integer.parseInt(productQty) <= QtyAvail) {
//a new LineItem is created and Attributes are set
ItemLine item = new ItemLine();
item.setProduct(product);
product.setProductDescription(productDescription);
item.setProductDescription(productDescription);
product.setProductQuantity(Integer.parseInt(productQty));
item.setProductQuantity(Integer.parseInt(productQty));
product.setProductPrice(Double.parseDouble(productQty));
item.setProductPrice(Double.parseDouble(productPrice));
cart.addItem(item);
//passes page to cart jsp
response.sendRedirect("CustomerCart.jsp");
}
else {
%>
<h3> Sorry! we only have currently" <%out.println(QtyAvail);%> "of <%out.println(ProductName);%> in Inventory </h3>
<h3> Please select a quantity amount we have in Inventory </h3>
<input type="button" name="continue" value="Continue Shopping" onclick="window.location='homePage.html'">
<% }
//}
//catch(Exception e){
//out.println("404 System Not Found");
// }
%>
</body>
</html>
The Remove.java is the servlet and the index.jsp is the jsp file. I am trying to delete the file using email,since it is unique.
Remove.java
package servletPool;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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("/Remove")
public class Remove extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uEmail = request.getParameter("email");
try {
Class.forName("com.mysql.jdbc.Driver");
String user = "root";
String pass = "root";
String query = "delete from user_details where email=?";
Connection con = DriverManager.getConnection("jdbc:mysql://locahost:3306/dbname", user, pass);
PreparedStatement ps = con.prepareStatement("delete from user_details where email=?");
ps.setString(1, uEmail);
int i = ps.executeUpdate();
if(i > 0) {
out.println("User successfully removed...");
}
} catch (Exception e) {
System.out.println(e);
}
}
}
and here is the index.jsp file from which the record will be deleted.
index.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>Registration Page.</title>
</head>
<body>
<div>
<div style="padding : 10px;">
<center>
<form action="Remove.servlet" method="get">
<h5>If you want to remove users,</h5>
<input type="email" placeHolder="User's Email" name="email"/>
<input type="button" value="Click" name="remove"/>
</form>
</center>
</div>
</center>
</div>
</body>
</html>
Try changing from:
<form action="Remove.servlet" method="get">
to:
<form action="Remove" method="post">
and from:
<input type="button" value="Click" name="remove"/>
to:
<input type="submit" value="Click" name="remove"/>
In addition, line 26 (</center>) in index.jsp and line 29 (String query = "delete from user_details where email=?";) in Remove.java should be removed because they are unnecessary.
On using the incorrect password it displays the message failed but on using the correct message it should display a welcome message with a logout button instead it displays a blank page. Can someone please check what the problem is?
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="dashboard" method="POST">
<input type="text" name="emailLogin" placeholder="enter your email address" size="50" />
<br>
<br>
<input type="password" name="passLogin" placeholder="enter your password" size="50" />
<br>
<br>
<input type="submit" value="login" name="login" />
</form>
</body>
</html>
dashboard.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<!DOCTYPE html>
<%
session = request.getSession(false);
if(session.getAttribute("userEmail")!=null)
{
Connection con=null;
PreparedStatement ps;
ResultSet rs;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e)
{
System.out.println(e);
}
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/userpass", "root", "root");
query="select * from userinfo where email=?";
ps = con.prepareStatement(query);
ps.setString(1, session.getAttribute("email").toString());
rs = ps.executeQuery();
if(rs.next())
{
out.println("welcome, "+rs.getString("name")+"!!");
out.println("<br>session created for you....");
//creating logout button
out.println("<form action=\"logout.jsp\" method=\"post\">");
out.println("<input type=\"submit\" name=\"logout\"value=\"Logout\">");
out.println("</form>");
}
}
if("POST".equalsIgnoreCase(request.getMethod()));
{
if(request.getParameter("login")!=null)
{
if(request.getParameter("login").equals("login"))
{
String email = request.getParameter("emailLogin");
String password = request.getParameter("passLogin");
Connection con=null;
PreparedStatement ps;
ResultSet rs;
String query;
try
{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){System.out.println(e);}
try
{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login", "root", "root");
query="select * from userinfo where email=? and password=?";
ps = con.prepareStatement(query);
ps.setString(1, email);
ps.setString(2, password);
rs = ps.executeQuery();
if(rs.next())
{
//login sucessfull!
//creating session..
session = request.getSession();
session.setAttribute("email", email);
response.sendRedirect("dashboard.jsp");
}else
{
out.println("failed");
}
}catch(SQLException e)
{
System.out.println(e);
}
}
}
}
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Dashboard</title>
</head>
<body>
</body>
</html>
logout.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
session.invalidate();
session = request.getSession();
response.sendRedirect("index.jsp");
%>
It was a simple syntax error a mismatch between attribute userEmail and email
I am still wondering what it is that i am doing wrong,my problem is i dont know if it is my entire sample code which has na error or my connection to the database which has an issues, as of where i stand i am not sure what is making me get this error. (displayed below).I have tried to look here at stack overflow but all i get is loading images using JSP but not adding them to the database. If we have one i couldnt trace please help me with the link. I have included all the libraries needed and my code has no error apart from this output. I came here because i am stranded and need a short review of what you proffesionals think is wrong with my code as done below. I will really appreciate anyhelp given as i am working on a deadline.
my Database name is
AppDB
I was wondering should i use the name of the table? to INSERT INTO? which is
'contacts'
Error Message
HTTP Status 404 - /UploadImageOnWeb/uploadServlet type Status report
message /UploadImageOnWeb/uploadServlet description The requested
resource is not available. Apache Tomcat/8.0.23
Thank you
Java Servlet Code
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet implementation class FileUploadDBServlet
*/
#MultipartConfig(maxFileSize = 16177215)
#WebServlet("/FileUploadDBServlet")
public class FileUploadDBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// database connection settings
/*private String dbURL = "jdbc:mysql://localhost/AppDB";
private String dbUser = "root";
private String dbPass = "mypassword";*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Connection conn = null;
String message = null;
try {
// connects to the database
/*DriverManager.registerDriver("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);*/
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/AppDB","root","mypassword");
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
My .Jsp class
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="uploadServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Enter First Name: </td>
<td><input type="text" name="firstName" size="20"/></td>
</tr>
<tr>
<td>Enter Last Name: </td>
<td><input type="text" name="lastName" size="20"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="20"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Display 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>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
The 404 error indicates that the form is not even getting to the servlet.
You defined the action attribute in the form as uploadServlet which doesn't seem to be a valid URL for your application.
The servlet's URL is defined in the #WebServlet annotation as FileUploadDBServlet.
So you can fix it by changing the action in the form or changing the URL for the servlet.