Retaining values of variables after successive form submission in JSP [duplicate] - html

This question already has answers here:
How can I retain HTML form field values in JSP after submitting form to Servlet?
(2 answers)
Closed 7 years ago.
I have written following two jsp files. First file i.e. submit.jsp has form where user submits her query and her city and latitude and longitude are recorded and she is forwarded to another jsp page which also has a form where she can again submit her query as many times as she wants and I want the values of city , latitude and longitude to be retained but they are getting reset. The code of the two files are as follows:
submit.jsp
<%# page contentType="text/html; charset=iso-8859-1" language="java" %>
<html>
<head>
<script type="text/javascript">
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function displayLocation(latitude,longitude){
var request = new XMLHttpRequest();
var method = 'GET';
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
var async = true;
request.open(method, url, async);
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
var data = JSON.parse(request.responseText);
var address = data.results[0];
//document.write(address.formatted_address);
var city=document.getElementById("city");
var n = address.formatted_address.split(",");
city.value = n[n.length-3];
}
};
request.send();
};
function showPosition(position){
//var x = document.getElementById("demo");
var latitude=document.getElementById("latitude"),longitude=document.getElementById("longitude");
//x.innerHTML="+" + position.coords.latitude + "+" + position.coords.longitude;
latitude.value = position.coords.latitude;
longitude.value = position.coords.longitude;
displayLocation(latitude.value,longitude.value);
}
</script>
</head>
<body onload="getLocation()">
<form name="frm" method="post" action="process.jsp">
<input type="text" name="myQuery" placeholder="Type here">
<input name="latitude" id="latitude" type="hidden">
<input name="longitude" id="longitude" type="hidden">
<input name="city" id="city" type="hidden">
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
process.jsp
<%# page contentType="text/html; charset=iso-8859-1" language="java" %>
<%! String city; String latitude; String longitude; %>
<form name="frm" method="post" action="process.jsp">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="22%"> </td>
<td width="78%"> </td>
</tr>
<tr>
<td> </td>
<td><input type="text" name="myQuery" placeholder="Type here"></td>
</tr>
<tr>
<td> </td>
<input name="latitude" id="latitude" type="hidden" value="${latitude}" >
<input name="longitude" id="longitude" type="hidden" value="${longitude}" >
<input name="city" id="city" type="hidden" value="${city}" >
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
<%
String query=request.getParameter("myQuery");
String city=request.getParameter("city");
String latitude=request.getParameter("latitude");
String longitude=request.getParameter("longitude");
%>
<html>
<body>
<p>Query phrase is : <%=query%></p>
<p>User's city : <%=city%></p>
</body>
</html>
I am new to JSP. So can anyone please help me to fix the given code.

<%# page contentType="text/html; charset=iso-8859-1" language="java" %>
<%! String city; String latitude; String longitude;String query; %>
<%
query=request.getParameter("myQuery");
city=request.getParameter("city");
latitude=request.getParameter("latitude");
longitude=request.getParameter("longitude");
%>
<html>
<body>
<form name="frm" method="post" action="process.jsp">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="22%"> </td>
<td width="78%"> </td>
</tr>
<tr>
<td> </td>
<td><input type="text" name="myQuery" placeholder="Type here"></td>
</tr>
<tr>
<td> </td>
<input name="latitude" id="latitude" type="hidden" value="<%=latitude%>" >
<input name="longitude" id="longitude" type="hidden" value="<%=longitude%>>" >
<input name="city" id="city" type="hidden" value="<%=city%>" >
<td><input type="submit" name="submit" value="Submit"></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
<p>Query phrase is : <%=query%></p>
<p>User's city : <%=city%></p>
</body>
</html>

try to get the parameters at the beginning of the file.
<%
String query=request.getParameter("myQuery");
String city=request.getParameter("city");
String latitude=request.getParameter("latitude");
String longitude=request.getParameter("longitude");
%>

