I am quite new to hibernate frameworks and I am working on a Hibernate framework project in the netbeans IDE. I have a javadb that is connected to the project and I need to get the task list for each employee and display it as a bullet list in a <td> against each employee name. The following is the table displaying the employees' names and roles that are being fetched using the getEmployeeDetails method in the EmployeeHelper class.
Issue - The task list is always empty though I call the resultTaskList parameter that is passed from the Controller. - I know that I have to do an if conditional check for task within the nested forloop that will list the tasks to group them based on the employee names. But am not sure how to do an if within a jsp page.
Any suggestions on how to display the task list of each employee within the same table will be highly appreciated.
In this table, I intend to have the tasks pertaining to each employee as a bulletlist within each corresponding <td>.
Employee.jsp
...
<div class="content">
<!--Display table of roles with an edit button against each role-->
<form method="get" action="<%= request.getContextPath() %>/RoleController">
<br>
<table border ="2">
<thead class="thead-inverse">
<tr>
<th></th>
<th>Employee Name</th>
<th>Role</th>
<th>Tasks</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
<c:forEach items="${result}" var="res">
<tr>
<th scope="row">
</th>
<td>
<c:out value="${res[0]}"></c:out>
</td>
<td>
<c:out value="${res[1]}"></c:out>
</td>
<td>
<c:out value="${resultTaskList[1]}"></c:out>
</td>
<td>
<input type="button" class="btn btn-info" value="Edit Role">
</td>
</tr>
</c:forEach>
</table>
</form>
</div>
...
EmployeeController.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
EmployeeHelper helper = new EmployeeHelper();
List<Employee> resultTaskList = helper.getEmployeeTasks();
request.setAttribute("resultTaskList", resultTaskList);
List<Employee> result = helper.getEmployeeDetails();
request.setAttribute("result", result);
request.getRequestDispatcher("Employee.jsp").forward(request, response);
}
EmployeeHelper.java
public class EmployeeHelper {
Session session = null;
public EmployeeHelper(){
this.session = HibernateUtil.getSessionFactory().openSession();
}
public List getEmployeeDetails(){
Transaction tx = this.session.beginTransaction();
List<Employee> employeeList = null;
try{
Query query = session.createQuery("select e.name, r.title from Employee as e, Role as r where e.employeeid=r.employeeid");
employeeList = (List<Employee>)query.list();
tx.commit();
}
catch(HibernateException ex){
ex.printStackTrace();
tx.rollback();
}
return employeeList;
}
public List getEmployeeTasks(){
Transaction tx = this.session.beginTransaction();
List<Employee> employeeTaskList = null;
try{
Query query = session.createQuery("select e.name, t.description from Employee as e, Role as r, Task as t, EmployeeTask as et where e.employeeid=r.employeeid and t.taskid=et.taskid and e.employeeid=et.employeeid");
employeeTaskList = (List<Employee>)query.list();
tx.commit();
}
catch(HibernateException ex){
ex.printStackTrace();
tx.rollback();
}
return employeeTaskList;
}
}
SQL Query executed within the getEmployeeTasks() method
instead of List employeeTaskList use List and iterate loop and set values in employee list try following code .
public List getEmployeeTasks(){
Transaction tx = this.session.beginTransaction();
List<Employee> employeeTaskList = null;
try{
session.beginTransaction();
Query query = session.createQuery("select e.name, t.description from Employee as e, Role as r, Task as t, EmployeeTask as et where e.employeeid=r.employeeid and t.taskid=et.taskid and e.employeeid=et.employeeid");
List<Object[]> result = (List<Object[]>) query.list();
if (null != result && result.size() != 0) {
for (Object[] obj : result) {
//Set values over here
employeeTaskList.set.....
}
tx.commit();
}
}
catch(HibernateException ex){
ex.printStackTrace();
tx.rollback();
}
return employeeTaskList;
}
These two lists are non-related as suggested by JB Nizet. Still You can do something like this.
<c:forEach items="${result}" var="res">
<tr>
<th scope="row">
</th>
<td>
<c:out value="${res[0]}"></c:out>
</td>
<td>
<c:out value="${res[1]}"></c:out>
</td>
<td>
<c:forEach items="${resultTaskList}" var="resultTaskList">
<c:if test = "${res[0] == resultTaskList[0]}">
<c:out value="${resultTaskList[1]}"></c:out>
</c:if>
</c:forEach>
</td>
<td>
<input type="button" class="btn btn-info" value="Edit Role">
</td>
</tr>
</c:forEach>
Hope this helps.
Related
Im using Spring mvc and facing the problem about inserting data into two tables, my target is inserting data into 2 tables from 1 jsp (1 form)
I have two 2 tables:
1.Cars
Id
Name
CityId(FK)
2.City
Id
Name
this is my controller:
#RequestMapping(value="/CreateCar", method = RequestMethod.GET)
public ModelAndView getCreateCarPage(ModelMap model) throws ServletException, IOException {
try {
Car myCar = new Car();
City city = new City();
myCar.setCity(city);
model.addAttribute("city", city);
model.addAttribute("createCar", myCar);
}
catch(Exception e) {
e.printStackTrace();
}
return new ModelAndView("testForm");
}
#RequestMapping(value="/CreateCar", method = RequestMethod.POST)
public ModelAndView setCreateCarPage(ModelMap model,
#ModelAttribute("createCar") Car createCar) throws SQLException, Exception {
try {
carService.createCar(createCar);
}
catch(Exception e) {
e.printStackTrace();
}
return new ModelAndView("successProcess");
}
}
JSP:
<form:form modelAttribute="createCar" method="POST" commandName="createCar" action="/CreateCar" enctype="multipart/form-data">
<fieldset style="width:300px">
<table cellspacing="0" cellpadding="0" align="center">
<tr>
<td>
<label>Name of car</label>
<form:input path="name" id="name"/>
</td>
<td>
<label>Name of city</label>
<form:input path="city.name" />
</td>
</tr>
<tr>
<td><input class="btn btn-danger" type="submit" value="Inser New" style="width:100px;" /></td>
</tr>
</table>
</fieldset>
With above source, it just insert name of car success but can not insert name of city
Log massages:
SqlExceptionHelper - Column 'city_id' cannot be null
How can I fix this problem ? thank so much !
I have 2 project folders. The first one is a RESTful service and the other one is a client. What I'm trying to do is:
Getting all notes from the RESTful service (I do this as a list) of a specific user.
Then display the notes to the client in a table (html).
When I try to display the notes I get the following error:
javax.servlet.jsp.JspTagException: Don't know how to iterate over supplied "items" in <forEach>
The HTML code (I'm using JSP). The error appears at the 'forEach' loop:
<table class="table table-striped">
<thead>
<tr>
<!-- Here we create the columns -->
<th> Id </th>
<th> Title </th>
<th> Text </th>
<th> Color </th>
<th> Date/Time </th>
<th> Actions </th> <!-- the table header for Actions -->
</tr>
</thead>
<!-- Table body - The data in the table -->
<tbody>
<c:forEach items="${note-all}" var="pp">
<tr>
<td><c:out value="${pp.id}" /></td>
<td><c:out value="${pp.title}" /></td>
<td><c:out value="${pp.text}" /></td>
<td><c:out value="${pp.color}" /></td>
<td><c:out value="${pp.datetime}" /></td>
<!-- The final column is the Actions, which is a list of buttons,
that we can perfom on our note Entities. -->
<td>
<div class="btn-group">
<!-- ***** Edit Button ***** -->
<a href="#Url.Action("Edit", new {pp.id})" class="btn btn-xs btn-primary">
<i class="glyphicon glyphicon-edit"></i>
Edit
</a>
<a href="#Url.Action("Delete", new {pp.id})" class="btn btn-xs btn-danger" data-post="Are you sure you want to delete this?">
<i class="glyphicon glyphicon-remove"></i>
Delete
</a>
</div>
</td>
</tr>
</c:forEach>
</tbody>
</table>
The RESTful service code:
#Path("/getAll")
#POST
#Consumes({MediaType.APPLICATION_FORM_URLENCODED/})
#Produces({MediaType.APPLICATION_XML})
public Response login(#FormParam("username") String uname
) throws ClassNotFoundException, SQLException{
System.out.println(uname);
//*First*: We get the id of the user
String sql = "SELECT user_id "
+ " FROM user_table "
+ " WHERE username = ?";
PreparedStatement ps = DbCon.getPreparedStatement(sql);
ps.setString(1, uname);
ResultSet rs = ps.executeQuery();
String id = "";
if(rs.next()){
id = rs.getString("user_id");
}
//*Second*: We get the users notes
String sql2 = "SELECT * "
+ " FROM notes_table "
+ " WHERE user_id_fk = ?";
PreparedStatement ps2 = DbCon.getPreparedStatement(sql2);
ps2.setString(1, id);
ResultSet rs2 = ps2.executeQuery();
ArrayList<Note> note_AL = new ArrayList<Note>();
if(rs2.next()){
Note note = new Note();
note.setId(rs2.getInt("note_id"));
note.setTitle(rs2.getString("title"));
note.setText(rs2.getString("text"));
note.setColor(rs2.getString("color"));
note.setDate(rs2.getString("datetime"));
note_AL.add(note);
}
//we wrap the ArrayList with Generic ENtity
GenericEntity<ArrayList<Note>> generic_list_of_notes = new GenericEntity<ArrayList<Note>>(note_AL){};
return Response.ok(generic_list_of_notes).build();
}
The client servlet code (the post method):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Form form = new Form();
form.add("username", "ali");
//We create a client object
Client client = Client.create();
//We create a resource object and pass a url to it
WebResource webR = client.resource("http://localhost:8080/MyNote/api/notes/getAll");
ClientResponse resp = webR.accept(MediaType.APPLICATION_XML/*"text/html"*/).post(ClientResponse.class, form);
//for debug
if (resp.getStatus() != 200){
System.err.println("Unable to connect to the RESTFUL web service");
}
List<Note> output = resp.getEntity(new GenericType<List<Note>>(){});
request.setAttribute("note-all", output);
RequestDispatcher rd = request.getRequestDispatcher("/Notes.jsp");
rd.forward(request, response);
}
I am trying to create a way of filtering data that is stored within the datastore. The method I am using for this is a mixture of HTML, Javascript and Java Servlets. A form is made that allows data that is input into the Web Application to be sent to the Java Servlet. The Servlet then does the required actions and sends the user back to the page with the updated data. My problem is I have to use a SelectBox within this form that allows the user to select the atribute they wish to filter by, e.g. title, author. When the submit button is pressed, the value of the SelectBox is not sent as a parameter. This means a ERROR 500 appears as there isn't enough parameters to perform the function. I need to:-
Get the value of the SelectBox.
Pass it to the function with the parameter value in a text field. (Almost Completed)
Set the value of idvBook to equal the List that is sent back to the Webb Application.
Firstly, this is how I am creating the form with the SelectBox, TextInput and ButonInput:-
<div class="headline">Filter the DataStore</div>
<div class="info">To view individual records, select the attribute
you'd like to filter by and enter the value you'd like to find. Click
the button to generate the table based on your search criteria.</div>
<script type="text/javascript">
function filter(){
document.filterBooks.action="/get";
var idvBook = document.filterBooks.submit();
}
</script>
<form name="filterBooks">
<table>
<tr>
<td valign="top"><label for="attribute">Attribute</label></td>
<td>
<select id="attributeSelect">
<option value="void">Select Attribute</option>
<option value="id">ID</option>
<option value="title">Title</option>
<option value="author">Author</option>
<option value="publisher">Publisher</option>
</select>
</td>
</tr>
<tr>
<td valign="top"><label for="value">Value</label></td>
<td><input type="text" name="value" id="value"></input></td>
</tr>
<tr>
<td colspan="2" align="right"><input type="submit" value="Filter" onclick="filter()"></td>
</tr>
</table>
</form>
<table>
<tr>
<th>Book ID</th>
<th>Title</th>
<th>Description</th>
<th>Author</th>
<th>Publisher</th>
<th>Publish Date</th>
<th>Remove Book</th>
</tr>
<%
for (Book book : idvBook) {
%>
<tr>
<td><%=book.getId()%></td>
<td><%=book.getTitle()%></td>
<td><%=book.getDescription()%></td>
<td><%=book.getAuthor()%></td>
<td><%=book.getPublisher()%></td>
<td><%=book.getPublishDate()%></td>
<td><a class="done" href="/done?id=<%=book.getId()%>">Remove</a></td>
</tr>
<%
}
%>
</table>
</div>
Once this has been made, it is then placed in the HTML table located below the form (shown in the code above).
This sends the parameters to this servlet:-
public class ServletGetBooks extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse resp) throws IOException
{
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
String attribute = request.getParameter("attributeSelect").toString();
String param = request.getParameter("value");
Dao.INSTANCE.getBooks(attribute, param);
resp.sendRedirect("/TodoApplication.jsp");
}
}
You can see another function is ran here. This function looks like this:-
public List<Book> getBooks(String attribute, String param) {
EntityManager em = EMFService.get().createEntityManager();
Query q = null;
if(attribute.equals("id"))
{
q = em.createQuery("select b from Book b where b.id = :id");
q.setParameter("id", param);
}
else if(attribute.equals("title"))
{
q = em.createQuery("select b from Book b where b.title = :title");
q.setParameter("title", param);
}
else if(attribute.equals("author"))
{
q = em.createQuery("select b from Book b where b.author = :author");
q.setParameter("author", param);
}
else if(attribute.equals("publisher"))
{
q = em.createQuery("select b from Book b where b.publisher = :publisher");
q.setParameter("publisher", param);
}
List<Book> books = q.getResultList();
return books;
}
How can i get it so that i can get the value of the SelectBox, run the function and set the result of this to equal idvBook?
EDIT-------------------------------------------------------------------------------------------------
I'll simplify things. I need this within <% ... %> tags:-
List<Book> idvBook = new ArrayList<Book>();
idvBook = dao.getBook("Value in SelectBox","Value in TextInput");
Your select box does not have a name attribute and its value is thus not sent with the form data.
I have a page where am adding an employee into a table. In table i have set a composite key. If i insert same record through my application it throws error "HTTP Status 500 - PreparedStatementCallback; SQL [INSERT INTO EMPLOYEE_ROLE(EMP_NUM,ROLE,STATUS)VALUES (?,?,'LOGGEDIN')]; ORA-00001: unique constraint (EMPLOYEE_ROLE_PK) violated"
My JSP page:
Add New User Details
<%
System.out.println("your selected Emp_Num from script :"+request.getParameter("enum")+" "+request.getParameter("ename"));
String eNum=request.getParameter("enum");
String eName=request.getParameter("ename");
if(eNum!=null){
System.out.println("your selected Emp_Num inside servlet:"+eNum);
ArrayList<HashMap<String, String>> empList1 = UserJdbcGenericDao.empNameDetails_AA(eNum);
System.out.println("Size (servlet): "+empList1.size());
for (int i=0;i<empList1.size();i++) {%>
<tr><td><label for="empNum">Employee Number:</label></td>
<td>
<select id="empNum" name="empNum">
<option value="<%=empList1.get(i).get("3")%>" selected="selected"><%=empList1.get(i).get("3")%></option>
<%
ArrayList<HashMap<String, String>> empList = UserJdbcGenericDao.empNumDetails_AA();
for (int j=0;j<empList.size();j++) {
%>
</select>
<% }%>
</td>
<td><label for="empName">Employee Name:</label></td>
<td>
<select id="empName" name="empName" size="1">
<option value="" selected="selected">Select Emp_Num:</option>
<option value="" selected="selected"><%=empList1.get(i).get("0")+empList1.get(i).get("1")+empList1.get(i).get("2")%></option>
</select>
<% }
}else if(eName!=null){%>
</td><%
System.out.println("your selected Emp_Num inside servlet:"+eName);
ArrayList<HashMap<String, String>> empList1 = UserJdbcGenericDao.empNameDetails_AAname(eName);
System.out.println("Size (servlet): "+empList1.size());
for (int i=0;i<empList1.size();i++) {%>
<tr><td><label for="empNum">Employee Number:</label></td>
<td>
<select id="empNum" name="empNum" onchange="selectEmpNum()">
<option value="" selected="selected"><%=empList1.get(i).get("3")%></option>
<%
ArrayList<HashMap<String, String>> empList = UserJdbcGenericDao.empNumDetails_AA();
for (int j=0;j<empList.size();j++) {
%>
</select>
<% }%>
</td>
<td><label for="empFName">Employee Name:</label></td>
<td>
<select id="empFName" name="empFName" size="1">
<option value="" selected="selected">Select Emp_Num:</option>
<option value="" selected="selected"><%=empList1.get(i).get("0")+empList1.get(i).get("1")+empList1.get(i).get("2")%></option>
</select>
<% }
}%>
</td>
</tr>
<tr>
<td><label for="empRole">Employee Role:</label></td>
<td>
<select name="empRole" id="empRole">
<option value="" > Select Employee Role</option>
<%
ArrayList<HashMap<String, String>> roles = UserJdbcGenericDao.empDetails_AA();
for (int i=0;i<roles.size();i++) {%>
<option value="<%=roles.get(i).get("0")%>"><%=roles.get(i).get("0")%></option>
<% }%>
</select>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" class="table-footer">
<input type="submit" class="button round green text-upper" value="save" onClick="return userValidate()"/>
<input type="reset" class="button round green text-upper" value="Cancel" onClick="pageCall()"/>
<!--cancel -->
</td>
</tr>
</tfoot>
</table>
controller works like this if action ="insert" then it goes to this condition and performs action :
if(action.equalsIgnoreCase("insert"))
{
System.out.println("inside insert service");
UserManager user = new UserManager();
System.out.println("Emp_Num value:"+request.getParameter("empNum"));
user.setEmpNum(Long.parseLong(request.getParameter("empNum")));
System.out.println("Employee Name value is :"+request.getParameter("empName"));
String empName=request.getParameter("empName");
user.setEmpRole(request.getParameter("empRole"));
System.out.println("Role value is :"+request.getParameter("empRole"));
Boolean isAdd=dao.addUser(user);
System.out.println("checking condition Value :"+isAdd);
if(isAdd){
System.out.println("Emp_Num value is :"+request.getParameter("empNum"));
String emp_num=request.getParameter("empNum");
String lastModifiedBy=hs.getAttribute("fullname").toString();
hs.setAttribute("emp_num",emp_num);
ArrayList<HashMap<String, String>> itemList =com.compass.banker.dao.jdbc.UserJdbcGenericDao.empuid(emp_num);
int indexs = 0;
for (int j=0;j<itemList.size();j++) {
userId=itemList.get(j).get("0");
System.out.println("your creating UserId is:"+userId);
MessageUser users = new MessageUser();
String LastModifiedBy=hs.getAttribute("fullname").toString();
System.out.println("lastModifiedBy :"+LastModifiedBy);
System.out.println("login User id:"+LastModifiedBy);
users.setLastModifiedBy(LastModifiedBy);
users.setUserId(userId);
String mText="Hi"+userId+"Your Account has been created by "+LastModifiedBy+"in Compass data base";
users.setmText(mText);
System.out.println("Message Text value is :"+mText);
Format formatter = new SimpleDateFormat("dd-MMM-yy");
String s = formatter.format(new Date());
System.out.println("Todays date is:"+s);
users.setLast_modified_date(s);
Boolean isAdded=dao.addUsers(users);
System.out.println("checking condition is:"+isAdded);
}
//Accessing the Email-Id to Send a confirmation Mail
ArrayList<HashMap<String, String>> itemsList =com.compass.banker.dao.jdbc.UserJdbcGenericDao.empMail(emp_num);
int index = 0;
for (int i=0;i<itemsList.size();i++) {
eMail_id=itemsList.get(i).get("0");
setMailServerProperties();
String msg="This mail is from Pinovus Consulting Pvt Ltd<b>";
try {
createEmailMessage(eMail_id,msg);
} catch (AddressException e) {
System.out.println("Mailing Address is not correct in createMailMessage...."+e.getMessage());
} catch (MessagingException e) {
System.out.println("Message not send...."+e.getMessage());
}
try {
sendEmail();
} catch (AddressException e) {
System.out.println("Mailing Address is not correct in sendEmail...."+e.getMessage());
} catch (MessagingException e) {
System.out.println("Mail not send...."+e.getMessage());
}
}
//System.out.println("2.you have to send a confirmation mail to this mail_id:"+eMail_id[i]);
String var="One User Account added successfully";
RequestDispatcher rd = request.getRequestDispatcher("/App_Admin/UsermanagementA.jsp?ref="+var);
rd.forward(request, response);
}else{
System.out.println("Record not updated");
response.sendRedirect("/App_Admin/statusMessage.jsp");
}
}
All these pages are there which are there in the code. But how to perform this alert or routing to another page if there is any database error as mentioned. Please suggest some solution.
You can make custom error pages that Tomcat will server instead of 500's (or whatever): Custom Error Page in Tomcat 7 for Error Code 500.
You could also do proper exception handling and generate error output as needed, specific to the current situation.
You can also create a servlet filter that grabs unhandled exceptions and displays them appropriately.
You can also check for an existing entry first and don't attempt to insert if it exists (but be prepared to handle errors anyways in the case of race conditions in multi-user applications).
Try this in your code WEB-INF/web.xml
<error-page>
<error-code>500</error-code>
<location>/Error.jsp</location>
</error-page>
In your case if you need show the error as alert, then you can use javascript alert().
You can try alert(<%=msg%>).
Hope it will help you.
Guess you are talking about the runtime exceptions that are thrown ,
For example , ora00232 Invalid identifiers
you can pass this objects in the response or set in the session,
In your code ,
catch(Exception ex)
{
request.setAttribute("error",ex);
}
//Forward your response
Hope this helps !!
Im having some little troubles with the UPDATE servlet.
Im trying to update my db but its just not happening. I'm new to this chapter of Java EE.
**NB: I'm just having trouble with the UpdateServlet because i dont know how to get the modified datas from the JSP in order to send it to the DAO and then to update the DB. The rest is OK
The purpose : When the user hits the "Update" button (screenshot below)...
... the JSP forwards the request to the "update user" page (below) where he'll be able to modify the first and last name attached to the email (which is the primaary key)(screenshot below)...
My question is : how do i implement the UpdateUserServlet (see code below) code that gets the User object from the session and updates the database with the new first and last name.
The JSP that displays the User List
<body>
<h1>Users List</h1>
<table cellpadding="5" border=1>
<tr valign="bottom">
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
</tr>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:forEach var="user" items="${users}">
<tr valign="top">
<td><p>${user.firstName}</td>
<td><p>${user.lastName}</td>
<td><p>${user.emailAddress}</td>
<td>Update</td>
<td>Delete</td>
</tr>
</c:forEach>
</table>
</body>
After hitting the "Update button" this JSP below takes over.
....
<body>
<h1>Update User</h1>
<form action="updateUser" method="post">
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td><input type="text" name="firstName"
value="${user.firstName}">
</td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value="${user.lastName}">
</td>
</tr>
<tr>
<td align="right">Email address:</td>
<td>${user.emailAddress}</td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Submit"></td>
</tr>
</table>
</form>
</body> ....
The Update servlet. Ineed help with this one.
package user;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import business.User;
import data.UserDB;
public class UpdateUserServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
User user = new User();
HttpSession session = request.getSession();
session.setAttribute("user", user);
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmailAddress(emailAddress);
UserDB.update(user);
// TODO: add code that gets the User object from the session and updates the database
String url = "/displayUsers";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
}
}
The DAO
package data;
import java.sql.*;
import java.util.ArrayList;
import business.User;
public class UserDB
{
public static int update(User user) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String query = "UPDATE User SET " + "FirstName = ?, " + "LastName = ? "
+ "WHERE EmailAddress = ?";
try {
ps = connection.prepareStatement(query);
ps.setString(1, user.getFirstName());
ps.setString(2, user.getLastName());
ps.setString(3, user.getEmailAddress());
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
}
Try adding logs to update(User user) method. See whether control is coming to this place if atall.
I found the root cause in the second JSP see the code below.
<tr>
<td align="right">Email address:</td>
<td>${user.emailAddress}</td>
</tr>
The servlet's getParameter("emailAddress") method was actually getting a null value since there is no parameter name in the code above..
So, it should have been done like this:
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailaddress"
value="${user.emailaddress}">
</td>
</tr>
Note that the -input type="text"- is not necessary since the email address doesnt have to be modified like the name and firsname. So i should find a way to show the email address in something else than a input text box. But it works now