Search through a database in a JSP - html

I've been making a database for a flight company, and one of the requirements is to allow customers to search for flight schedules in order for them to book flights. However, when I run my code, I keep getting errors. I've tried looking through my code many times, but I still can't seem to find out where the problem is. The error message that I got was that there was a problem with the line if(rs.next()){, but it doesn't show any red underline when I'm looking through the code editor. Instead, the parts that have the red underlines are all my <tr> and <td> tags.
Also, I would appreciate it if someone can teach me how to create a dropdown table for the origin_airport and destination_airport datafields, so that users can choose.
Here's my code:
<%# 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>Member Login</title>
</head>
<body>
<form>
<table>
<%#page import="java.sql.*" %>
<%
String user = request.getParameter("user");
out.println("Welcome, "+user);
out.println("<br>Account status: Member");
out.println("<br>What flight do you want to search for today?");
String origin=request.getParameter("origin_airport");
String dest=request.getParameter("destination_airport");
String depart=request.getParameter("departure_time");
String arrival=request.getParameter("arrival_time");
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url="jdbc:mysql://localhost/testing";
String username="root";
String password="password";
Connection conn=DriverManager.getConnection(url,username,password);
Statement st=conn.createStatement();
ResultSet rs = st.executeQuery("select * from flight_schedule where origin_airport='"+origin+"'");
ResultSet rs1 = st.executeQuery("select * from flight_schedule where destination_airport='"+dest+"'");
ResultSet rs2 = st.executeQuery("select * from flight_schedule where departure_time='"+depart+"'");
ResultSet rs3 = st.executeQuery("select * from flight_schedule where arrival_time='"+arrival+"'");
if(rs.next()){
%>
<tr><td>Origin airport: </td><td<input type="text" value="<%=rs.getString("origin_airport")%>" > </td></tr>
<tr><td>Destination airport: </td><td<input type="text" value="<%=rs1.getString("destination_airport")%>" > </td></tr>
<tr><td>Departure date: </td><td<input type="text" value="<%=rs2.getString("departure_time")%>" > </td></tr>
<tr><td>Arrival date: </td><td<input type="text" value="<%=rs3.getString("arrival_time")%>" > </td></tr>
<%
}
%>
</form>
</table>
</body>
</html>
I would really appreciate it if someone could take their time and help me by pointing me in the right direction. Thanks in advance.
The error message shown on Eclipse: An exception occurred processing JSP page [/Homescreen_Member.jsp] at line [33]
Exception of error:
org.apache.jasper.JasperException: An exception occurred processing JSP page [/Homescreen_Member.jsp] at line [33]
30: ResultSet rs1 = st.executeQuery("select * from flight_schedule where destination_airport='"+dest+"'");
31: ResultSet rs2 = st.executeQuery("select * from flight_schedule where departure_time='"+depart+"'");
32: ResultSet rs3 = st.executeQuery("select * from flight_schedule where arrival_time='"+arrival+"'");
33: if(rs.next()){
34: %>
35: <tr><td>Origin airport: </td><td<input type="text" value="<%=rs.getString("origin_airport")%>" > </td></tr>
36: <tr><td>Destination airport: </td><td<input type="text" value="<%=rs.getString("destination_airport")%>" > </td></tr>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:588)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root cause:
javax.servlet.ServletException: java.sql.SQLException: Operation not allowed after ResultSet closed
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:669)
org.apache.jsp.Homescreen_005fMember_jsp._jspService(Homescreen_005fMember_jsp.java:178)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.sql.SQLException: Operation not allowed after ResultSet closed
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743)
com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6303)
org.apache.jsp.Homescreen_005fMember_jsp._jspService(Homescreen_005fMember_jsp.java:142)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)

The Javadoc for Statement says "By default, only one ResultSet object per Statement object can be open at the same time." You've opened three other ResultSets before accessing the first one, each causing the previous ResultSet to be closed, and you can't do that.

Related