like this ...
<%# page contentType="text/html; charset=iso-8859-1" language="java" %>
<html>
<head>
<script type="text/javascript">
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function displayLocation(latitude,longitude){
var request = new XMLHttpRequest();
var method = 'GET';
var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
var async = true;
request.open(method, url, async);
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
var data = JSON.parse(request.responseText);
var address = data.results[0];
//document.write(address.formatted_address);
var city=document.getElementById("city");
var n = address.formatted_address.split(",");
city.value = n[n.length-3];
}
};
request.send();
};
function showPosition(position){
//var x = document.getElementById("demo");
var latitude=document.getElementById("latitude"),longitude=document.getElementById("longitude");
//x.innerHTML="+" + position.coords.latitude + "+" + position.coords.longitude;
latitude.value = position.coords.latitude;
longitude.value = position.coords.longitude;
displayLocation(latitude.value,longitude.value);
}
</script>
</head>
<body onload="getLocation()">
<%! String city; String latitude; String longitude; %>
<%
String query=request.getParameter("myQuery");
String city=request.getParameter("city");
String latitude=request.getParameter("latitude");
String longitude=request.getParameter("longitude");
%>
<form name="frm" method="post" action="submit.jsp">
<input type="text" name="myQuery" placeholder="Type here">
<input name="latitude" id="latitude" type="hidden">
<input name="longitude" id="longitude" type="hidden">
<input name="city" id="city" type="hidden">
<input type="submit" name="submit" value="Submit">
</form>
<p>Query phrase is : <%=query%></p>
<p>User's city : <%=city%></p>
</body>
</html>

Related

Delete multiple records from MySql by using check box in JSP

