Search inside table MySql database with JSB - java

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.

Related

Why retrieve Data is not Update in jsp

I have three JSP as follows:
Employee_vendor_approve.jsp : which is retrieve Employee Details
update_employeeVendorLoginCredentials.jsp: Which is take reference of Employee_vendor_approve.jsp page for upadate process
update_process_employeeVendorLoginCredentials.jsp: is update retrieve data
from point 1 i can able to retrieve data but i unable to proceed point 2 and 3. where is problem i unable to find, when i click update link on Employee_vendor_approve.jsp, update_employeeVendorLoginCredentials.jsp showing blank here is my code
Employee_vendor_approve.jsp:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee and vendor approve Page</title>
</head>
<body>
<table border="1" align="center">
<tr>
<td>FIRST_NAME </td>
<td>LAST_NAME</td>
<td>ORGANIZATION_NAME</td>
<td>EMPLOYEE_ID</td>
<td>Approve</td>
<td>Status</td>
</tr>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con==DriverManager.getConnection("jdbc:oracle:thin:#173.18.114.213:1821:godb","ex","xe");
statement=con.createStatement();
String Sql="SELECT FIRST_NAME,LAST_NAME,ORGANISATION_NAME,EMPLOYEE_ID,APPROVE from REGISTRATION_EMPLOYEE where role in ('Employee','Vendor')";
resultSet=statement.executeQuery(Sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("FIRST_NAME")%></td>
<td><%=resultSet.getString("LAST_NAME")%></td>
<td><%=resultSet.getString("ORGANISATION_NAME")%></td>
<td><%=resultSet.getString("EMPLOYEE_ID")%></td>
<td><%=resultSet.getString("APPROVE")%></td>
<td>
update
</td>
</tr>
<%
}
//con.close();
%>
</table>
</body>
</html>
update_employeeVendorLoginCredentials.jsp:
<html>
<body>
<form method="post" action="update_process_employeeVendorLoginCredentials.jsp">
<table border="1">
<tr>
<th>FIRST_NAME </th>
<th>LAST_NAME</th>
<th>ORGANIZATION_NAME</th>
<th>EMPLOYEE_ID</th>
<th>Approve</th>
</tr>
<%
String employee_id=request.getParameter("employee_id");
int sumcount=0;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#173.18.114.213:1821:godb","ex","xe");
Statement st=con.createStatement();
String query="SELECT FIRST_NAME,LAST_NAME,ORGANISATION_NAME,EMPLOYEE_ID,APPROVE from REGISTRATION_EMPLOYEE where EMPLOYEE_ID="+employee_id;
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
%>
<tr>
<td><input type="text" name="FIRST_NAME" value="<%=rs.getString("FIRST_NAME")%>"> </td>
<td><input type="text" name="LAST_NAME" value="<%=rs.getString("LAST_NAME")%>"> </td>
<td><input type="text" name="ORGANISATION_NAME" value="<%=rs.getString("ORGANISATION_NAME")%>"> </td>
<td><input type="text" name="APPROVE" value="<%=rs.getString("APPROVE")%>"> </td>
<td><input type="hidden" name="EMPLOYEE_ID" value="<%=rs.getString(1)%>"></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Update" style="background-color:#49743D;font-weight:bold;color:#ffffff;"></td>
</tr>
<% }
}
catch(Exception ex)
{
}
%>
</table>
</form>
</body>
</html>
update_process_employeeVendorLoginCredentials.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:#173.18.114.213:1821:godb","ex","xe");
String EMPLOYEE_ID=request.getParameter("EMPLOYEE_ID");
String first_name=request.getParameter("FIRST_NAME");
String Last_name=request.getParameter("LAST_NAME");
String ORGANISATION_NAME=request.getParameter("ORGANISATION_NAME");
String Approve_status=request.getParameter("APPROVE");
if (EMPLOYEE_ID!=null)
{
// Connection con = null;
PreparedStatement ps = null;
int personID = Integer.parseInt(EMPLOYEE_ID);
try
{
String Sql="update REGISTRATION_EMPLOYEE set APPROVE='Y' where EMPLOYEE_ID="+EMPLOYEE_ID;
ps=con.prepareStatement(Sql);
ps.setString(1, Approve_status);
int i=ps.executeUpdate();
if(i>0)
{
out.print("Record Updated Successfully");
}
else
{
out.print("There is a problem in updating Record.");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
%>
</body>
</html>
In Employee_vendor_approve.jsp: you set parameter name called id
update
but in update_employeeVendorLoginCredentials.jsp you get the parameter via employee_id
String employee_id=request.getParameter("employee_id");
They do not keep the same,so you get empty value.In order to solve this,you can change it to below:
String employee_id=request.getParameter("id");//using id instead of employee_id
To the problem you can not update data,it's also due to you fetch wrong value in update_employeeVendorLoginCredentials.jsp:
<td><input type="hidden" name="EMPLOYEE_ID" value="<%=rs.getString(1)%>"></td> // you have get the wrong value for id
In order to let it work,change it as below:
<td><input type="hidden" name="EMPLOYEE_ID" value="<%=rs.getString("EMPLOYEE_ID")%>"></td>

how to delete single recodrs from multiple row records like gridview in jsp page

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 + "'";

can not update using JSP

can you help me resolve my problem?I use JSP to update but no action be occurred(insert and delete be OK).For example,I update cname from ASUS to SONY but when click on Update button,cname still be ASUS.
note that cid is auto_increment
Here is update method in DAO
public int updateComputer(Computer com) {
int n = 0;
try {
String sql = "UPDATE Computer SET cname=?, quantity=?, price=?,functions=? where cid=?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
// Parameters start with 1
preparedStatement.setString(1, com.getCname());
preparedStatement.setInt(2, com.getQuantity());
preparedStatement.setDouble(3, com.getPrice());
preparedStatement.setString(4, com.getFunc());
n = preparedStatement.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(ComputerDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return n;
}
here is updateComputer.jsp
<%#page import="java.sql.ResultSet"%>
<%#page import="dao.ComputerDAO"%>
<%#page import="entity.Computer"%>
<%#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>
<%
ComputerDAO comDAO = new ComputerDAO();
String cid = request.getParameter("cid");
ResultSet rs = comDAO.getData("Select * from Computer where cid=" + Integer.parseInt(cid));
Computer com = new Computer();
if (rs.next()) {
int id = rs.getInt(1);
String cname = rs.getString(2).trim();
int quan = rs.getInt(3);
double price = rs.getDouble(4);
String func = rs.getString(5).trim();
com = new Computer(id, cname, quan, price, func);
}
%>
<form name="form1" method="post" action="ProcessUpdateComputer.jsp">
<table width="400" height="252" border="0" align="center" cellpadding="2" cellspacing="2">
<caption>
<h2>Update Computer</h2>
</caption>
<tr>
<th width="29%" align="left" scope="row">Computer ID</th>
<td width="71%">
<input type="text" name="cid" id="cid" disabled="" value="<%= com.getCid()%>"></td>
</tr>
<tr>
<th width="29%" align="left" scope="row">Computer Name</th>
<td width="71%">
<input type="text" name="cname" id="cname" value="<%=com.getCname()%>"></td>
</tr>
<tr>
<th align="left" scope="row">Quantity</th>
<td>
<input type="text" name="quantity" id="quantity" value="<%=com.getQuantity()%>"></td>
</tr>
<tr>
<th align="left" scope="row">Price</th>
<td>
<input type="text" name="price" id="price" value="<%= com.getPrice()%>"></td>
</tr>
<tr>
<th align="left" scope="row">Functions</th>
<td>
<!--<input type="text" name="functions" id="functions" value="<%=com.getFunc()%>"></td>-->
<textarea name="functions" rows="8" id="functions" value="<%=com.getFunc()%>"></textarea></td>
</tr>
<tr>
<th align="right" scope="row"></th>
<td><input type="submit" name="button" id="button" value="Update">
<input type="hidden" name="service" id="service" value="<%= cid%>"></td>
</tr>
</table>
<p align="center">View Computer List</p>
</form>
</body>
</html>
Here is ProcessUpdateComputer.jsp
<%#page import="entity.Computer"%>
<%#page import="dao.ComputerDAO"%>
<%#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>
<%
ComputerDAO dao = new ComputerDAO();
String cname = request.getParameter("cname");
String quan = request.getParameter("quantity");
String price = request.getParameter("price");
String func = request.getParameter("functions");
int uquan = Integer.parseInt(quan);
double uprice = Double.parseDouble(price);
Computer com = new Computer(0, cname, uquan, uprice, func);
int i = dao.updateComputer(com);
if (i > 0) {
out.println("updated");
}
%>
<p>View Computer List</p>
</body>
</html>
Here you're missing the fifth parameter, the cid:
String sql = "UPDATE Computer SET cname=?, quantity=?, price=?,functions=? where cid=?";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
// Parameters start with 1
preparedStatement.setString(1, com.getCname());
preparedStatement.setInt(2, com.getQuantity());
preparedStatement.setDouble(3, com.getPrice());
preparedStatement.setString(4, com.getFunc());
preparedStatement.setString(5, com.getId());
n = preparedStatement.executeUpdate();
Here is not clear what you want to do, are you always trying to update the computer with cid=0?
Computer com = new Computer(0, cname, uquan, uprice, func);
int i = dao.updateComputer(com);
You'll probably want to retrieve the cid from the request, like the other params
String cid = request.getParameter("cid");

Unable to retrive the data from database. Getting a runtime error. here's an instance of my servlet DBController.java

servlet: DBController.java
java.sql.Statement statement = conn.createStatement();
ResultSet rs2=statement.executeQuery("select * from stud_db");
while(rs2.next())
{
int id2= rs2.getInt("id");
String name2= rs2.getString("name");
int age2=rs2.getInt("age");
String address2= rs2.getString("address");
float percentage2 = rs2.getFloat("percentage");
request.setAttribute("id",id2);
request.setAttribute("name",name2);
request.setAttribute("age", age2);
request.setAttribute("address",address2);
request.setAttribute("percentage", percentage2);
request.getRequestDispatcher("/next.jsp").include(request,response);
My jsp page
next.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>next page</title>
</head>
<body>
<center><h1>DATA SUCCESSFULLY ENTERED</h1></center>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<h2>Details are shown below </h2>
<body>
<form action="${pageContext.request.contextPath}/DBController" method="POST">
<table border="2">
<tr>
<td>ID</td>
<td>NAME</td>
<td>AGE</td>
<td>ADDRESS</td>
<td>PERCENTAGE</td>
</tr>
<c:forEach var="row" items="${result.rows}"> </c:forEach>
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.name}"/></td>
<td><c:out value="${row.age}"/></td>
<td><c:out value="${row.address}"/></td>
<td><c:out value="${row.percentage}"/></td>
</table>
</form>
<h1>Thank you..</h1>
</body>
</html>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.name}"/></td>
<td><c:out value="${row.age}"/></td>
<td><c:out value="${row.address}"/></td>
<td><c:out value="${row.percentage}"/></td>
</tr> // Check this
</c:forEach> // Also this
</table>
when you are fetching the value from the database you need to specify the column index and not the column name.
try this
Result r2= statement.executeQuery("select * from TABLE");
while(rs2.next())
{
int id2= rs2.getInt(1);
String name2= rs2.getString(2);
int age2=rs2.getInt(3);
String address2= rs2.getString(4);
float percentage2 = rs2.getFloat(5);
i have just taken an example of the sequence of the columns. you need to take the exact column number. i hope that works. :)
there is no collection named result(which you are trying to access in the for loop in jsp page) is defined anywhere in DbController so add following piece of code and see if it works.
try
{
conn = ConnectionManager.getConnection();
stmt = conn.createStatement();
res = stmt.executeQuery("select * from stud_db);
ArrayList Rows = new ArrayList(); //---->forgot to initialize another arraylist here. please check
while(res.next()){
ArrayList row = new ArrayList();
for (int i = 1; i <= 4; i++){
row.add(res.getString(i));
}
HttpSession session = request.getSession();
session.setAttribute("name", res.getString(2));
session.setAttribute("id", res.getString(1));
session.setAttribute("address", res.getString(3));
session.setAttribute("percentage", res.getString(4));
Rows.add(row);
}
request.getSession().setAttribute("results", Rows);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/DDLResults.jsp");
request.getRequestDispatcher("/next.jsp").include(request,response);
conn.close();
}
catch (SQLException se)
{
se.printStackTrace();
}
catch (Exception e)
{
throw new ServletException(e.toString());
}
}

unable to compile class for JSP

Iam working on a project in JSP using netbeans.
Iam getting the following error......but i didn't find the java any files..please provide me something.The error is:
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 205 in the generated java file
Syntax error, insert "Finally" to complete TryStatement
An error occurred at line: 206 in the generated java file
Syntax error, insert "}" to complete ClassBody
Stacktrace:
org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:92)
org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:439)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:349)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:327)
org.apache.jasper.compiler.Compiler.compile(Compiler.java:314)
org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:589)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
The files i used are:
addNewUser.jsp:
<%# page language="java" %>
<%# page session="true" %>
<%# page import="java.util.*" %>
<HTML>
<head>
<LINK href="styles.css" type="text/css" rel="stylesheet">
</head>
<SCRIPT LANGUAGE="JavaScript">
<!--
history.go(+1);
function validate(){
x = document.NewUser.uid;
y = document.NewUser.pwd;
z = document.NewUser.auth;
var ed=x.value;
var pd=y.value;
var ad=z.value;
var pattern = /^([a-zA-Z0-9\_\.]{4,10})$/;
var Apattern = /^([0-3]{1})$/;
if(!(pattern.test(ed))){
alert("Invalid username");
return false;
}
else if(!(pattern.test(pd))){
alert("Invalid password");
return false;
}
else if(!(Apattern.test(ad))){
alert("Invalid Authentication");
return false;
}
else
return true;
}
//-->
</SCRIPT>
<br><br>
<body Class=Grad>
<center>
<BR><BR><br><br>
<FONT FACE="Century Gothic">
<FONT size="2" color="blue" FACE="Century Gothic">
<FORM NAME="NewUser" ACTION="AddNewUser1.jsp" METHOD="POST" onsubmit="return validate()">
<TABLE Border=0 align=center>
<TR class=row_title ALIGN="center">
<TH COLSPAN="2"> Add user</TH>
</TR>
<TR class=row_even>
<TD>UserID * </TD>
<TD><input TYPE=text name=uid size="10" maxlength="10"></TD>
</TR>
<TR class=row_odd>
<TD>Password * </TD>
<TD><input TYPE=password name=pwd size="10" maxlength="20"></TD>
</TR>
<TD><input type=hidden name=auth value=2>
<TR class=row_even>
<TD><INPUT TYPE=submit name=submit value="Submit">
</TD>
<TD><INPUT TYPE=reset name=resett value="Reset" >
</TD>
</TR>
</TABLE>
<A align="center" href="Login.jsp">BACK TO HOME</A>
</FORM>
</BODY>
</HTML>
addNewUser1.jsp:
<%# page language="java" %>
<%# page session="true" %>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%# page import="java.util.Random" %>
<html>
<head>
<LINK href="styles.css" type="text/css" rel="stylesheet">
<SCRIPT LANGUAGE="JavaScript">
<!--
history.go(+1);
//-->
</SCRIPT>
</head>
<jsp:include page="MultiLevelmenu.htm"/><br><br><body Class=SC>
<center>
<BR><BR>
<FONT FACE="Century Gothic">
<!--Declaration of varaibles-->
<%! String errormsg ;%>
<%! String disluserid ;%>
<%! String dislpwd ;%>
<%! int auth ;%>
<%
/*Retreiving user id and password*/
disluserid = request.getParameter("uid");
if(disluserid == null)
disluserid = "";
dislpwd = request.getParameter("pwd");
if(dislpwd == null)
dislpwd = "";
String sauth = request.getParameter("auth");
if(sauth == null)
auth=0;
auth = Integer.parseInt(sauth);
//System.out.println(disluserid+dislnewpwd+dislpwd);
%>
<%
/*Declaration of variables*/
Connection con=null;
Statement stmt=null;
ResultSet rs=null;
String Userid,Password;
try
{
/*Getting the connection variable from session*/
con=(Connection)session.getAttribute("connection");
stmt = con.createStatement();
String Query = "SELECT * from student where studentid = \'"+disluserid+"\'";
System.out.println(Query);
rs = stmt.executeQuery(Query);
}
catch(Exception e)
{
System.out.println("Exception"+e);
/* If user provides valid username & password then update the new password to database*/
if(rs.next())
{%>
<script>
for(i=1;i<=6;i++) document.write("<br>");
</script>
<H3 align="center"> User already exists</H3>
<BR>
<center>
Back
</center>
<%
}
else{
String UpdateQuery =
"Insert into student values(\'"+disluserid+"\',\'"+dislpwd+"\',"+auth+")";
//System.out.println(UpdateQuery);
int rowsAffected=stmt.executeUpdate(UpdateQuery);
//System.out.println("Rows Affected = " + rowsAffected);
if(rowsAffected==1)
{%>
<script>
for(i=1;i<=10;i++) document.write("<br>");
</script>
<H3 align="center">User Created Successfully </H3>
Create Another User
<br/>
Home
<BR>
<%}
/* If user provides invalid password or username*/
else{%>
<script>
for(i=1;i<=6;i++) document.write("<br>");
</script>
<H3 align="center">Unable to create user please try again </H3>
<BR>
<% } %>
<%
}
%>
</FONT>
</center>
</BODY>
</html>
try {
/*Getting the connection variable from session*/
con=(Connection)session.getAttribute("connection");
stmt = con.createStatement();
String Query = "SELECT * from student where studentid = \'"+disluserid+"\'";
System.out.println(Query);
rs = stmt.executeQuery(Query);
} catch(Exception e) { System.out.println("Exception"+e);
In the above code section you are not completing the try's catch block.

Categories