Updating database with jquery ajax for jsp - java

I wish to create a simple script to store information dynamically without refreshing or redirecting to another page. I've sourced high and low for answers before coming here, and I followed this.
However, I'm still unable to get it to store data because I don't know where I've goen wrong. Also, I wish to ask the purpose of success: function(msg)
Thanks a lot!
Update 1: Got it to work after following Anoop's solutions. However, such a popup appears when the data is submitted
StaffReg.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Staff Registration</title>
</head>
<body>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Javascript --%>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#Register').click(function(e) {
e.preventDefault();
$.ajax({
url: "StaffRegAuth.jsp",
type: "post",
data: {
username: $('#username').val(),
password: $('#password').val(),
userGroup: $('#userGroup').val()
},
success: function(msg) {
alert(msg);
}
});
});
});
</script>
<%-- Main body --%>
<h1 align="center"> Account Registration: </h1>
<div align="center">
<table style="width = 30%" >
<tr>
<td> User Name: </td>
<td><input type="text" id="username"></td>
</tr>
<tr>
<td> Password: </td>
<td><input type="password" id="password"></td>
</tr>
<tr>
<tr>
<td> User Group: </td>
<td><select name = "userGroup" id="userGroup">
<option value="1">Administrator
</optin>
<option value="2">Clerk
</optin>
<option value="3">Operations
</optin>
<option value="4">Sales
</optin>
</select></td>
</tr>
<tr>
</table>
<input type="submit" value="Register" id="Register">
</div>
</body>
</html>
StaffRegAuth.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%-- Imports --%>
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%#page import="javax.servlet.*" %>
<%#page import="javax.servlet.http.*" %>
<%-- HTTP header --%>
<%response.addHeader("Cache-Control","no-cache");
response.addHeader("Pragma","no-cache");
response.addHeader("Expires","0");
%>
<%-- Variables that will be written --%>
<% String sUsername = request.getParameter("username");
String sPassword = request.getParameter("password");
int sUserGroup = Integer.parseInt(request.getParameter("userGroup"));
%>
<%-- Creating new staff account - writing --%>
<%
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conURL= "jdbc:odbc:HOD_DATA";
Connection con = DriverManager.getConnection(conURL);
Statement st = con.createStatement();
int status = st.executeUpdate("insert into Staff(username, password, user_group) values('"+sUsername+"','"+sPassword+"',"+sUserGroup+")");
if(status>0){
//out.println("Update sucessful");
}
else{
//out.println("Update unsuccessful");
}
st.close();
con.close();
}
catch(Exception e){
out.println(e);
}
%>
</body>
</html>

Remove the submit button and use a normal html button with Id as Register.
Modify your html input types and replace the name attribute with id attribute. Ex: use id="username" instead of name="username"
Debugging:
Use firebug to check what value is passed to server. Ensure the correct ajax request is submitted.
Hope it helps.

Related

Read file path from javascript variable and send it to form action?

code:
<script type="text/javascript">
function showFileName() {
var filename = document.getElementById("uploadFile");
}
</script>
OR
<script type="text/javascript">
var filename = document.getElementById("uploadFile");
</script>
OR
var filename="uploadedfilename";
<form name="AttachmentsForm" method="post" action="<%=Constants.WEB_APP_NAME%><%=Constants.SERVLET_NAME%>?para=ajaxRefTabUpload&action=add&uploadfilename="+filename+"" ENCTYPE="multipart/form-data">
<table class="innerBorderTable" width="100%">
<tr>
<td>Attach New File:</td>
<td>
<INPUT TYPE="FILE" NAME="uploadFile" width="120">
<input type="submit" class="button" value="Add Attachment">
</td>
</tr>
</table>
</form>
I tried 3 different approaches to pass it with +filename+ i am getting null with uploadfilename in action parameter
Please advise
use of scriptlets(<% %>) in JSP highly discouraged, use JSTL(<c:tags) or Expression Language(${})
to use JSTL in your jsp download jstl.x.x.jar file and add it to your buildpath.
then, add this
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
in top of jsp.
to resolve form action url you have:
<%=Constants.WEB_APP_NAME%><%=Constants.SERVLET_NAME%>
no need of any constants for that, instead use <c:url tag to resolve url like:
<c:url value="/yourServletUrl" var="postUrl"/>
<form action="${postUrl}" method="post" ...
i am getting null with uploadfilename in action parameter
because, you accessing javascript variable in html(&uploadfilename="+filename+"), instead do like:
jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<title>your title</title>
</head>
<body>
<c:url value="/yourServletUrl" var="postUrl"/>
<form id="AttachmentsForm"
method="post"
onSubmit="showFileName()"
action="${postUrl}para=ajaxRefTabUpload&action=add"
enctype="multipart/form-data">
<table class="innerBorderTable" width="100%">
<tr>
<td>Attach New File:</td>
<td>
<input type="file" name="uploadFile" width="120">
<input type="submit" class="button" value="Add Attachment">
</td>
</tr>
</table>
</form>
<script type="text/javascript">
function showFileName(e) {
if (e.preventDefault)
e.preventDefault();
var filename = document.getElementById("uploadFile");
alert('fileName: '+filename);
//here, attach filename to from action and continue your form submition by AJAX
// You must return false to prevent the default form behavior
return false;
}
}
</script>
</body>
</html>
Try something like:
function showFileName() {
document.forms[0].action ="<%=Constants.WEB_APP_NAME%>... //Here goes the expression you want to set the action to
}