I am trying to delete multiple row from MySql database using checkbox. Here is my code. I only can delete row by row without checkbox.
displayfood.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="stylesheet_2.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="validation.js"> </script>
<title>All Food Menu</title>
</head>
<body>
<!--############# HEADER ############# -->
<table id="t1Body_food">
<tr><td colspan="5">
<table class="table_header" align="center" >
<tr> <td class="tbody-logo_food" align="right" valign="bottom">
<form name="myForm" action="searchFood.jsp" onsubmit="return searchvalidate()" method="post">
<input type="text" name="type" placeholder="Search">
<input name="search" type="submit" value="search">
<input type="button" value="Logout" onclick="logoutpage()"/>
</form></td></tr>
</table> </td> </tr>
<tr>
<td class="td1-header"id="rice" > Home </td>
<td class="td1-header"> Food </td>
<td class="td1-header"> Reservation </td>
<td class="td1-header"> About Us </td>
<td class="td1-header"> Contact us </td>
</tr>
</table>
<table id="t2Body" >
<tr><td colspan="5" id="rice"><hr color="orange" size="13"></td>
</tr>
<tr> <td class="td_2header" > Name</td>
<!-- <td class="td_2header" > Type</td>
<td class="td_2header" > Picture </td> -->
<td class="td_2header" > Description </td>
<td class="td_2header" > Price </td>
<td align="right" colspan="4"> <a target="_blank" href="addItem_Form.jsp">
<button name="AddItem" > +Add New Food Menu </button> </a>
</td>
</tr>
<tr><td colspan="5" id="rice"><hr color="orange" size="13"></td>
</tr>
<%
String id= request.getParameter("hiddenID");
try {
// Step1: Load JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL ="jdbc:mysql://localhost/restaurant?user=root& password=Password";
// Step 3: Establish connection to URL
Connection conn = DriverManager.getConnection(connURL);
// Step 4: Create Statement object
Statement stmt = conn.createStatement();
// Step 5: Execute SQL Command
PreparedStatement pstmt =conn.prepareStatement("Select * from food");
ResultSet rs=pstmt.executeQuery();
// out.println("<table id='t2Body' >");
while (rs.next())
{ id=rs.getString("ID");
String name=rs.getString("name");
String type=rs.getString("type");
String pic=rs.getString("picture");
int price=rs.getInt("price");
String desc=rs.getString("description");
// out.println("<tr> <td class=td_2border><div class=food_name>"+id+" </div>");
out.println(" <tr>s<td class=td_2border><div class=food_name>"+name+"</div>");
out.println(" <div><img src=\" " + pic+"\" "+"/></div>");
out.println("<div>"+type+"</div><br>");
out.println("<div><hr color=orange></div> ");
out.println("</td>");
out.println("<td class=td2_desc><br>"+ desc+"</td>");
out.println("<td class=td_2border><br> $"+price+"</td>");
%>
<td class=td_2border>
<br>
<form action="delete.jsp" method="get">
<input type="checkbox" name="hiddenID" value="<%=id%>">
<input type="hidden" name="hiddenID" value="<%=id%>">
<input type="submit" Value="Delete" name ="delete"/>
<%-- <input type="submit" value="<%=id %>" name="check" /> --%>
</form>
</td>
<td class=td_2border><br>
<form action="update_Form.jsp" method="get">
<input type="hidden" name="hiddenID" value="<%=id%>" />
<input type="submit" value="Update" name="updateBtn" />
</form>
</td>
</tr>
<%
}
%>
<tr>
<td colspan="5" align="right">
<form action="delete.jsp" method="get">
<%-- <input type="hidden" name="hiddenID" value="<%=id%>" > --%>
<input type="submit" name="submit" value="confirm" >
</form>
</td>
</tr>
</table>
<%
}
catch(Exception e ){
out.println(e);}
%>
</body>
</html>
delete.jsp:
<%#page import="java.sql.*"%>
<%
String [] id = request.getParameterValues("hiddenID");
// String id= request.getParameter("hiddenID");
if (id != null && id.length != 0) {
out.println("You have selected: ");
for (int i = 0; i < id.length; i++) {
out.println(id[i]);
} //end for loop
}// end if
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
// Step 2: Define Connection URL
String connURL = "jdbc:mysql://localhost/restaurant?user=root&password=Password";
// Step 3: Establish connection to URL
conn = DriverManager.getConnection(connURL);
String sqlStr = "Delete from food WHERE id =?";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
//pstmt.setArray(1,Integer.parseInt(id));
//pstmt.setInt(1,Integer.parseInt(id));
// for (int i = 0; i < id.length; i++)
//if (id !=null){
// for (int i = 0; i < id.length; i++){
// pstmt.setString(1, id[i]);
pstmt.setString(1, id[i]);
int rec=pstmt.executeUpdate();
conn.close();
if (rec>0){
%>
<script>
alert("record is deleted!");
window.location.reload("allFood2.jsp");
</script>
<%
} //end if
else{
%>
<script>
alert(" no record is deleted!");
window.location.reload("allFood2.jsp");
</script>
<%
} //end else
}//end try
catch (Exception e) {
out.println(e.getMessage());
}
%>
You can create a string parameter to hold CSV values for the ids and modify the query to use then as parameter.
String ids = "";
if (id != null && id.length != 0) {
out.println("You have selected: ");
for (int i = 0; i < id.length; i++) {
ids += id[i] +",";
out.println(id[i]);
} //end for loop
}// end if
if (ids .endsWith(","))
ids = ids.substring(0, ids .length() - 1);
try {
if (!"".equals(ids){
String sqlStr = "Delete from food WHERE id in (?)";
PreparedStatement pstmt = conn.prepareStatement(sqlStr);
pstmt.setString(1, ids);
int rec=pstmt.executeUpdate();
conn.commit();
}
} finally {
if (pstmt != null)
pstmt.close();
if (conn != null)
conn.close();
}

jsp update Query

Pls help me out...i just want to do edit operation using jsp..if i press edit button i just want to edit the current row data...how to set row data to the textbox...how to match the current row to text box
Employeeupdate.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">
<%# page import ="java.sql.*" %>
<%
try{
String n=request.getParameter("employeeid");
String p=request.getParameter("employeegender");
String e=request.getParameter("employeename");
String c=request.getParameter("employeesalary");
String d=request.getParameter("employeePhoneno");
String q=request.getParameter("employeeaddress");
String r=request.getParameter("employeeCountry");
Class.forName("com.mysql.jdbc.Driver"); // MySQL database connection
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/employee","root","root123");
PreparedStatement ps = conn.prepareStatement("Update emplo set emp_id=? emp_gender=?,emp_name=?,emp_sal=?,emp_phoneno=?,emp_address=? emp_country =? where emp_id =+ emp_id");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3,e);
ps.setString(4,c);
ps.setString(5,d);
ps.setString(6,q);
ps.setString(7,r);
int i=ps.executeUpdate();
ResultSet rs = ps.executeQuery();
if(i>0)
out.print( " successfully Updated by: "+e);
}catch (Exception e2) {System.out.println(e2);}
out.close();
%>
Employeeupdate.html
<html>
<body bgcolor="HotPink ">
<form action="EmployeeUpdate.jsp" method="get">
<center>
<h1>
<b><u>Employee Update form</u></b>
</h1>
<table border="2" bgcolor="Khaki " style="color: black">
<tr>
<td><b>Employee Id:</b></td>
<td><input type="text" name="employeeid"></td>
</tr>
<tr>
<td><b>Gender:</b></td>
<td><input type="radio" name="employeegender" value="male">Male<br>
<input type="radio" name="employeegender" value="female">Female</td>
</tr>
<tr>
<td><b>Employee Name:</b></td>
<td><input type="text" name="employeename"></td>
</tr>
<tr>
<td><b>Employee Salary:</b></td>
<td><input type="text" name="employeesalary"></td>
</tr>
<tr>
<td><b>Employee PhoneNo:</b></td>
<td><input type="text" name="employeePhoneno"></td>
</tr>
<tr>
<td><b>Employee Address</b></td>
<td><input type="text" name="employeeaddress"></td>
</tr>
<tr>
<td><b>Country:</b></td>
<td><select name="employeeCountry">
<option>Select</option>
<option>India</option>
<option>Austraila</option>
<option>SouthAfrica</option>
<option>England</option>
<option>Usa</option>
<option>UAE</option>
<option>Srilanka</option>
<option>Pakistan</option>
<option>other</option>
</select></td>
</tr>
<tr>
<center> <td><td><input type="submit" value="Update"></td></td></center>
</tr>
</table>
</center>
</form>
</body>
</html>
Move your HTML file into the jsp and then populate your text fields as the following
<td><b>Employee Id:</b></td>
<td><input type="text" name="employeeid" value=<%=request.getParameter("employeeid")%>></td> //etc
Note, however, that java expressions inside a jsp file (<%= %>) are considered bad practice but they are fine if it's just a simple page.
You really should create a servlet and move your business logic there (database access etc).

