I have a table where I display items from database. In first ResultSet I have created an dropdown menu that let you choose if you want item to be available or not. But, because I have created it in first ResultSet rs, I cannon use it in second ResultSet rs1. Problem is in this line:
if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno"))
And here is the whole code:
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Stil/cssstil.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Prikaz oružja</title>
</head>
<body>
<h1>Prikaz oruzja</h1>
<%
out.print("<p align = \"center\">Administrator <a style=\"color:red;\">" + session.getAttribute("user") + "</a></p>");
%>
<table align = "center" bgcolor = "darkgrey" border = "1" cellpadding="3" cellspacing="1">
<tr>
<td>
<p style = "color: black;">Naziv</p>
</td>
<td>
<p style = "color: black;">Opis</p>
</td>
<td>
<p style = "color: black;">Cena</p>
</td>
<td>
<p style = "color: black;">Dostupnost</p>
</td>
<td>
</td>
</tr>
<%
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/CS230-Projekat", "root", "123");
Statement statement = connection.createStatement();
String sql = "SELECT * FROM oruzje";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
%>
<tr bgcolor="grey">
<td><%=rs.getString("naziv")%></td>
<td><%=rs.getString("opis")%></td>
<td><%=rs.getString("cena")%></td>
<%
if (rs.getString("dostupnost").equals("1")) {
out.print("<td><p style = \"color: green; font-size: 20px\">Dostupno</p></td>");
} else {
out.print("<td><p style = \"color: red; font-size: 20px\">Nedostupno</p></td>");
}
%>
<%
int a = rs.getInt("dostupnost");
if (a == 1) {
out.print("<td><select name=\"" + rs.getString("naziv") + "polje\"><option value = \"Dostupno\">Dostupno</option><option value = \"Nedostupno\">Nedostupno</option></select></td>");
} else {
out.print("<td><select name=\"" + rs.getString("naziv") + "polje\"><option value = \"Dostupno\">Dostupno</option><option value = \"Nedostupno\">Nedostupno</option></select></td>");
}
}
%>
</tr>
<tr><td></td><td></td><td></td><td></td>
<td align=center>
<form method="post">
<% Statement statement1 = connection.createStatement();
int bre;
ResultSet rs1 = statement.executeQuery(sql);
while (rs1.next()) {
if (request.getParameter(rs1.getString("naziv") + "polje").equals("Nedostupno")) {
bre = statement1.executeUpdate("UPDATE oruzje SET dostupnost = 0 WHERE naziv='" + rs1.getString("naziv") + "'");
} else {
bre = statement1.executeUpdate("UPDATE oruzje SET dostupnost = 0 WHERE naziv='" + rs1.getString("naziv") + "'");
}
}
} catch (Exception e) {
e.printStackTrace();
}
%>
<input type="submit" value="Apply" name="Apply" />
</form>
</td>
</tr>
</table>
<p style=" position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;"><img src = "Slike/home.png" alt = "home"/></p>
</body>
First, I'll split your code in Servlets and JSP and show you why this is a better way to go.
Your view (assuming is called "foo.jsp"):
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!-- adding JSTL to your project -->
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Stil/cssstil.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Prikaz oružja</title>
</head>
<body>
<h1>Prikaz oruzja</h1>
<p align="center">
Administrator <span style="color:red"><c:out value="${user}" /></span>
</p>
<!--
In this case, the form should wrap all your table
since you want to process all the input elements
inside it. Otherwise, you will update the entire data
rather than update per entity.
-->
<form method="post">
<table align="center" bgcolor="darkgrey" border="1" cellpadding="3" cellspacing="1">
<th>
<td>
<p style = "color: black;">Naziv</p>
</td>
<td>
<p style = "color: black;">Opis</p>
</td>
<td>
<p style = "color: black;">Cena</p>
</td>
<td>
<p style = "color: black;">Dostupnost</p>
</td>
<td>
</td>
</th>
<c:forEach items="${oruzjeList}" var="oruzje">
<tr bgcolor="grey">
<td>${oruzje.naziv}</td>
<td>${oruzje.opis}</td>
<td>${oruzje.cena}</td>
<td>
<p style="color: green; font-size: 20px">
<!-- printing the value dynamically in view -->
<c:out value="${oruzje.dostupnost == '1' ? 'Dostupno' : 'Nedostupno'}" />
</p>
</td>
<td>
<!--
oruzje.naziv should be an ID, not the "unique name"
because a name could contain empty spaces which
will break the name of the component
here I use id but you will replace it with your ID
-->
<select name="polje_${oruzje.id}">
<option value="1" ${oruzje.dostupnost == '1' ? 'selected' : ''}>Dostupno</option>
<option value="0" ${oruzje.dostupnost == '0' ? 'selected' : ''}>Nedostupno</option>
</select>
<!--
Additionally, we need to obtain the respective id for
the row to be updated.
We will use a hidden input field which uses the ID
-->
<input type="hidden" name="hidId_${oruzje.id}" value="${oruzje.id}" />
</td>
</tr>
</c:forEach>
<tr>
<td></td><td></td><td></td><td></td>
<td>
<input type="submit" value="Apply" />
</td>
</tr>
</table>
</form>
<p style="position: absolute; bottom: 0; left: 0; width: 100%; text-align: center;">
<img src="Slike/home.png" alt="home"/>
</p>
</body>
</html>
This assumes you have an entity that supports that maps to your database table:
public class Oruzje {
private int id;
private String naziv;
private String opis;
private String cena;
private String dostupnost;
//propers getters and setters for your fields
}
Now, your Servlet:
//yes, a Servlet can map directly to your JSP
//there's no problem using this approach
#WebServlet("/foo.jsp")
public class OruzjeServlet extends HttpServlet {
//I won't go far with more classes
//nor with other improvements to the code
//I'll write the basic stuff here in Servlet
//this method should be in an utility class
//to provide reusability
private void closeResource(Closeable resource) {
try {
if (resource != null) {
resource.close();
}
} catch (IOException e) {
//silent exception
}
}
//this method should also be in an utility class
//and should recover the connection from a DataSource
//instead of creating the physical connection everytime
private Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/CS230-Projekat", "root", "123");
} catch (Exception e) {
//this should be splitted for better handling
//but I leave this up to you
//handle the exception
//very basic handling
e.printStacktrace();
}
}
//this method should be in a proper DAO class
//reusing a connection for execution of multiple statements
private List<Oruzje> getOruzjeList(Connection con) {
List<Oruzje> oruzjeList = new ArrayList<Oruzje>();
Statement statement = null;
ResultSet rs = null;
try {
statement = connection.createStatement();
String sql = "SELECT * FROM oruzje";
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
Oruzje oruzje = new Oruzje();
oruzje.setId(rs.getInt("id")); //use the real column
oruzje.setNaziv(rs.getString("naziv"));
oruzje.setOpis(rs.getString("opis"));
oruzje.setCena(rs.getString("cena"));
oruzje.setDostupnost(rs.getString("dostupnost"));
oruzjeList.add(oruzje);
}
} catch (SQLException e) {
//again, handle the exception
e.printStacktrace();
} finally {
closeResource(rs);
closeResource(statement);
}
return oruzjeList;
}
//this method will be executed when a client (browser)
//tries to enter to your foo.jsp page
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connection con = getConnection();
List<Oruzje> oruzjeList = getOruzjeList(con);
closeResource(con);
//setting the oruzjeList variable as attribute
//this will feed the ${oruzjeList} used in the
//<c:forEach>
request.setAttribute("oruzjeList", oruzjeList);
//now, forward the view to the right view (JSP)
//it is not a redirect
request.getRequestDispatcher("/foo.jsp").forward(request, response);
}
//this method will be executed when user selects "Apply"
//option in the view (the JSP)
//because you stated that the method to submit the <form>
//is POST
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//now, we just retrieve the necessary parameters and process the data
//sent from the form
Connection con = getConnection();
List<Oruzje> oruzjeList = getOruzjeList(con);
//each ? is a parameter in the query
//starting at index 1
String updateSql = "UPDATE oruzje SET dostupnost = ? WHERE id = ?";
PreparedStatement pstmt = con.prepareStatement();
for(Oruzje oruzje : oruzjeList) {
//this is where the static part of the name becomes handy
String theId = request.getParameter("hidId_" + oruzje.getId());
String theDostupnost = request.getParameter("polje_" + oruzje.getId());
//I'll avoid basic validation like
//if (theId == null || "".equals(theId))
//right to the update!
//setting the first parameter: dostupnost = ?
pstmt.setString(1, theDostupnost);
//setting the second parameter: ID = ?
//since it's an int, parsing the String to int
pstmt.setInt(2, Integer.parseInt(theId));
//perform the update for the current ID and Dostupnost
pstmt.execute();
}
//at the end, closing the resources
closeResource(pstmt);
//this is cumbersome but just to make sure
//the data was updated successfully
oruzjeList = getOruzjeList(con);
closeResource(con);
//similar to the doGet, we will forward to the view
request.getRequestDispatcher("/foo.jsp").forward(request, response);
}
}
More info:
How to avoid Java code in JSP files?
StackOverflow JSTL Wiki
StackOverflow EL Wiki
Difference between JSP forward and redirect
Sending a variable from Servlet to JSP
Retrieve values from JDBC and use JSTL tags to call the methods
Is it a good idea to put jdbc connection code in servlet class?
Difference between Statement and PreparedStatement
Related
As a part of my project, I started a student monitoring system. As a part of this, I want to insert the student details into the database. I want to insert entered details into database using a prepared statement. In this process I faced this issue. How to solve?
The code is as follows.
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<html>
<body bgcolor = "pink">
<%!
Connection con;
PreparedStatement ps;
public void jspInit()
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection( "jdbc:oracle:thin:#localhost:1521:XE","system","sai");
ps = con.prepareStatement("insert into list(?,?,?,?,?,?)");
}
catch(Exception ex){ex.printStackTrace();}
}
%>
<%
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String ID = request.getParameter("ID");
String gender = request.getParameter("gender");
String phone = request.getParameter("phone");
String email = request.getParameter("email");
%>
<h2 align = "center"><font color = "red">Your Entered Details::</font></h2>
<table align = "center" border = "1px solid black" cellspacing = "2px" cellpadding="5px">
<tr>
<td><b>Field</b></td>
<td><b>data</b></td>
</tr>
<tr>
<td><b>Firstname</b> </td>
<td><%=firstname%></td>
</tr>
<tr>
<td><b>Lastname</b></td>
<td><%=lastname%></td>
</tr>
<tr>
<td><b>Student ID</b></td>
<td><%=ID%></td>
</tr>
<tr>
<td><b>Gender </b></td>
<td><%=gender%></td>
</tr>
<tr>
<td><b>Phone </b></td>
<td><%=phone%></td>
</tr>
<tr>
<td><b>Email</b></td>
<td><%=email%> </td>
</tr>
</table>
<%
try
{
ps.setString(1,firstname);
ps.setString(2,lastname);
ps.setString(3,ID);
ps.setString(4,gender);
ps.setString(5,phone);
ps.setString(6,email);
int i = ps.executeUpdate();
if(i>0)
{
out.println("<h3 align = 'center'><font color = 'red'>successfully registered</font></h3>");
out.println("<h4 align = 'center'>Click here to.! -> <a href='http://localhost:9999/kaushik/index.html'>Go back</a></h4>");
}
else
{
out.println("<h3 align = 'center'><font color = 'red'>Unable to register</font></h3>");
out.println("<h4 align = 'center'>please try again.! -> <a href='http://localhost:9999/kaushik/insert.html'> click here</a></h4>");
}
}
catch(Exception ex){out.println("An exception occurred: " + ex);}
%>
<%!
public void jspDestroy()
{
try
{
ps.close();
con.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>
</body>
</html>
I think the is no problem in the variables set (firstname, lastname, etc.) as those values are successfully being displayed in the table.
So, the ps.setString(...) is not working because ps is set to null. I created the table in Oracle database. How to solve this issue? What is the error in my program?
I am having some trouble figuring out why I am getting an error with my code. Below is my JSP file (the problem is with the second form):
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Book Drivers</title>
</head>
<body>
<h1>Book Demands</h1>
<form method="POST" action="BookDriver.do">
<br>View a table </br>
<input type="radio" name="tbl" value="ListTodaysDemands">List Todays Demands<br />
<input type="radio" name="tbl" value="ListAllDemands">List All Demands<br />
<input type=submit value="Go!"> <br />
</form>
</body>
<body>
<h2>Demands</h2>
<%=(String)(request.getAttribute("query"))%>
</body>
<body>
<h2>Journeys</h2>
<%=(String)(request.getAttribute("query1"))%>
</body>
<body>
<h2>Drivers</h2>
<%=(String)(request.getAttribute("query2"))%>
</body>
<body>
<h2>Book taxi</h2>
<form method="POST" action="BookDriver.do">
<table>
<tr>
<th></th>
<th>Please provide your following details</th>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" name="address"/></td>
</tr>
<tr>
<td>Destination:</td>
<td><input type="text" name="destination"/></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" name="date"/></td>
</tr>
<tr>
<td>Time:</td>
<td><input type="text" name="time"/></td>
</tr>
<tr>
<td> <input type="submit" value="Book"/></td>
</tr>
</table>
</form>
</body>
Below is my controller:
public class BookDriver extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
LocalDate date = LocalDate.now();
String qry1 = "select * from CUSTOMER";
String qry2 = "select * from DRIVERS";
String qry3 = "select * from DEMANDS where date = '"+date+"'";
String qry4 = "select * from DEMANDS";
String qry5 = "select * from JOURNEY";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
//String qry4 = "SELECT Drivers.Name, Drivers.Registration FROM Drivers LEFT JOIN Journey ON Journey.Registration = Drivers.Registration LEFT JOIN Demands ON Demands.Date = Journey.Date LEFT JOIN Demands ON Demands.Time = Journey.Time WHERE Demands.id IS NULL";
response.setContentType("text/html;charset=UTF-8");
HttpSession session = request.getSession(false);
Jdbc dbBean = new Jdbc();
dbBean.connect((Connection)request.getServletContext().getAttribute("connection"));
session.setAttribute("dbbean", dbBean);
if((Connection)request.getServletContext().getAttribute("connection")==null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
else if (request.getParameter("tbl").equals("ListTodaysDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current journeys";
try {
msg = dbBean.retrieve(qry3);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
else if (request.getParameter("tbl").equals("ListAllDemands")){
String msg="No current demands";
String msg2="No current journeys";
String msg3="No current drivers";
try {
msg = dbBean.retrieve(qry4);
msg2 = dbBean.retrieve(qry5);
msg3 = dbBean.retrieve(qry2);
} catch (SQLException ex) {
Logger.getLogger(BookDriver.class.getName()).log(Level.SEVERE, null, ex);
}
request.setAttribute("query", msg);
request.setAttribute("query1", msg2);
request.setAttribute("query2", msg3);
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
///////////THIS PART NOT WORKING//////////////////////////
String [] query = new String[5];
query[0] = (String)request.getParameter("name");
query[1] = (String)request.getParameter("address");
query[2] = (String)request.getParameter("destination");
query[3] = (String)request.getParameter("date");
query[4] = (String)request.getParameter("time");
Jdbc jdbc = (Jdbc)session.getAttribute("dbbean");
if (jdbc == null)
request.getRequestDispatcher("/WEB-INF/conErr.jsp").forward(request, response);
if(query[0].equals("") ) {
request.setAttribute("msg", "Username cannot be NULL");
}
request.getRequestDispatcher("/WEB-INF/bookDemands.jsp").forward(request, response);
}
The first form in the JSP works absolutely fine, the issue is with the second form. Whenever I use the button "Book" I get a null pointer exception and I cannot figure out why and if I comment out all of the code to due with the first form in the servlet, then it no longer throws the exception and it works fine.
I would really appreciate some help with this as I have now spent hours searching for a solution online and i'm still very much struggling to solve the problem.
Cheers,
Use request.getParameterValues("name").. and same for others too maybe the current value be null
I have built a page of jsp where I have taken inputs from the user and created a table from that input now I have to show that table on another page and also I have to create that table in mysql simultaneously through Java.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Dynamic table</title>
<script src ="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<SCRIPT language="javascript">
var counter=2;
function addRow(tableID){
var dynamicVal = 'row'+counter;
$('#dataTable').append('\
<TR>\
<TD><INPUT type="checkbox" name="'+dynamicVal+'_chk" id="'+dynamicVal+'_chk"/></TD>\
<TD><INPUT type="text" name="'+dynamicVal+'_col" id="'+dynamicVal+'_col" required/></TD>\
<TD>\
<SELECT name="'+dynamicVal+'_datatype" id="'+dynamicVal+'_datatype">\
<OPTION value="int">INT(40)</OPTION>\
<OPTION value="var">VARCHAR(40)</OPTION>\
<OPTION value="char">CHAR(40)</OPTION>\
</SELECT>\
</TD>\
</TR>');
counter++;
}
function deleteRow(tableID){
/*$('#dataTable').find('[INPUT type="checkbox"]').each(function(){\
if($this).prop("checked") == true({
($this).closest('tr').remove();
}
});*/
$('#dataTable').find('tr').each(function(){
if($(this).find('input[type="checkbox"]').prop('checked') == true){
$(this).remove();
}
});
}
function createJSON() {
var obj ={};
obj.table_name=$("input[id=table_name]").val();
var rowcolms = {};
var rowcollection = [];
$('#dataTable').find('tr').each(function(){
var row = {};
row.colName=$(this).find('input[type="text"]').val();
row.dataType = $(this).find('select').val();
rowcollection.push(row);
});
obj.tablecolms=rowcollection;
/*var col_name = $(this).val("text");
var datatype = $(this).type("select");
item = {}
item ["text"] = "col_name" ;
item ["select"] = "datatype";
jsonObj.push(item);
});
$*/
console.log(obj);
}
function ajaxcall(){
$.get.json({
url: Createdatabase,
type:"post",
data: jsonObj,
success: function(data){
console.log(data);
}
});
}
</SCRIPT>
</head>
<style>
body {
background-color : #D3D3D3;
margin: 0;
padding: 0;
}
h4 {
color : #000000;
text-align : center;
font-family: "SIMPSON";
}
form {
width: 300px;
margin: 0 auto;
}
</style>
<body>
<form>
<h4>Create Your Table</h4>
<form action="servlet/createdatabase" method="post">
Table Name: <input type="text" name="table_name" id="table_name"required>
<input type="submit" value="Submit"><br><br>
<h4>Design Your Table</h4>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<TABLE id="dataTable" name="dataTable" width="350px" border="1">
<TR>
<TD><INPUT type="checkbox" name="row1_chk" id="row1_chk"/></TD>
<TD><INPUT type="text" name="row1_col" id="row1_col" required/></TD>
<TD>
<SELECT name="row1_datatype" id="row1_datatype" type="select">
<OPTION value="int">INT(40)</OPTION>
<OPTION value="var">VARCHAR(40)</OPTION>
<OPTION value="char">CHAR(40)</OPTION>.
</SELECT>
</TD>
</TR>
</TABLE><br>
<input type="button" value="Create Table" onclick="ajaxcall'">
</form>
</body>
</html>
So please can anyone tell that how can I create this table on another page and also in the format of tables and create this table in mysql?
The connection between JSP and MySQL: The below code explains creating a connection first.
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
to display data on the second page, you need to connect to DB again, then retrieve the data , for more information check out this link
mysql and jsp
This is for creating a table from JSP, connection is also established with mysql
<%# page import="java.sql.*" %>
<HTML>
<HEAD>
<TITLE>Creating a Table</TITLE>
</HEAD>
<BODY>
<H1>Creating a Table</H1>
<%
Connection connection = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
connection = DriverManager.getConnection("jdbc:odbc:data", "userName", "password");
Statement statement = connection.createStatement();
String command = "CREATE TABLE Employees (ID INTEGER, Name CHAR(50));";
statement.executeUpdate(command);
} catch (Exception e) {
out.println("An error occurred.");
}
%>
The Employees table was created.
</BODY>
</HTML>
I'm a beginner programmer, I already build page for data entry and page show all entries, but now I want to show specific row inside the table, which code can help me?
My table columns: fullname - email - Phone - education
I want to search by email to show the other data in one page.
I found this code on internet:
<%#page import="java.sql.*"%>
<% Class.forName("com.mysql.jdbc.Driver");%>
<%#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>
<%!
public class Showit {
String URL = "jdbc:mysql://localhost/regdata";
String USERNAME = "root";
String PASSWORD = "admin";
Connection conn = null;
PreparedStatement selectRegister = null;
ResultSet resultSet = null;
public Showit() {
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
selectRegister = conn.prepareStatement(
"SELECT a.fullname, a.email,"
+ " FROM mainr a,"
+ "WHERE a.fullname = ?"
+ "AND a.email = ?");
} catch (Exception e) {
e.printStackTrace();
}
}
public ResultSet getShowit(String fullname, String email) {
try {
selectRegister.setString(1, fullname);
selectRegister.setString(2, email);
resultSet = selectRegister.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return resultSet;
}
}
%>
<%
String fullname = new String();
String email = new String();
if (request.getParameter("fullname") != null) {
fullname = request.getParameter("fullname");
}
if (request.getParameter("email") != null) {
fullname = request.getParameter("email");
}
Showit showit = new Showit();
ResultSet showits = showit.getShowit(fullname, email);
%>
<table border="1">
<tbody>
<tr>
<td>Full Name</td>
<td>Email</td>
<td>Title</td>
</tr>
<% while (showits.next()) {%>
<tr>
<td><%= showits.getString("fullname")%></td>
<td><%= showits.getString("email")%></td>
<td><%= showits.getString("Phone")%></td>
</tr>
<% }%>
</tbody>
</table>
</body>
</html>
which connect with this page:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.Scanner" %>
<% Class.forName("com.mysql.jdbc.Driver");%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search</title>
</head>
<body>
<form name="search" action="display.jsp" method="POST">
<table border="0">
<tbody>
<tr>
<td>Full Name</td>
<td><input type="text" name="fullname" value="" size="50" /></td>
</tr>
<tr>
<td>E-Mail</td>
<td><input type="text" name="email" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Reset" name="reset" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
but it's not work.
The issue may be with this line:
fullname = request.getParameter("email");
Note that you are assigning the email parameter to the fullname variable.
first what i see is that the Query is wrong. Remove the , after the table alias "a" (here line 2) like this:
"SELECT a.fullname, a.email,"
+ " FROM mainr a"
+ "WHERE a.fullname = ?"
+ "AND a.email = ?");
There is also an issue here:
<td><%= showits.getString("Phone")%></td>
You did not include Phone in the SELECT statement, so it will not exist in the ResultSet.
I am trying to edit and delete a single record from multiple records.Here below is my sample record displaying on jsp page,
I can edit the record for each row easily using below code,
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.util.List" %>
<%# page import="java.util.Iterator" %>
<%#page import="java.sql.ResultSet"%>
<!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>Insert title here</title>
<script src="jquery1.11.0.min.js"></script>
</head>
<body>
<script type="text/javascript">
function editRecording(task_id) {
//alert(task_id)
url = "EditRecord";
window.location="/RTTSchecking/"+url+"?task_id="+task_id;
}
</script>
<table align="center" border="1px" width="80%" >
<thead>
<tr>
<th>User_Id</th>
<th>Class</th>
<th>Subject</th>
<th>Chapter</th>
<th>Planned_Features</th>
<th>Planned_Date</th>
</thead>
<%Iterator itr;%>
<%List data = (List) request.getAttribute("TaskData");
for(itr = data.iterator(); itr.hasNext();)
{
%>
<tr>
<% String s = (String) itr.next();
%>
<td style="background-color: yellow;">
<input type="text" name="tid" value="<%=s %>"></td>
<td><input type="text" name="tid" value="<%=itr.next() %>"></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><%=itr.next() %></td>
<td><input type="button" value="edit" name="<%=s%>" onclick="editRecording(this.name);"></td>
<td><input type="button" value="delete" name="<%=s%>" onclick="deleteRecording(this.name);"></td>
<% } %>
</tr>
</table>
</body>
</html>
EditREcord(servlet):
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
String a=request.getParameter("task_id");
convty = new Connectivity();
con = convty.setConnection();
st = con.createStatement();
query = "select * from task_table where task_id='"+a+"'";
rset = convty.getResultSet(query, con);
}
catch(Exception e) {
}
finally {
request.setAttribute("EditData", rset);
RequestDispatcher dd= request.getRequestDispatcher("editdata.jsp");
dd.forward(request, response);
out.close();
//out.println(""+tid);
}
}
Above code working fine.But my problem is, i want to delete record based on User_id, Class, Subject, Chapter and Planned_Date so how can i get these values from single row (which want to delete row)?
how to achive this below code?,
<script type="text/javascript">
function deleteRecording(User_id,Class,Subject,Chapter,Date) {
//alert(task_id,Class,Subject,Chapter,Date)
url = "EditRecord";
window.location="/RTTSchecking/"+url+"?user_id="+User_id+"&Tclass="+Class+"&subject="+Subject+"&chapter="+Chapter+"&date="+Date;
</script>
once if i achieved above code then i can easily delete selected single record from multiple rows using below code,
try {
String uid=request.getParameter("user_id");
String class=request.getParameter("Tclass");
String sub=request.getParameter("subject");
String chap=request.getParameter("chapter");
String date=request.getParameter("date");
convty = new Connectivity();
con = convty.setConnection();
st = con.createStatement();
query = "delete from task_table where User_id='"+uid+"' and class='"+class+"' and subject='"+sub+"' and chapter='"+chap+"' and date='"+date+"'";
st.executeUpdate(query);
}
catch(Exception e) {
}
Note : I can do delete records using delete from task_table where User_id='"+uid+"';
but how to do with query = "delete from task_table where User_id='"+uid+"' and class='"+class+"' and subject='"+sub+"' and chapter='"+chap+"' and date='"+date+"'";
I hope someone will help me out.
Once you delete data from database that means it's deleted.
You just need to reload that page again on click of delete.
I hope you've found the solution to your problem by now. But in case you haven't, I ran into the same problem today, and after many experiments, I came up with the following syntax for deleting a row using multiple criteria:
" DELETE FROM table_name WHERE " +
" first_db_field_name = '" + matching_variable_name + "'" +
" and next_db_field_name = '" + next_matching_variable_name + "'" +
" and last_db_field_name = '" + last_matching_variable_name + "'";