updating Table from Form data input using Spring MVC+JDBC - mysql

I am having issue with updating records on a table using jdbcTemplate.
here is my jsp form
<form:form method="post" action="edit" modelAttribute="Student">
<table>
<tr>
<td>id:</td>
<td><form:input path="id" /></td>
</tr>
<tr>
<td>Name:</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Salary:</td>
<td><form:input path="salary" /></td>
</tr>
<tr>
<td>Designation:</td>
<td><form:input path="designation" /></td>
</tr>
<tr>
<td><input type="submit" value="Update" /></td>
</tr>
</table>
</form:form>
update method in StudentDaoImpl class is:
public void update(Student s) {
String sql = "UPDATE Student set name=?, salary=?, designation=? where id=?";
jdbcTemplate.update(sql,s.getId(),s.getName(),s.getSalary(),s.getDesignation());
System.out.println("-- Student list is Updated---" );
int status =jdbcTemplate.update(sql);
System.out.println("-------status---"+status);
}
controller method for updating is:
#RequestMapping(value =("/edit"), method= RequestMethod.POST)
public ModelAndView editStudent(#ModelAttribute("Student") Student student,BindingResult result, ModelMap map){
#SuppressWarnings("resource")
ApplicationContext ac = new ClassPathXmlApplicationContext("META-INF/applicationContext.xml");
StudentDAO dao = (StudentDAO) ac.getBean("studentDao");
// map.addAttribute("id", student.getId());
map.addAttribute("name", student.getName());
map.addAttribute("salary", student.getSalary());
map.addAttribute("designation", student.getDesignation());
dao.save(student);
return new ModelAndView("redirect:/viewstudent");
}
I want to update record by id on my student table...I get sql query error.
What I am doing wrong? please suggest.

Related

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.

Registration page in string, handle data from the JSON and response something?

My task is to create user account in Spring. This is an excerpt from index.jsp.
Submitting to /register sends Name, Surname, Login and Email using POST. My task is to receive this data and send it to the database. When data is registered in database I must return status code: "1" for success or "0" if no users were added.
When I execute /register I have information that "Required param GET". What is the problem?
<div id="register">
<div class="top-bar">
<header class="page-title">Zarządzanie projektami studenckimi</header>
</div>
<header class="section-title">Rejestracja</header>
<table cellspacing="0" cellpadding="0">
<tr> <td colspan="2" class="info" /> </tr>
<tr>
<td class="param">Imię:</td>
<td class="value">
<input type="text" id="register-firstname" />
</td>
</tr>
<tr>
<td class="param">Nazwisko:</td>
<td class="value">
<input type="text" id="register-surname" />
</td>
</tr>
<tr>
<td class="param">Adres email:</td>
<td class="value">
<input type="text" id="register-email" />
</td>
</tr>
<tr>
<td class="param">Nazwa użytkownika:</td>
<td class="value">
<input type="text" id="register-user" />
</td>
</tr>
<tr>
<td style="text-align: left;" />
<td style="text-align: right;">
<input type="button" id="register-button" value="Zarejestruj" />
</td>
</tr>
</table>
</div>
And this is my code from the logincontroller.java in Spring:
#RequestMapping(value = "/register", method = RequestMethod.POST)
public #ResponseBody Integer addProwadzacy(
#RequestParam(value = "firstname", required = true) String imie,
#RequestParam(value = "surname", required = true) String nazwisko,
#RequestParam(value = "email", required = true) String mail,
#RequestParam(value = "user", required = true) String login,
Model model) {
Date data = new Date();
String haslo = null;
// RandomPassword.
Prowadzacy prowadzacy = new Prowadzacy();
prowadzacy.setImiona(imie);
prowadzacy.setNazwisko(nazwisko);
prowadzacy.setEmail(mail);
prowadzacy.setLogin(login);
prowadzacy.setDataDodania(data);
prowadzacy.setWaznosc(true);
prowadzacy.setAktywowany(false);
prowadzacy.setHaslo(Encryption.encrypt(haslo));
loginService.addProwadzacy(prowadzacy);
List<Prowadzacy> registerlist = loginService.validateRegister(imie,
nazwisko, mail, login);
if (registerlist.size() > 0) {
return 1;
} else {
return 0;
}
}

How to read multiple textboxes and insert into database?

How can I update multiple textbox in database using ASP.NET Web Pages(razor syntax). I want to edit emails of students. And the number of rows containing textbox varies or dynamic. Somebody help.
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tr>
<td>Jason</td>
<td><input type="text" name="txtbox1"></td>
</tr>
<tr>
<td>Kripkee</td>
<td><input type="text" name="txtbox2"></td>
</tr>
<tr>
<td>Kane</td>
<td><input type="text" name="txtbox3"></td>
</tr>
<tr>
<td>Michael</td>
<td><input type="text" name="txtbox4"></td>
</tr>
<tr>
<td><input type="submit" value="Update"></td>
</tr>
</table>
</form>
You can try this:
Assuming you have a view model providing a list of students.
View -
#foreach (var student in Model.Students)
{
<tr>
<td>#student.Name</td>
<td><input name="studentEmails[#student.Id]"/></td>
</tr>
}
Controller -
public ActionResult UpdateEmails(IDictionary<int, string> studentEmails)

Geting the first line in the textarea from database

I am trying to retrieve the value of an HTML textarea in jsp page from mysql database.The problem I am having is that I only can get he first line in the textarea(When I'm saving address in databse, It's retrieving first line only). This is happening for text box also, where data has space in the database, it's only getting first line of the data.
Thanks in advance.
HTML Code:
<div class="container2">
<table>
<tr>
<td align="right">TPO Name</td>
<td><input type="text" readonly name="tponame" value=<%=rs.getString("tponame")%>></td>
</tr>
<tr>
<td align="right">Name of College</td>
<td><input type="text" readonly name="college_name" value=<%=rs.getString("college_name")%>></td>
</tr>
<tr>
<td align="right">Contact Number</td>
<td><input type="text" name="contactno" value=<%=rs.getString("contactno")%>></td>
</tr>
<tr>
<td align="right">Contact Email</td>
<td><input type="text" name="contactemail" value=<%=rs.getString("contactemail")%>></td>
</tr>
<tr>
<td align="right">Address</td>
<td><input type="text" name="address" value=<%=rs.getString("address")%>></td>
</tr>
<tr>
<td colspan="2"><input type="submit" class="button" value="Update" style="float:right;"></input></td>
</tr>
JSP code:
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/FMS","root","root");
Statement st=con.createStatement();
String tponame= request.getParameter("tponame");
String college_name=request.getParameter("college_name");
String contactno=request.getParameter("contactno");
String contactemail=request.getParameter("contactemail");
String address=request.getParameter("address");
String sql = ("update tpo_details set contactno='"+contactno+"',contactemail='"+contactemail+"',address='"+address+"' where tponame='"+tponame+"'");
st.executeUpdate(sql);
response.sendRedirect("update_tpo_network_data.jsp");
%>