What is the syntax of replace statement?

This is my controller
#RequestMapping(value = "/deleteMultiple", method = RequestMethod.POST)
public ModelAndView deleteEmp(#ModelAttribute("employee") Employee emp,#RequestParam(value="Id",required=false) String Id,Model model) {
List<Employee> empList = empService.getEmpList();
List<Employee> empListById = empService.getemp_IdDetails(Id);
empList=empService.searchEmpDetails(emp);
empList.addAll(empListById);
Employee emp1=new Employee();
if(empList!=null){
model.addAttribute("delete", empList);
if(empList.isEmpty()){
model.addAttribute("message","This Employee Details are not present");
}
}
model.addAttribute("employee", emp1);
return new ModelAndView("delete","empList",empList);
}
This is my sql
#Override
public List<Employee> getemp_IdDetails(String emp_Ids){
List<Employee> empList = new ArrayList<Employee>();
String sql="select * from EmpDetails where emp_Id IN" + " ("+emp_Ids+") ";
sql.replace("emp_Id", emp_Ids);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
empList = jdbcTemplate.query(sql, new EmployeeRowMapper());
System.out.println("empList:"+empList.size());
return empList;
}
This is my jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Drop down</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#delete").click(function(){
var d = [];
$.each($("#delete option:selected"), function(){
d.push($(this).val());
});
var s=(d.join(", "));
console.log(s);
$("#delete_empId").val(s);
console.log($("#delete_empId").val());
});
});
</script>
</head>
<body>
<div align="center">
<form:form method="post" action="${pageContext.request.contextPath}/deleteMultiple" modelAttribute="employee">
<table>
<tr>
<td>First Name :</td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td>Last Name :</td>
<td><form:input path="lastName" /></td>
</tr>
<tr>
<td>emp_Id :</td>
<td><form:input path="emp_Id" /></td>
</tr>
<tr>
<td>email_Id :</td>
<td><form:input path="email_ID"/></td>
</tr>
<tr>
<td>phone_No :</td>
<td><form:input path="phone_No"/></td>
</tr>
<tr>
<td>City :</td>
<td><form:input path="city"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Search" /></td>
</tr>
</table>
<input type= "hidden" id="delete_empId" name="delete_empId" />
</form:form>
</div>
<div align="center">
<h2 style="color:blue">SelectBox:</h2>
<form:form method="post" action="${pageContext.request.contextPath}/deleteMultipleEmpDetails">
<select id="delete" multiple name="employees">
<c:forEach items="${empList}" var="employee">
<option value= "${employee.emp_Id}" >${employee.firstName}</option>
${msg}
</c:forEach>
</select>
<input type="submit" name="delete" value="delete">
</form:form>
</div>
<div>
<h4 style="color:red">${message}</h4>
</div>
</body>
</html>
This is my code i am retriving the values from jsp and passing the values to my controller.So i need to replace the values of emp_Id by emp_Ids.I have wriiten the replace function in sql is that coorect.I am getting null pointer exception.

AngularJs File Upload in asp.net mvc