how to submit the option selected from drop down list in jsp page to perform a mysql query

My project is StaffAllocation, and I want to retrieve information from the database. I'm very new and this is my very first project. I created a drop down list retrieving staffnames from one of my table. Now I want to perform a query action to view the details of the selected staffnames from the drop-down list. The following is the coding which i have, which is not correct:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*" %>
<%# page import="java.io.*" %>
<%# page import="java.lang.*" %>
<%# page import="javax.servlet.*" %>
<%# page import="javax.servlet.http.*" %>
<%ResultSet resultset =null; %>
<!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>Staff Details</title>
</head>
<BODY>
<form method=post>
<h3>Select Stafftype:</h3>
<p><input type="radio" name="Stafftype" value="Male"> Male</input></p>
<p><input type="radio" name="Stafftype" value="Female"> Female</input></p>
<input type="submit" value="Submit">
</form>
<%
try{
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/StaffAllocation? user=root&password=success");
Statement statement = connection.createStatement() ;
String Stafftype= request.getParameter("Stafftype");
out.print(Stafftype);
if(Stafftype.contentEquals("Male")){
resultset=statement.executeQuery("select * from tblstaffdetails where Stafftype= 'Male'");
}
else if(Stafftype.contentEquals("Female")){
resultset=statement.executeQuery("select * from tblstaffdetails where Stafftype= 'Female'");
}
else
{
System.out.println("your coding is wrong");
}
%>
<select> <% while(resultset.next()){ %>
<option><%= resultset.getString(2)%></option>
<%} %>
<%
String StaffName= request.getParameter("StaffName");
int staffId;
String subcode;
if(StaffName != null) {
resultset=statement.executeQuery("SELECT a.staffId, a.StaffName, b.subcode FROM tblstaffdetails a LEFT JOIN tblsubhandled b ON a.staffId = b.staffId where StaffName='request.getParameter('StaffName')'");
}
}
catch(Exception e)
{
out.println("wrong entry"+e);
}
%>
<form method = "get">
<br><br>
<input name="Submit" type="button" value="Submit">
</form>
</body>
</html>`
Tables:
tblstaffdetails -(1).staffId(2).StaffName(3).Stafftype(male or female)
tblsubhandled - (1).staffId(2).subcode
I have fiddled sample implementation for your reference. You can implement like that. All you need to do is include jQuery plugin. Sample code lke this,
$.ajax({
url : 'ur_servlet_url' + selValue,
type : "POST",
async : false,
success : function(data) {
//Sample data
var data = "<select id='child'>
<option value='11'>Value11</option></select>"
$("#fillValue").html(data);
}
});
You need to compose your java response like select tag and return it to your ajax response. Finally you can fill the second dropdown like that. Let me know if this helps.
<form method="post" action="select.jsp">
<select name="sell">
<option value="Alto">Alto</option>
<option value="Esteem">Esteem</option>
<option value="Honda City">Honda City</option>
<option value="Chevrolet">Chevrolet</option>
</select>
<br>
<input type="Submit" value="Submit">
</form>
<%
String st=request.getSelectedIndex("sell");
if(st!=null){
out.println("You have selected: "+st);
}
%>

how to display the names in a jsp page according to name

i have a page editpatient.jsp which includes a page patientlist.jsp. when you run editpatient.jsp then it displays all the records present in the database.I have a dropdown and also a search field to specify searches. So when i run editpatient.jsp then it displays all the records in the manner it is stored in DB. So i wanted to sort it according to name and display.So please tell me how to do the same. when you hit the name or email or city then it will sort accordingly
patientlist.jsp
<%# page import="java.util.*" %>
<%# page import="java.sql.*" %>
<%# page import="DB.*" %>
<%# 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>
<style type="text/css">
.evenRow{
height: 50px;
background-color: white;
text-transform: none;
text-shadow: none;
color: black;
}
.evenRow:hover
{
background-color: #C2FEF0;
}
.row{
height: 50px;
background-color: #E4E6E6;
text-transform: none;
text-shadow: none;
color: black;
}
.row:hover {
background-color: #C2FEF0;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<table style="border-collapse: collapse;overflow-x: scroll; width:97%">
<tr style="background-color:grey;height:50px">
<th style="min-width: 100px">
NAME
</th>
<th style="min-width: 100px">
CITY
</th>
<th style="min-width: 100px">
LAST VISIT
</th>
<th style="min-width: 100px">
MOBILE
</th>
<th style="min-width: 100px">
EMAIL
</th>
<th style="min-width: 100px">
STATUS
</th>
<th style="min-width: 100px">
VIEW
</th>
<th style="min-width: 100px">
EDIT
</th>
</tr>
<%
DataBaseConnection db = new DataBaseConnection();
Connection con = db.connet();
PreparedStatement pt = con
.prepareStatement("select * from Patient");
ResultSet rs = pt.executeQuery();
String searchBy = request.getParameter("searchBy");
String searchElement = request.getParameter("searchElement");
int count = 0;
int index = -1;
boolean name = false;
if ("city".equalsIgnoreCase(searchBy))
index = 9;//change the index to the index of the city
else if ("firstName".equalsIgnoreCase(searchBy))
index = 1;
else if ("lastName".equalsIgnoreCase(searchBy))
index = 2;
else if ("name".equalsIgnoreCase(searchBy)) {
index = 1;
name = true;
}
while (rs.next()) {
if (searchElement == null
|| ((searchElement.equals(rs.getString(index)) && !name) || (name && searchElement
.equalsIgnoreCase(rs.getString(index) + " "
+ rs.getString(index + 1))))) {
if (count++ % 2 == 0) {
%>
<tr class="evenRow" >
<td>
<%=rs.getString(1)%>
</td>
<td>
<%=rs.getString(2)%>
</td>
<td>
<%=rs.getString(3)%>
</td>
<td>
<%=rs.getString(4)%>
</td>
<td>
<%=rs.getString(5)%>
</td>
<td>
<%=rs.getString(6)%>
</td>
<td>
<form action="getPatientDetails.jsp"><input type="hidden" name="hidden" value="<%=count%>"/><input type="submit" value="view"></form>
</td>
<td>
<a onclick="renderEdit(<%out.println("edit");%>)"><%
out.println("edit");
%></a>
</td>
</tr>
<%
} else {
%>
<tr class="row">
<td>
<%=rs.getString(1)%>
</td>
<td>
<%=rs.getString(2)%>
</td>
<td>
<%=rs.getString(3)%>
</td>
<td>
<%=rs.getString(4)%>
</td>
<td>
<%=rs.getString(5)%>
</td>
<td>
<%=rs.getString(6)%>
</td>
<td>
<a onclick="renderView(<%out.println("view");%>)"><%
out.println("view");
%></a>
</td>
<td>
<a onclick="renderEdit(<%out.println("edit");%>)"><%
out.println("edit");
%></a>
</td>
</tr>
<%
}
}
}
%>
</table>
</body>
</html>
editpatient.jsp
<%# page import="java.util.*" %>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
<script type="text/javascript">
var request;
function getRequestObject()
{
if (window.ActiveXObject)
{
return(new ActiveXObject("Microsoft.XMLHTTP"));
}
else if (window.XMLHttpRequest)
{
return(new XMLHttpRequest());
}
else {
return(null);
}
}
function sendRequest()
{
request = getRequestObject();
request.onreadystatechange = handleResponse;
var address = "patientList.jsp?searchBy=" + document.getElementById("searchBy").value + "&searchElement="+ document.getElementById("searchElement").value;
request.open("GET", address, true);
request.send(null);
}
function handleResponse()
{
if (request.readyState == 4 && request.status == 200)
{
document.getElementById("table").innerHTML = request.responseText;
}
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Edit Patient</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<form id="f1" name="f1" method="post" onsubmit="ccheck();" >
<script>
$(document).ready(function() {
$("#datepicker").datepicker();
});
</script>
<section id="page" > <!-- Defining the #page section with the section tag -->
<header > <!-- Defining the header section of the page with the appropriate tag -->
<hgroup align="center">
<h3>Edit Patient</h3>
</hgroup>
</header>
<section id="articles"> <!-- A new section with the articles -->
<!-- Article 1 start -->
<div class="line"></div> <!-- Dividing line -->
<article id="article1"> <!-- The new article tag. The id is supplied so it can be scrolled into view. -->
<div class="articleBody clear">
search:
<select id="searchBy">
<option value="lastName">Last Name</option>
<option value="firstName">First Name</option>
<option value="name">Name</option>
<option value="city">City</option>
</select>
<input id="searchElement"/>
<input type="button" value="Search" onclick="sendRequest();"/>
</div>
</article>
<div id="table" align="center">
<jsp:include page="patientList.jsp" />
</div>
</article>
</section>
<footer> <!-- Marking the footer section -->
<div class="line"></div>
Go UP
</footer>
</section> <!-- Closing the #page section -->
<!-- JavaScript Includes -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="jquery.scrollTo-1.4.2/jquery.scrollTo-min.js"></script>
<script src="script.js"></script>
</form>
</body>
</html>
See if this links help you.
http://tympanus.net/codrops/2009/10/03/33-javascript-solutions-for-sorting-tables/
http://www.allmyscripts.com/Table_Sort/
Also let us know if you tried anything already
1.First store the dropdown /search value in Model class(using setter).
2.When you fired a query to fetch the details from database append the dropdown /search value which is stored in model class(using getter).
3.After fetch the value from DB render the dataTable .
Suggestion :
Please Follow the any one MVC architecture (Like Spring MVC architecture) to avoid the complexity of the your project.
Thanks you.
ASFAIK, The solution to your problem is ,you can use the jquery in jsp code, So you can find all Library's and include in it . There is no need to worry about sort and editing . Jquery has the Data Tables which has inbuilt API to sort the data in listed tables, its possible to edit the data in the table.
Reference Edit Reference Sort How to use data table in jsp pages
This is not exactly answers to question.
Try grid like jqGrid which takes care of things like sorting, searching, etc..

MVC - Sending Value of a field with request/session via a JSP

I'm trying to make a list of members of type Party, and linking their memberID to an update page which automatically gets the memberID of the one which was clicked.
I've already written code in the servlet to display a view of all of the members, with each of their IDs linked to a page called UpdateParty.jsp however what I want is for the ID clicked to be passed on with the request so that it can be used in the UpdateParty.jsp as a parameter so that the user does not have to enter it.
I'm using postgres for my SQL if anyone wants to know.
Servlet code which produces a list of all party members:
else if (request.getParameter("listallmembers") != null) {
try {
User sessionuser = (User) session.getAttribute("User");
String u = sessionuser.getUsername();
ArrayList<Party> p = new ArrayList<Party>();
ResultSet rs = this.findAllMembers(u);
while (rs.next()) {
Party party = new Party();
party.setMemberID(rs.getString("memberID"));
party.setPartyFirstname(rs.getString("partyFirstname"));
party.setPartySurname(rs.getString("partySurname"));
party.setUsername(rs.getString("username"));
p.add(party);
}
request.setAttribute("members", p);
request.getRequestDispatcher("ViewPartyMembers.jsp").forward(request, response);
} catch (Exception e) {
out.print(e);
e.printStackTrace(out);
}
Code for ViewPartyMembers.jsp:
<%#page import="HolidayExchange.Party"%>
<%#page import="HolidayExchange.User"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<%
List<Party> l = (List<Party>) request.getAttribute("members");
if(l!=null){
out.println("<table>");
out.println("<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>");
for(int i = 0; i < l.size();i++){
out.println("<tr><td>"+ l.get(i).getMemberID() +
"</td><td><a href='UpdateParty.jsp'>"+ l.get(i).getPartyFirstname() +
"</a></td><td>"+ l.get(i).getPartySurname() +
"</td><td>" + l.get(i).getUsername() + "</td>");
out.println("</tr>");
}
out.println("</table>");
}else{
%>
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
<%
}
%>
</body>
</html>
Here's something a little more sane for you. It uses the JSTL Expression Language and tag library.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>All Party Members</title>
</head>
<body>
<h1>View Party Members</h1>
<c:if test="${!empty members}">
<table>
<tr><th>Member ID</th><th>Firstname</th><th>Second Name</th><th>Associated User</th></tr>
<c:forEach items="${members}" var="member">
<tr><td>${member.memberID}</td>
<c:url value="link" value="UpdateParty.jsp">
<c:param name="memberId" value="${member.memberID}"/>
</c:url>
<td>${member.partyFirstname}</td>
<td>${member.partySurname}</td>
<td>${member.username}</td>
</tr>
</c:forEach>
</table>
</c:if>
<c:if test="${empty members}">
<form action="PartyServlet" method="get">
<input type="hidden" name="listallmembers" value="1" /><br />
<input type="submit" value="Show all Members" />
</form>
</c:if>
</body>
</html>
If you want the ID to be available on the UpdateParty.jsp your link should look like:
<a href='UpdateParty.jsp?id=" + l.get(i).getMemberID() + "'>"+ l.get(i).getPartyFirstname()"</a>
So the id property will be available in the JSP as a request parameter.
Anyway, I recommend you not use scriptlet in your JSP and instead point directly to a JSP point to a Controler/Action

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