Taking input variables from a table(HTML) and supply the values as a variable name for a database table

I would like to create a form for a patient database system. Then I will give some input data to each textbox of the form and the data will be stored in a MySQL database.
I wrote a JSP file as follows
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<tr><td>Pid</td><td><input type="text" name="pid" required /></td></tr>
<tr><td>Name</td><td><input type="text" name="patientname" required /></td></tr>
<tr><td>Address</td><td><input type="text" name="patientaddress" ></td></tr>
<tr><td>Phone number</td><td><input type="number" name="Ph" required /></td></tr>
<tr><td>Email</td><td><input type="email" name="email" required /></td></tr>
<tr><td>Type</td><td><input type="text" name="patienttype" ></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="register"></td></tr>
</table>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hospitalm","root","1234");
out.println ("database successfully opened.");
String sql = "INSERT INTO patient (pid, pname, address, phone, email_id,ptype) values (?, ?, ?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, Pid);
statement.setString(2, Name);
statement.setString(3, "Forrest");
statement.setDouble(4, 664208158);
statement.setString(5, "ava#gmail.com");
statement.setString(6,"G");
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("One row inserted.");
}
}
catch(SQLException e) {
out.println("SQLException caught: " +e.getMessage());
}
%>
</body>
</html>
This two lines throw error
statement.setString(1, Pid);
statement.setString(2, Name);
If I input some values like 'p101' for Pid and 'John' for Name then I can easily entered a record on the database hospitalM.
But if I try Pid and Name which are the variable names for table,
<tr><td>Pid</td><td><input type="text" name="pid" required /></td></tr>
<tr><td>Name</td><td><input type="text" name="patientname" required /></td></tr>
I got error.
How could I solve this?
JSP does not automagically bind request parameters in to Java variables, which is what you're trying to do here.
In order to get the parameters, you need to query the request object directly. Something akin to:
statement.setString(1, request.getParameter("Pid"));
statement.setString(2, request.getParameter("Name"));
Addenda:
Regarding double (or other non-strings), there's two things you can do.
One, you can convert them on the fly:
statement.setDouble(4, Double.parseDouble(requests.getParameter("phone")));
Second, you can rely on the SQL driver to do it for you.
statement.setString(4, requests.getParameter("phone"));
The "setXXX" in JDBC is based on the value that you're setting, NOT the data type of the column in the database. Inevitably, most of the time, whatever you set in the JDBC statement is going to be turned in to a string before being shipped up to the DB anyway. So, you can just use setString and be done with it and let the driver/db figure it out.
Either way, if you send in badly formatted data (i.e. "Tom" for the phone number), you're going to get an exception, either from the Double.parseDouble or when the DB tries to convert it during the insert. But that's a separate issue from simply setting parameters.

Get SQLexception error before giving the user input in jsp page