here is what I've tried till now
I cant send that file to my action result, its showing me null,
<form ng-show="divPatient" name="PatientForm" ng-submit="AddUpdatePatient()">
<table>
<tr>
<td>
<input class="form-control" type="text" readonly placeholder="Key (Automatic)" ng-model="PatientID" />
</td>
<td>
<input id="FormFocus" name="FirstName" class="form-control" type="text" placeholder="FirstName" ng-model="FirstName" ng-minlength="3" required />
</td>
<td>
<input name="LastName" class="form-control" type="text" placeholder="LastName" ng-model="LastName" ng-minlength="3" required />
</td>
<td>
<input class="form-control" type="text" placeholder="Disease" ng-model="Disease" name="Disease" ng-minlength="3" required />
</td>
<td>
<input class="form-control" type="number" placeholder="Phone No." ng-model="PhoneNo" name="PhoneNo" ng-pattern="/^[789]\d{9}$/" required />
</td>
<td>
<input type="file" onchange="angular.element(this).scope().selectFileforUpload(this.files)" accept="image/*" class="form-control" ng-model="PhotoURL" value="{{PhotoURL}}" required />
</td>
<td colspan="2">
<input type="submit" value="save" class="btn btn-success" ng-disabled="PatientForm.PhoneNo.$dirty && PatientForm.PhoneNo.$invalid || PatientForm.LastName.$dirty && PatientForm.LastName.$invalid || PatientForm.FirstName.$dirty && PatientForm.FirstName.$invalid || PatientForm.Disease.$dirty && PatientForm.Disease.$invalid" />
<input type="button" value="cancel" class="btn btn-primary" ng-click="CancelForm()" />
</td>
</tr>
<tr>
<td></td>
<td><span class="eror-text" ng-show="PatientForm.FirstName.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.LastName.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.Disease.$error.minlength">min 3 letters</span></td>
<td><span class="eror-text" ng-show="PatientForm.PhoneNo.$error.pattern">Invalid phone no</span></td>
</tr>
</table>
</form>
$scope.selectFileforUpload = function (files) {
$scope.selectedFile = files;
}
$scope.AddUpdatePatient = function () {
var file = $scope.selectedFile[0];
var Patient = {
FirstName: $scope.FirstName,
LastName: $scope.LastName,
Disease: $scope.Disease,
PhoneNo: $scope.PhoneNo
};
var getData = angularService.AddPatient(Patient,filee);
getData.then(function (msg) {
GetAllPatients();
alert(msg.data);
$scope.divPatient = false;
}, function () {
alert('Error in adding record');
});
}
here is my service code
this.AddPatient = function (patient, file) {
// this showing me file object thats fine
alert("in services" + filee);
// i think something wrong here we shouldn't or can't send the file to actionresult like this
var response = $http({
method: "post",
url: "AddPatient",
data: JSON.stringify(patient),
dataType: "json",
// something wrong here ??
file : file
});
return response;
}
amd last my method in my controller
public string AddPatient(Patient patient,HttpPostedFileBase file)
{
// I'm getting patient data that is fine, but file is showing me null
}
is anything wrong with my service method ??? or do you know how to send form along with files to actionresult or any method in the mvc controller, i heard some pleople do it by using "new FormData", but i dont know that, but i'm willing to learn it or use it, if that solves my problem

Exactly i"m getting this error? Unknown column 'Nationality' in 'field list' using in jsp, mysql and tomcat?

i ill created the program of create, insert, update, delete, exit using in jsp and mysql only. i got the solutions for insert, delete, exit, and create but, update section only i got error., in my DB name is employee and table name is employees, the fields are in the order like 1. employee name, 2. employee_id, 3. nationality,. In update part i'm using the Employee_id is displayed in default, it's also displayed but i got error in 3 field of Nationality. I send my code if you any clear my error,. thanks in advance. the coding following as:
<%# page import="java.sql.*" %>
<%# page import="java.sql.DriverManager.*" %>
<%# page import="java.sql.Statement.*" %>
<%# page import="java.io.*" %>
<html>
<head>
<title>
UPDATING DETAILS ABOUT EMPLOYEE
</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h3>ENTER THE EMPLOYEE DETAILS</h3><br>
<form action="editEmployee.jsp" name="UpdateForm" method="post">
<table cellspacing="1" cellpadding="1" border="1" WIDTH=90%>
<tr>
<td align="center">YOUR EMPLOYEE ID:</td><td align="center"><B><%= request.getParameter("emp_id")%></B></td>
</tr>
<tr>
<td align="center">EMPLOYEE NAME:</td>
<td align="center"><input type="text" name="EmployeeName"></td>
</tr>
<tr>
<td align="center"> EMPLOYEE NATIONLITY:</td>
<td align="center"><input type="text" name="Nationality"></td>
</tr>
<%
String EmployeeName=request.getParameter("EmployeeName");
String Nationality=request.getParameter("Nationality");
PreparedStatement ps;
Connection con=null;
String driverName="com.mysql.jdbc.Driver";
String connectionUrl="jdbc:mysql://localhost:3306/";
String user="root";
String password="sarakrish";
String dbName="employee";
try{
Class.forName(driverName);
con=DriverManager.getConnection(connectionUrl+dbName,user,password);
ps=con.prepareStatement("update employees set EmployeeName=?,Nationality=?");
ps.setString(1, EmployeeName);
ps.setString(2, Nationality);
ps.executeUpdate();
}
catch(Exception e)
{
out.print(e.getMessage());
e.printStackTrace();
}
%>
</table><br><br>
<input type="submit" value="UPDATE" name="method" class="button" >
<input type="reset" value="CLEAR">
<input type="button" name="method" value="BACK TO LIST" class="button" onclick="location.href='Employeelist.jsp'"/>
</form>
</body>
</html>
hey buddy's thanks for little conversations. I ill do some changes in my program and got the output., As the code is following as:
<%# page import="java.sql.*" %>
<%# page import="java.sql.DriverManager.*" %>
<%# page import="java.sql.Statement.*" %>
<%# page import="java.io.*" %>
<%
PreparedStatement ps;
Connection con=null;
ResultSet rs=null;
Statement st=null;
String driverName="com.mysql.jdbc.Driver";
String connectionUrl="jdbc:mysql://localhost:3306/";
String user="root";
String password="sarakrish";
String dbName="employee";
String emp_id = "";
String emp_name = "";
String nationality = "";
try{
Class.forName(driverName);
con=DriverManager.getConnection(connectionUrl+dbName,user,password);
if(request.getParameter("edit")!=null && request.getParameter("edit").toString().equals("yes")){
String EmployeeId = request.getParameter("emp_id");
String EmployeeName=request.getParameter("EmployeeName");
String Nationality=request.getParameter("Nationality");
ps=con.prepareStatement("update employees set EmployeeName=?,Nationlity=? where Employee_id=?");
ps.setString(1, EmployeeName);
ps.setString(2, Nationality);
ps.setString(3, EmployeeId);
ps.executeUpdate();
ps.close();
}
st = con.createStatement();
String sql="SELECT * FROM employees where employee_id='"+request.getParameter("emp_id")+"'";
rs=st.executeQuery(sql);
while (rs.next()) {
emp_id = rs.getString(2);
emp_name = rs.getString(1);
nationality = rs.getString(3);
break;
}
rs.close();
st.close();
con.close();
}catch(Exception e){
out.print(e.getMessage());
e.printStackTrace();
}
%>
<html>
<head>
<title>
UPDATING DETAILS ABOUT EMPLOYEE
</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>
<body>
<h3>ENTER THE EMPLOYEE DETAILS</h3><br>
<%=request.getParameter("edit")%>
<form action="editEmployee.jsp" name="UpdateForm" method="post">
<input type="hidden" name="edit" id="edit" value="yes">
<input type="hidden" name="emp_id" id="emp_id" value="<%=emp_id %>">
<table cellspacing="1" cellpadding="1" border="1" WIDTH=90%>
<tr>
<td align="center">YOUR EMPLOYEE ID:</td><td align="center"><B><%= request.getParameter("emp_id")%></B></td>
</tr>
<tr>
<td align="center">EMPLOYEE NAME:</td>
<td align="center"><input type="text" name="EmployeeName" value="<%=emp_name %>"></td>
</tr>
<tr>
<td align="center"> EMPLOYEE NATIONLITY:</td>
<td align="center"><input type="text" name="Nationality" value="<%=nationality %>"></td>
</tr>
</table><br><br>
<input type="submit" value="UPDATE" name="method" class="button" >
<input type="reset" value="CLEAR">
<input type="button" name="method" value="BACK TO LIST" class="button" onclick="location.href='Employeelist.jsp'"/>
</form>
</body>
</html>
Assuming this as string , since your Table details are unclear . Pass the arguments as String
ps=con.prepareStatement("update employees set EmployeeName=?,Nationality=? where employee_id=? ");
ps.setString(1,'EmployeeName');
ps.setString(2,'Nationality');
ps.setString(3,1);
Also avoid using scriptlets , read through the link Aniket suggested.
Hope it helps !!