I like to create a registration form where user can register his or her data and the given data will be saved on a database. I created a database HospitalM using mysql workbench 8.0. I ran the project, the jsp file for form creation on Tomcat server. The pid is a primary key in the table called patient in the database HospitalM.
When I run the form on server a form generated but the form did not wait for input data and throw a message SQLException caught: Column 'pid' cannot be null.
I will share my code and the form in the below. Can any one give me some hints why it did not work?
JSP code: (name of the jsp file insert.jsp)
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<tr><td>Pid</td><td><input type="text" name="pid" required /></td></tr>
<tr><td>Name</td><td><input type="text" name="patientname" required /></td></tr>
<tr><td>Address</td><td><input type="text" name="patientaddress" ></td></tr>
<tr><td>Phone number</td><td><input type="number" name="Ph" required /></td></tr>
<tr><td>Email</td><td><input type="email" name="email" required /></td></tr>
<tr><td>Type</td><td><input type="text" name="patienttype" ></td></tr>
<tr><td></td><td><input type="submit" name="submit" value="register"></td></tr>
</table>
<%
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/hospitalm","root","1234");
out.println ("database successfully opened.");
String sql = "INSERT INTO patient (pid, pname, address, phone, email_id,ptype) values (?, ?, ?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, request.getParameter("pid"));
statement.setString(2, request.getParameter("pname"));
statement.setString(3, request.getParameter("address"));
statement.setString(4, request.getParameter("phone"));
statement.setString(5, request.getParameter("email_id"));
statement.setString(6,request.getParameter("ptype"));
int row = statement.executeUpdate();
if (row > 0) {
System.out.println("One row inserted.");
}
}
catch(SQLException e) {
out.println("SQLException caught: " +e.getMessage());
}
%>
</body>
</html>
The sql query for patient table:
create table patient(pid varchar(10),
pname varchar(40) not null,
address varchar(10),
phone numeric(10,0) not null,
email_id varchar(20) not null,
ptype varchar(2),
primary key(pid),
check(email_id like '%_#__%.__%'));
The output that I got
The problem here is that when you first access the page, all of that code gets executed, but there was no request to process.
So, during the first access, all of those request parameters are null.
As suggested by Piotr, you could use the request method to get for whether it's a GET or a POST, and only execute the code on the POST.
The proper answer to that goes much deeper into how these kinds of things are architected along with the page workflow, but that's a much deeper topic that to go in to here.
For now, the simple issue is that on the first access, there are no parameters, so you're essentially trying to do:
statement.setString(1, null);
Which is illegal (to set a column to an explicit SQL NULL value in JDBC, you use the statement.setNull(1) method).

I cant understant why the delete button does not work for me in jsp

This is my code:
AdminDelete.jsp:
<%# page import ="java.sql.*" %>
<%
String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub",
"root", "root");
Statement st = con.createStatement();
int t= st.executeUpdate("DELETE * FROM post WHERE(uid like'"+uid+"' AND content like'"+content+"')");
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
this is in the Admin's index:
<form method="send" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<% String content = request.getParameter("content");%>
<input type="button" value="delete" id="content">
</form>
I am trying to make a button that when i'm clicking on it, it delete's all of the posts in my website but when i click it, it dosen't do anything
I can not write entire answer in comment. So writing answer. As I mentioned in comment. You need to add space after LIKE. Also using PreparedStatement.
<%# page import ="java.sql.*" %>
<% String uid = session.getAttribute("uid").toString();
String content = request.getParameter("content");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/upload_hub", "root", "root");
PreparedStatement ps = con.prepareStatement("DELETE FROM post WHERE uid like ? AND content LIKE ?");
ps.setString(1, "%" + uid + "%");
ps.setString(2, "%" + content + "%");
int t= ps.executeUpdate();
try {
con.close();
} catch(Exception e) {
e.printStackTrace();
}
if(t>0){
response.sendRedirect("../Admin.jsp");
}
%>
One thing to note here is that you need to verify the UID is set in session and content is set in request parameters.
Also you have used method="send". Instead use method="POST".
<form method="POST" action="functions/AdminDelete.jsp" >
<h3>delete all posts:</h3>
<input type="text" name="content" />
<input type="submit" value="Delete" />
</form>
Suppose one record in DB has UID containing letter a and corresponding to this record content has value containing b. Now submit data with b as input in form and make sure UID in session has value set to a. It should work. If you come up with any error message let me know.

to send value of <input> tag dynamically through iteration

this is my code:
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%
//String b1=request.getParameter("b1");
String fy=request.getParameter("fy1");
Connection con=conn.connectionprovider.getDbConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from institutemaster where fy='"+fy+"'");
out.println("<form action=adminlistvalidate method=post ><table border='3'>");
out.println("<tr><th>FINANCIAL YEAR</th><th>INSTITUTE ID</th><th>INSTITUTE NAME</th><th></th><th></th></tr>");
**while (rs.next())
{%>
<% out.println("<tr><td>"+rs.getString(1)+"</td><td>"+rs.getInt(2)+"</td><td>"+rs.getString(3)+"</td><td>active <input type=radio checked=checked name="+rs.getInt(2)+" value=a /> </td><td>inactive<input type=radio name="+rs.getInt(2)+" value=b /></td></tr>"); %>**
<% }//request.setAttribute("name",rs.getInt(2));
out.println("</table><input type=submit name=submit value=submit />");
out.println("</form>");
%>
now see the highlighted part. im sending each row of table obtained to next servlet page using dynamic name . i actually want to make an admin page in which admin can activate or deactivate intitutes at his will. so each active and inactive radio button has a name obtained from the database ie. a dynamic name.
my next servlet page is:
try {
Connection con=conn.connectionprovider.getDbConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from institutemaster");
//out.println("tom");
while(rs.next())
{
// out.print(" cat");
**if( request.getParameter(rs.getInt(2)+"").equals("a") )
{
int rs1=st.executeUpdate("update institutemaster set status='active' where instid="+rs.getInt(2)+"");
out.print("status=active");
}
else
{
int rs1=st.executeUpdate("update institutemaster set status='inactive' where instid="+rs.getInt(2)+"");
out.print("status=inactive");
}**
}
//out.print("done");
}
catch(Exception e){}
now in this , i am able to recieve and compare only the 1st radio button value
(see the highlighted area). it means that the only the first value through iteration is being sent from last page n other values are not.
any help please?

Program will not read my if statement

I am doing this project and I am almost done. It took me a while to actually get the code to actually run but I finally got it. My assignment was to make a HTML form, connect it to MySQL using JSP, and insert the values into the database or delete the values from the database. It is also password protected. Like I said I have gotten it to compile without error however the If statement I have implemented is not being picked up. I was wondering if you all could help me figure why this is happening. Im going to paste my HTML code then my JSP.
HTML CODE
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> Assignment 3 </title>
</head>
<body>
<h3> Song Name Form </h3>
<form action = "hgooding.jsp" method = "post">
<table border = "1">
<tr>
<td>Song Title: </td>
<td> <input type = "text" name = "song"/> </td>
</tr>
<tr>
<td>Artist </td>
<td> <input type = "text" name = "artist"/> </td>
</tr>
<tr>
<td>Password: </td>
<td> <input type = "password" name = "pass1"
size = "20"/> </td>
</tr>
</table>
<br>
<input type = "radio" name = "option" value = "add"/> Add
<input type = "radio" name = "option" value = "delete"/> Delete
<br>
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
JSP CODE
<%# page import = "java.sql.*" %>
<html>
<head> <title> Database jsp </title></head>
<body>
<%
String connectionURL = "jdbc:mysql://sql.njit.edu:3306/hg33";
Connection connection = null;
Statement stm = null;
ResultSet rst=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "hg33", "grapes34");
String song = request.getParameter("song");
String artist = request.getParameter("artist");
String action = request.getParameter("option");
String pass2 = request.getParameter("pass1");
Statement stminsert = null;
stminsert = connection.createStatement();
if (pass2 == "apples4")
{
if (request.getParameter("action").equals("add"))
{
String sqlupdate1=("INSERT INTO Songs VALUES('"+song+"', '"+artist+"')");
stm.executeUpdate(sqlupdate1);
out.println("Hi!");
}
if (request.getParameter("action").equals("delete"))
{
String sqlupdate2=("DELETE FROM Music WHERE Song =('"+song+"')");
stm.executeUpdate(sqlupdate2);
}
rst = stm.executeQuery("SELECT * from Music");
}
else
{
out.println( "Password is not correct!!!" );
}
out.println("insert attempted");
%>
</body>
</html>
I guess ur condition in if statement should be like this
if (action.equals("add")){.........................}
or
if (action == "add"){.........................}
instead of
if (request.getParameter("action").equals("add")){....................}
coz u catch option in action variable like this
String action = request.getParameter("option")