This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 7 years ago.
I am trying to show values from mysql table to a jsp table via servlet and I have done following
in BookSaleAuctionServlet
con = DriverManager.getConnection("jdbc:mysql://localhost/logins", "root", "");
try {
ArrayList<String> arr = new ArrayList<String>();
Statement stmt = con.createStatement();
ResultSet rst = stmt.executeQuery
("SELECT m.id,m.username,m.address,m.email,m.contact FROM members m");
request.setAttribute("memberList", rst);
request.getRequestDispatcher("MemberDetail.jsp").forward(request, response);
and in MemberDetail.jsp
<p>---------${memberList}</p>
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Contact</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:forEach var="row" items="${memberList}">
<tr>
<td><c:out value="${row.id}"/> </td>
<td><c:out value="${row}"></c:out> </td>
<td><c:out value="${row[0]}"></c:out> </td>
<td></td>
<td>Edit </td>
</tr>
</c:forEach>
</tbody>
</table>
Now i am not able to get values in the table and the value arriving from ${memberList} is com.mysql.jdbc.JDBC4ResultSet#166d6d3
I dont know how can i fetch value please help
Assume that you have a class User have the following attributes :-
class user{
private int id;
private String username;
private String address;
private String email;
private String contact;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
}
In your servlet :-
ArrayList<user> member= new ArrayList<user>();
while(rst.next()) {
user myUser = new user();
myUser.setUsername(rst.getString("name"));
myUser.setId(rst.getInt("id");
myUser.setAddress(rst.getString("address"));
myUser.setEmail(rst.getString("email"));
myUser.setContact(rst.getString("contact"));
member.add(myUser);
}
request.setAttribute("memberList", member);
In your Jsp:-
<c:forEach var="row" items="${memberList}">
<tr>
<td><c:out value="${row.id}"/> </td>
<td><c:out value="${row.username}"></c:out> </td>
<td><c:out value="${row.address}"></c:out> </td>
<td><c:out value="${row.email}"></c:out> </td>
<td><c:out value="${row.contact}"></c:out> </td>
<td></td>
<td>Edit </td>
</tr>
</c:forEach>
Related
I'm here again asking a question, I've tried asking this a while ago (for today) but I've reconstructed my code. So, my problem is that when I click the button to show the details from the database, it show me an error that Property Not Found, I'm confused as to why this error pops out, Here is an example of the error, as you can see it can read the elements in the database when I sysout it, displaying it in the console pic of error
)
//empServlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
empServices empserv= new empServices();
ArrayList <empGetSet> empgs = new ArrayList<empGetSet>();
if (request.getParameter("process")!=null && request.getParameter("process").equals("showdis")) {
empgs.addAll(empserv.getAll());
request.setAttribute("empdet", empgs);
RequestDispatcher rd = request.getRequestDispatcher("showdet.jsp"); //forward to xxxpage after submit by button
rd.forward(request,response);
}
//empServices
package emppackage;
import java.util.ArrayList;
public class empServices {
empServlet empservlet = new empServlet();
empDAO empdao = new empDAO();
public ArrayList <empGetSet> getAll()
{
return empdao.getAllEmp();
}
//empDAO
public ArrayList<empGetSet> getAllEmp()
{
ArrayList<empGetSet> empdetails = new ArrayList<empGetSet>();
try {
Connection conn = getConnection();
String showsql = "SELECT *FROM csemp;";
PreparedStatement psread= conn.prepareStatement(showsql);
ResultSet rsread = psread.executeQuery();
while (rsread.next())
{
empGetSet readgetset = new empGetSet();
readgetset.setFname(rsread.getString(1));
//System.out.println(readgetset.getFname());
System.out.println(rsread.getString(1));
readgetset.setLname(rsread.getString(2));
readgetset.setNameRes(rsread.getString(3));
readgetset.setSerials(rsread.getString(4));
readgetset.setJrss(rsread.getString(5));
readgetset.setBand(rsread.getString(6));
readgetset.setAcct(rsread.getString(7));
readgetset.setPMPs(rsread.getString(8));
readgetset.setsJRSS(rsread.getString(9));
readgetset.setOpenSeatDesc(rsread.getString(10));
readgetset.setReqSkills(rsread.getString(11));
readgetset.setReqBand(rsread.getString(12));
readgetset.setDreject(rsread.getString(13));
readgetset.setsRreject(rsread.getString(14));
readgetset.setDetActPlan(rsread.getString(15));
readgetset.setDataComplete(rsread.getString(16));
readgetset.setStat(rsread.getString(17));
empdetails.add(readgetset);
}
psread.close();
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return empdetails;
}
This is my Getters and Setters with really the same naming convention
package emppackage;
public class empGetSet {
private String Fname;
private String Lname;
private String NameRes;
private String Serials;
private String Jrss;
private String Band;
private String Acct;
private String PMPs;
private String sJRSS;
private String OpenSeatDesc;
private String ReqSkills;
private String ReqBand;
private String Dreject;
private String Rreject;
private String DetActPlan;
private String DataComplete;
private String Stat;
public String getFname() {
return Fname;
}
public void setFname(String Fname) {
this.Fname=Fname;
}
public String getLname() {
return Lname;
}
public void setLname(String Lname) {
this.Lname=Lname;
}
public String getNameRes() {
return NameRes;
}
public void setNameRes(String NameRes) {
this.NameRes=NameRes;
}
public String getSerials() {
return Serials;
}
public void setSerials(String Serials) {
this.Serials=Serials;
}
public String getJrss() {
return Jrss;
}
public void setJrss(String Jrss) {
this.Jrss=Jrss;
}
public String getBand() {
return Band;
}
public void setBand(String Band) {
this.Band=Band;
}
public String getAcct() {
return Acct;
}
public void setAcct(String Acct) {
this.Acct=Acct;
}
public String getPMPs() {
return PMPs;
}
public void setPMPs(String PMPs) {
this.PMPs=PMPs;
}
public String getsJRSS() {
return sJRSS;
}
public void setsJRSS(String sJRSS) {
this.sJRSS=sJRSS;
}
public String getOpenSeatDesc() {
return OpenSeatDesc;
}
public void setOpenSeatDesc(String OpenSeatDesc) {
this.OpenSeatDesc=OpenSeatDesc;
}
public String getReqSkills() {
return ReqSkills;
}
public void setReqSkills(String ReqSkills) {
this.ReqSkills=ReqSkills;
}
public String getReqBand() {
return ReqBand;
}
public void setReqBand(String Acct) {
this.Acct=Acct;
}
public String getDreject() {
return Dreject;
}
public void setDreject(String Dreject) {
this.Dreject=Dreject;
}
public String getRreject() {
return Rreject;
}
public void setsRreject(String Rreject) {
this.Rreject=Rreject;
}
public String getDetActPlan() {
return DetActPlan;
}
public void setDetActPlan(String DetActPlan) {
this.DetActPlan=DetActPlan;
}
public String getDataComplete() {
return DataComplete;
}
public void setDataComplete(String DataComplete) {
this.DataComplete=DataComplete;
}
public String getStat() {
return Stat;
}
public void setStat(String Stat) {
this.Stat=Stat;
}
}
This is my .jsp
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<!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>Show Details</title>
</head>
<body>
<div align="right"><button>Back</button></div>
<form action ="empServlet" method="get">
<table border =1 cellpadding="18">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Name of Resource (LN ID Format)</th>
<th>Serial Number</th>
<th>JRSS</th>
<th>Band</th>
<th>Account (Proposed)</th>
<th>PMP Seat</th>
<th>Seat JRSS</th>
<th>Open Seat Description</th>
<th>Required Skills</th>
<th>Required Band low/high</th>
<th>Date of Rejection</th>
<th>Reason for Rejection</th>
<th>Detailed Action Plan</th>
<th>Target Date of Completion</th>
<th>Status(Ongoing/Closed)</th>
<th colspan=2>Do This</th>
</tr>
</thead>
<tbody>
<c:forEach items ="${empdet}" var="empdet" >
<tr>
<td><c:out value ="${empdet.Fname}" /></td>
<td><c:out value ="${empdet.Lname}" /></td>
<td><c:out value ="${empdet.NameRes}" /></td>
<td><c:out value ="${empdet.Serials}" /></td>
<td><c:out value ="${empdet.Jrss}" /></td>
<td><c:out value ="${empdet.Band}" /></td>
<td><c:out value ="${empdet.Acct}" /></td>
<td><c:out value ="${empdet.PMPs}" /></td>
<td><c:out value ="${empdet.sJRSS}" /></td>
<td><c:out value ="${empdet.OpenSeatDesc}" /></td>
<td><c:out value ="${empdet.ReqSkills}" /></td>
<td><c:out value ="${empdet.ReqBand}" /></td>
<td><c:out value ="${empdet.Dreject}" /></td>
<td><c:out value ="${empdet.Rreject}" /></td>
<td><c:out value ="${empdet.DetActPlan}" /></td>
<td><c:out value ="${empdet.DataComplete}" /></td>
<td><c:out value ="${empdet.Stat}" /></td>
<td>Update</td>
<td>Delete</td>
</c:forEach>
</tbody>
</table>
<br>
Show All
</form>
</body>
</html>
I am trying to integrate hibernate with Spring. Here is the code,
Employee.java
package java4s.model;
import java.util.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.web.servlet.ModelAndView;
public class Employee {
#NotEmpty
private String userid;
#Size(min = 3, max = 20)
private String firstname;
#Size(min = 3, max = 20)
private String lastname;
#NotEmpty
private String mobileno;
#NotEmpty
#Size(min = 3, max = 20)
private String username;
#NotEmpty
#Size(min = 3, max = 20)
private String password;
#NotEmpty
#Pattern(regexp = ".+#.+\\.[a-z]+")
private String email;
#NotNull
#NotEmpty
private String birthDate;
#NotEmpty
private String profession;
private String studenterrors;
public String getUserid()
{
return userid;
}
public void setUserid(String userid)
{
this.userid = userid;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getFirstname()
{
return firstname;
}
public void setFirstname(String firstname)
{
this.firstname = firstname;
}
public String getLastname()
{
return lastname;
}
public void setLastname(String lastname)
{
this.lastname = lastname;
}
public String getMobileno()
{
return mobileno;
}
public void setMobileno(String mobileno)
{
this.mobileno = mobileno;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getBirthdate()
{
return birthDate;
}
public void setBirthdate(String birthDate)
{
this.birthDate = birthDate;
}
public String getProfession()
{
return profession;
}
public void setProfession(String profession)
{
this.profession = profession;
}
public String getStudenterrors()
{
return studenterrors;
}
public void setStudenterrors(String studenterrors)
{
this.studenterrors = studenterrors;
}
}
EmployeeServiceImpl.java
#SuppressWarnings("unchecked")
#Override
public List<Employee> getUserinfo(String username) {
// TODO Auto-generated method stub
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
String sql_query = "SELECT username, firstname, lastname, emailid, profession, mobileno, to_char(birthdate, 'MM/DD/YYYY') AS birthdate, password FROM EmployeeInfo WHERE username = ?";
Query query = session.createQuery(sql_query);
query.setString(0, username);
List<Employee> employees = (List<Employee>)query.list();
return employees;
}
LoginController.java
#RequestMapping(value = "/edit", method=RequestMethod.GET)
public ModelAndView EditMyInfo(ModelMap model, #ModelAttribute("editForm") Employee employee, HttpSession session) {
List<Employee> user_info = emp_service.getUserinfo((String)session.getAttribute("session_username"));
List<String> professionList = new ArrayList();
professionList.add("Developer");
professionList.add("Designer");
professionList.add("IT Manager");
model.put("professionList", professionList);
employee.setUsername(user_info.get(0).getUsername().toString());
employee.setFirstname(user_info.get(0).getFirstname().toString());
employee.setLastname(user_info.get(0).getLastname().toString());
employee.setEmail(user_info.get(0).getEmail().toString());
employee.setMobileno(user_info.get(0).getMobileno().toString());
employee.setBirthdate(user_info.get(0).getBirthdate());
return new ModelAndView("edit",model);
}
edit.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<c:if test="${session_username != null }">Hello ${session_username}!</c:if>
<font face="verdana" size="2">
${welcomeMessage} <BR><BR>
<form:form action="${pageContext.request.contextPath}/editemployee" method="POST" modelAttribute="editForm">
<table>
<tr>
<td colspan="2" align="center">Spring MVC Form Demo - Edit</td>
</tr>
<tr>
<td>User Name</td>
<td><form:input path="username" /></td>
</tr>
<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>Mobile No.</td>
<td><form:input path="mobileno" /></td>
</tr>
<tr>
<td>Password</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>BirthDate (mm/dd/yyyy)</td>
<td><form:input path="birthdate" /></td>
</tr>
<tr>
<td>Profession</td>
<td><form:select path="profession" items="${professionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</font>
</body>
</html>
Error :
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java4s.model.Employee
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to java4s.model.Employee
java4s.controller.LoginSuccessController.EditMyInfo(LoginSuccessController.java:106)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:776)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
I found the errors is on
employee.setUsername(user_info.get(0).getUsername().toString());
employee.setFirstname(user_info.get(0).getFirstname().toString());
employee.setLastname(user_info.get(0).getLastname().toString());
employee.setEmail(user_info.get(0).getEmail().toString());
employee.setMobileno(user_info.get(0).getMobileno().toString());
employee.setBirthdate(user_info.get(0).getBirthdate());
How can I solve this error?
There are some problems in your code
You need to add #Entity and #Table annotations to the Employ
as #KonstantinPavlov suggests.
You need the #Id annotation on userid.
This code is incorrect
String sql_query = "SELECT username, firstname, lastname,
emailid, profession, mobileno, to_char(birthdate, 'MM/DD/YYYY') AS
birthdate, password FROM EmployeeInfo WHERE username = ?";
Query query = session.createQuery(sql_query);
query.setString(0, username);
List<Employee> employees = (List<Employee>)query.list();
You need Employee but you use FROM EmployeeInfo. Hibernate can't convert your projections into Employee (it is need a transformer or the new operator with a constructor in the query). Your query looks like SQL, but you need HQL there.
String hqlQuery = "FROM Employee WHERE username = :userName";
Query query = session.createQuery(hqlQuery);
query.setParameter("userName", username);
List<Employee> employees = (List<Employee>)query.list();
You don't need to build SessionFactory for every request! You need create it using Spring's LocalSessionFactoryBean.
You open a session but don't close it.
You begin a transaction but don't commit or rollback it.
I am trying to connect my JSP servlets to a posgress database and I am currently using a java bean class which is playing the role of the middle man. I am experiencing some difficulties with making the registration form successfully store user information into the database. I would really appreciate if you would kindly help me out.
Thanks a lot in advance.
JSP servlet:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Register here</title>
</head>
<body>
<form method="post" action="registration.jsp">
<center>
<table border="1" width="30%" cellpadding="5">
<thead>
<tr>
<th colspan="2">Enter Information Here</th>
</tr>
</thead>
<tbody>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" value="" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" name="lname" value="" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="uname" value="" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" value="" /></td>
</tr>
<tr>
<td>Current Country</td>
<td><input type="text" name="country" value="" /></td>
</tr>
<tr>
<td>Current City</td>
<td><input type="text" name="city" value="" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
<td><input type="reset" value="Reset" /></td>
</tr>
<tr>
<td colspan="2">Already have an account? Login Here</td>
</tr>
</tbody>
</table>
</center>
</form>
</body>
The Java Bean that I use :
public class UserBean {
private int id;
private String username;
private String password;
private String email;
private String firstName;
private String lastName;
private String endDate;
private boolean validated;
public UserBean() {
// Empty constructor
}
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getEmail() {
return email;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEndDate() {
return endDate;
}
public boolean isValidated() {
return validated;
}
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setEmail(String email) {
this.email = email;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEndDate(String endDate) {
this.endDate = endDate;
}
public void setValidated(boolean validated) {
this.validated = validated;
}
}
Your POJO JavaBean won't magically get populated with the data. It has no connection to the database and no way to get or save data.
You need a controller that fetches data from the DB, creates model objects, and populates them with the data. The controller is also responsible for saving beans
You could write this yourself but it's generally better to use existing ORM frameworks like JPA2, a custom persistence provider API like Hibernate, or something like MyBatis. If you really want, you can hand-roll your controller with direct JDBC calls, injecting the connection from the environment, but that tends to produce a lot of boilerplate code for little benefit even with things like Spring JDBC to help smooth things over.
Some IDEs, like NetBeans and Eclipse, can even auto-generate models and controllers for you, though I've never been very happy with the results (particularly the failure to use a parent-class and generic methods and the lack of any sort of useful error handling).
A question about read and pass data from servlet to JSP
I want to create a Java EE project. Totally, it has 5 files in this project.
JSP Files: EmployeeInfo.jsp, EmployeeDetails.jsp
Servlets: EmployeeRegistrationServlet, EmployeeSearchServlet
Bean: Employee
EmployeeInfo.jsp file that gets either Employee Id or Employee Information. It have two Submit buttons. If user wants to search an Employee, an ID would be entered and it will call EmployeeSearchServlet, if user wants to add new Employee information, then EmployeeRegistrationServlet will be called with customer information entered. Here is the code:
EmployeeSearchServlet is supposed to search an employee with employee id that was entered by the end user. The job of the servlet is to find particular employee within a collection. Once the employee is found, the flow will be forwarded to EmployeeDetails.jsp.
EmployeeRegistrationServlet is supposed to add employees into a collection where store employees in memory.
If an employee is found, details of employee will be displayed on EmployeeDetails.jsp.
If a new employee is added, details of employee will be displayed on EmployeeDetails.jsp.
Here is my EmployeeInfo.jsp
<body>
<h1 align="center">Employee Information</h1>
<!--Form of find employee by employeeID -->
<form action="EmployeeSearchServlet" method="POST">
<fieldset>
<legend>Find Employee</legend>
Employee ID: <input type="text" name="findEmployeeID"><br>
<input type="submit" name="findEmployeeSubmit" value="Find Employee">
</fieldset>
</form>
<p></p>
<!--Form of add employee-->
<form action="EmployeeRegistrationServlet" method="POST">
<fieldset>
<legend>Employee Information</legend>
<table>
<tr>
<td>Employee ID (key)*: </td>
<td><input type="text" name="employeeID"></td>
</tr>
<tr>
<td>First Name:* </td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td>Last Name:* </td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td>Email: </td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Phone: </td>
<td><input type="text" name="phone"></td>
</tr>
<tr>
<td>Hire Date: </td>
<td><input type="text" name="hireDate"></td>
</tr>
<tr>
<td>Manager ID: </td>
<td><input type="text" name="managerID"></td>
</tr>
<tr>
<td>Department ID: </td>
<td><input type="text" name="departmentID"></td>
</tr>
</table>
<input type="submit" name="addEmployeeSubmit" value="Add Employee">
</fieldset>
</form>
</body>
Here is my Employee bean.
public class Employee {
private String employeeID;
private String firstName;
private String lastName;
private String email;
private String phoneNumber;
private String hireDate;
private String managerID;
private String departmentID;
public Employee(String newEmployeeID,
String newFirstName,
String newLastName,
String newEmail,
String newPhoneNumber,
String newHireDate,
String newManagerID,
String newDepartmentID){
this.employeeID = newEmployeeID;
this.firstName = newFirstName;
this.lastName = newLastName;
this.email = newEmail;
this.phoneNumber = newPhoneNumber;
this.hireDate = newHireDate;
this.managerID = newManagerID;
this.departmentID = newDepartmentID;
}
public void setEmployeeID(String newEmployeeID){
this.employeeID = newEmployeeID;
}
public void setFirstName(String newFirstName){
this.firstName = newFirstName;
}
public void setLastName(String newLastName){
this.lastName = newLastName;
}
public void setEmail(String newEmail){
this.email = newEmail;
}
public void setPhoneNumber(String newPhoneNumber){
this.phoneNumber = newPhoneNumber;
}
public void setHireDate(String newHireDate){
this.hireDate = newHireDate;
}
public void setManagerID(String newManagerID){
this.managerID = newManagerID;
}
public void setDepartmentID(String newDepartmentID){
this.departmentID = newDepartmentID;
}
public String getEmployeeID() {
return employeeID;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public String getHireDate(){
return hireDate;
}
public String getManagerID(){
return managerID;
}
public String getDepartmentID(){
return departmentID;
}
}
here is my EmployeeRegistrationServlet
#WebServlet("/EmployeeRegistrationServlet")
public class EmployeeRegistrationServlet extends HttpServlet {
private Map<String,Employee> employees;
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String employeeID = request.getParameter("employeeID").trim();
String firstName = request.getParameter("firstName").trim();
String lastName = request.getParameter("lastName").trim();
String email = request.getParameter("email").trim();
String phone = request.getParameter("phone").trim();
String hireDate = request.getParameter("hireDate").trim();
String managerID = request.getParameter("managerID").trim();
String departmentID = request.getParameter("departmentID").trim();
employees = new HashMap<String,Employee>();
Employee newAdd = new Employee(employeeID, firstName, lastName, email, phone, hireDate, managerID, departmentID);
request.getRequestDispatcher("../../../../WebContent/EmployeeDetail.jsp").forward(request,response);
}
}
My question is how to use EmployeeDetail.jsp read bean object passed from EmployeeRegistrationServlet? And how to Find an employee by searching the employee ID?
Please give me some suggestions. Thanks a lot.
My question is how to use EmployeeDetail.jsp read bean object passed from EmployeeRegistrationServlet?
You need to set the Object in request / session attribute to be available to forwarded jsp
how to Find an employee by searching the employee ID?
depends on your data store, for example if you are using mysql you need to use jdbc and query to get record by id
See
example on jsp wiki
servlet wiki
You have many choices. I would encourage you to look at this tutorial, and consider using <jsp:useBean id="myObject" class="myClass" scope="session"/> tags:
http://www.jsptut.com/forms.jsp
Here is the full JSTL tutorial from Oracle:
http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html
I have a table for which I am passing list of student objects from my spring controller method, On page load 3 rows are populated. I want the user to be able to add more rows delete existing rows on button click. Can anyone tell me how to achieve this. See below my controller and jsp code. On clicking add I want to add 3 more rows selecting check box and clicking delete row should delete the row. i want the the added columns to be binded
I am very new to jQuery is this possible without jQuery. If not please tell me in detail how to achieve this using jQuery
Student Entity
#Entity
#Table(name="STUDENT_REGISTRATION")
public class Student {
private int studentId;
private String firstName;
private String lastName;
private Date dob;
private String sex;
private String status;
private Date doj;
private int deptId;
private String deptName;
private int batchId;
private String batchName;
private int roleId;
private String roleName;
private String regNo;
public Student(){
}
public Student(int studentId, String firstName, String lastName, Date dob,
String sex, String status, Date doj, int deptId,
String deptName, int batchId, String batchName, int roleId,
String roleName, String regNo) {
super();
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
this.sex = sex;
this.status = status;
this.doj = doj;
this.deptId = deptId;
this.deptName = deptName;
this.batchId = batchId;
this.batchName = batchName;
this.roleId = roleId;
this.roleName = roleName;
this.regNo = regNo;
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="STUDENT_ID")
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
#Column(name="STUDENT_FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="STUDENT_LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name="DOB")
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
#Column(name="SEX")
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
#Column(name="STATUS")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
#Column(name="DOJ")
public Date getDoj() {
return doj;
}
public void setDoj(Date doj) {
this.doj = doj;
}
#Column(name="DEPT_ID")
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
#Column(name="DEPT_NAME")
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
#Column(name="BATCH_ID")
public int getBatchId() {
return batchId;
}
public void setBatchId(int batchId) {
this.batchId = batchId;
}
#Column(name="BATCH_NAME")
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
#Column(name="ROLE_ID")
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
#Column(name="ROLE_NAME")
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
#Column(name="REG_NO")
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo;
}
}
Student DTO
public class StudentDTO {
private int studentId;
private String firstName;
private String lastName;
private Date dob;
private String sex;
private String status;
private Date doj;
private int deptId;
private String deptName;
private int batchId;
private String batchName;
private int roleId;
private String roleName;
boolean select;
private String regNo;
public StudentDTO(){
}
public StudentDTO(int studentId, String firstName, String lastName,
Date dob, String sex, String status, Date doj, int deptId,
String deptName, int batchId, String batchName, int roleId,
String roleName, boolean select, String regNo) {
super();
this.studentId = studentId;
this.firstName = firstName;
this.lastName = lastName;
this.dob = dob;
this.sex = sex;
this.status = status;
this.doj = doj;
this.deptId = deptId;
this.deptName = deptName;
this.batchId = batchId;
this.batchName = batchName;
this.roleId = roleId;
this.roleName = roleName;
this.select = select;
this.regNo = regNo;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Date getDoj() {
return doj;
}
public void setDoj(Date doj) {
this.doj = doj;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public int getBatchId() {
return batchId;
}
public void setBatchId(int batchId) {
this.batchId = batchId;
}
public String getBatchName() {
return batchName;
}
public void setBatchName(String batchName) {
this.batchName = batchName;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public boolean isSelect() {
return select;
}
public void setSelect(boolean select) {
this.select = select;
}
public String getRegNo() {
return regNo;
}
public void setRegNo(String regNo) {
this.regNo = regNo;
}
}
Here I am adding 3 Student Objects
public List<StudentDTO> addStudentToList(){
List<StudentDTO> studentList = new ArrayList<StudentDTO>();
StudentDTO stud = new StudentDTO();
for(int i=0; i<3; i++){
studentList.add(stud);
}
return studentList;
}
Student Controller class
#RequestMapping(value="/addStudent", method=RequestMethod.GET)
public ModelAndView getStudentForm(ModelMap model)
{ List<StudentDTO> studentList = studentService.getStudentAttributesList();
//List<Integer> userIdForDropDown = userDAO.getAllUserIdForDropDown();
//model.addAttribute("userIdDropDown",userIdForDropDown);
List<String> deptList = configDAO.getDeptListForDropDown();
model.addAttribute("deptlist",deptList);
List<String> batchList = configDAO.getAllBatchForDropDrown();
model.addAttribute("batchList", batchList);
ModelAndView mav = new ModelAndView("add_student");
Student stu = new Student();
mav.getModelMap().put("add_student", stu);
StudentForm studentForm = new StudentForm();
studentForm.setStudentList(studentList);
model.addAttribute("studentForm",studentForm);
return mav;
}
#RequestMapping(value="/addStudent", method=RequestMethod.POST)
public String saveStudent(#ModelAttribute("add_student") StudentForm studenfForm, BindingResult result, SessionStatus status, ModelMap model) throws ParseException{
/*if(result.hasErrors()){
return "add_student";
}*/
List<StudentDTO> newList = (List<StudentDTO>) studenfForm.getStudentList();
List<Student> newList1 = new ArrayList<Student>();
for(StudentDTO stud:studenfForm.getStudentList()){
Student student = new Student();
student.setBatchId(stud.getBatchId());
student.setBatchName(stud.getBatchName());
student.setDeptId(stud.getDeptId());
student.setDeptName(stud.getDeptName());
SimpleDateFormat sdf = new SimpleDateFormat("DD/MM/YYYY");
Date dateWithoutTime = sdf.parse(sdf.format(new Date()));
student.setDob(stud.getDob());
student.setDoj(stud.getDoj());
student.setFirstName(stud.getFirstName());
student.setLastName(stud.getLastName());
student.setRegNo(stud.getRegNo());
student.setRoleId(stud.getRoleId());
student.setRoleName(stud.getRoleName());
student.setStatus(stud.getStatus());
student.setSex(stud.getSex());
student.setStudentId(stud.getStudentId());
newList1.add(student);
}
Integer saveStatus = studentDAO.saveStudentInfo(newList1);
//Integer res = roleDAO.saveRole(role);
if(saveStatus!=null){
status.setComplete();
model.addAttribute("savedMsg", "Student record saved Successfully.");
}
return "redirect:addStudent";
}
See my jsp page
<table bgcolor="white" width="1200" height="300" align="center" style="border-collapse: collapse;" border="1" bordercolor="#006699" >
<form:form action="addStudent" method="post" commandName="add_student" modelAttribute="studentForm">
<tr>
<td align="center" style="background-color: lightblue"><h3>Add Student</h3></td>
</tr>
<tr align="left">
<td align="left">
<input type="button" id="addrows" name="addrows" class="addperson" value="Add Rows">
<input type="button" id="removerows" class="removerows" value="Delete Rows" />
<input type="submit" value="Save" />
</td>
</tr>
<tr valign="middle" align="center">
<td align="center" valign="middle">
<table width="1200" height="200" style="border-collapse: collapse;" border="0" bordercolor="#006699" cellspacing="0" cellpadding="0">
<thead>
<tr height="1" bgcolor="lightblue">
<th colspan="1">
No
</th>
<th width="5">
Select
</th>
<th>
Reg No
</th>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Sex
</th>
<th>
DOB
</th>
<th>
DOJ
</th>
<th>
Dept Name
</th>
<th>
Role Name
</th>
<th>
Batch Name
</th>
<th>
Status
</th>
</tr>
</thead>
<tbody>
<c:forEach var="rows" items="${studentForm.studentList}" varStatus="status">
<tr class="${status.index % 2 == 0 ? 'even' : 'odd'}" >
<td width="15">
<b>${status.count}</b>
</td>
<td width="10">
<form:checkbox path="studentList[${status.index}].select"/>
</td>
<td><form:input path="studentList[${status.index}].regNo"/></td>
<td><form:input path="studentList[${status.index}].firstName"/></td>
<td><form:input path="studentList[${status.index}].lastName"/></td>
<td><form:select path="studentList[${status.index}].sex">
<form:option value="NONE" label="--- Select ---"/>
<form:option value="M" label="Male"/>
<form:option value="F" label="Female"/>
</form:select></td>
<td><form:input path="studentList[${status.index}].dob"/></td>
<td><form:input path="studentList[${status.index}].doj"/></td>
<td><form:select path="studentList[${status.index}].deptName">
<form:option value="NONE" label="--- Select ---"/>
<form:options items="${deptlist}" />
</form:select></td>
<td><form:select path="studentList[${status.index}].roleName">
<form:option value="NONE" label="--- Select ---"/>
<form:option value="ROLE_STUDENT" label="Student"/>
<form:option value="ROLE_BATCHREP" label="Batch Rep"/>
</form:select></td>
<td><form:select path="studentList[${status.index}].batchName">
<form:option value="NONE" label="--- Select ---"/>
<form:options items="${batchList}" />
</form:select>
</td>
<td><form:select path="studentList[${status.index}].status">
<form:option value="NONE" label="--- Select ---"/>
<form:option value="E" label="Enable"/>
<form:option value="D" label="Disable"/>
</form:select></td>
</tr>
</c:forEach>
</tbody>
</table>
</td>
</tr>
<tr align="center">
<td width="100" align="center"><B>
${savedMsg}
</B>
</td>
</tr>
</form:form>
</table>
Even though this thread is older, For the benefit of others who is in need of this.
Let me explain with a minimal code and User example with firstName, email, userName and gender fields so that people won't get confused with bigger code.
Consider you are sending 3 empty users in usersList from controller this will creates 3 empty rows. If you inspect/view page source you will see
Rows(<input> tags) with different id's like list0.firstName
list1.firstName
Rows(<input> tags) with different names like list[0].firstName
list[1].firstName
Whenever form is submitted id's are not considered by server(added for only for helping client side validations), but name attribute will be interpreted as request parameter and are used to construct your modelAttribute, hence attribute names are very important while inserting rows.
Adding row
So, How to construct/append new rows?
If i submit 6 users from UI, controller should receive 6 user object from usersList. Steps to achieve the same is given below
1. Right click -> view page source. You will see rows like this(you can see *[0].* in first row and *[1].* in second row)
<tr>
<td><input id="list0.firstName" name="list[0].firstName" type="text" value=""/></td>
<td><input id="list0.email" name="list[0].email" type="text" value=""/></td>
<td><input id="list0.userName" name="list[0].userName" type="text" value=""/></td>
<td>
<span>
<input id="list0.gender1" name="list[0].gender" type="radio" value="MALE" checked="checked"/>Male
</span>
<span>
<input id="list0.gender2" name="list[0].gender" type="radio" value="FEMALE"/>Female
</span>
</td>
</tr>
<tr>
<td><input id="list1.firstName" name="list[1].firstName" type="text" value=""/></td>
<td><input id="list1.email" name="list[1].email" type="text" value=""/></td>
<td><input id="list1.userName" name="list[1].userName" type="text" value=""/></td>
<td>
<span>
<input id="list1.gender1" name="list[1].gender" type="radio" value="MALE" checked="checked"/>Male
</span>
<span>
<input id="list1.gender2" name="list[1].gender" type="radio" value="FEMALE"/>Female
</span>
</td>
</tr>
Copy first row and construct a javascript string and replace '0' with variable name index. As given in below sample
'<tr>'+
'<td><input id="list'+ index +'.firstName" name="list['+ index +'].firstName" type="text" value=""/></td>'+
'<td><input id="list'+ index +'.email" name="list['+ index +'].email" type="text" value=""/></td>'+
...
'</tr>';
Append the constructed row to the <tbody>. Rows get added in UI also on submission of form newly added rows will be received in controller.
Deleting row
Deleting row is little bit complicated, i will try to explain in easiest way
Suppose you added row0, row1, row2, row3, row4, row5
Deleted row2, row3. Do not just hide the row but remove it from the
DOM by catching event.
Now row0,row1,row4,row5 will get submitted but in the controller your
userList will have 6 user object but user[2].firstName will be null
and user[3].firstName will be null.
So in your controller iterate and check for null and remove the
user.(Use iterator don't use foreach to remove user object)
Posting code to benefit beginners.
// In Controller
#RequestMapping(value = "/app/admin/add-users", method = RequestMethod.GET)
public String addUsers(Model model, HttpServletRequest request)
{
List<DbUserDetails> usersList = new ArrayList<>();
ListWrapper userListWrapper = new ListWrapper();
userListWrapper.setList(usersList);
DbUserDetails user;
for(int i=0; i<3;i++)
{
user = new DbUserDetails();
user.setGender("MALE"); //Initialization of Radio button/ Checkboxes/ Dropdowns
usersList.add(user);
}
model.addAttribute("userListWrapper", userListWrapper);
model.addAttribute("roleList", roleList);
return "add-users";
}
#RequestMapping(value = "/app/admin/add-users", method = RequestMethod.POST)
public String saveUsers(#ModelAttribute("userListWrapper") ListWrapper userListWrapper, Model model, HttpServletRequest request)
{
List<DbUserDetails> usersList = userListWrapper.getList();
Iterator<DbUserDetails> itr = usersList.iterator();
while(itr.hasNext())
{
if(itr.next().getFirstName() == null)
{
itr.remove();
}
}
userListWrapper.getList().forEach(user -> {
System.out.println(user.getFirstName());
});
return "add-users";
}
//POJO
#Entity
#Table(name = "userdetails")
#XmlRootElement(name = "user")
public class DbUserDetails implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String firstName;
private String userName;
private String email;
private String gender;
//setters and getters
}
//list wrapper
public class ListWrapper
{
private List<DbUserDetails> list;
//setters and getters
}
In JSP
<form:form method="post" action="${pageContext.request.contextPath}/app/admin/add-users" modelAttribute="userListWrapper">
<table class="table table-bordered">
<thead>
<tr>
<th><spring:message code="app.userform.firstname.label"/></th>
<th><spring:message code="app.userform.email.label"/></th>
<th><spring:message code="app.userform.username.label"/></th>
<th><spring:message code="app.userform.gender.label"/></th>
</tr>
</thead>
<tbody id="tbodyContainer">
<c:forEach items="${userListWrapper.list}" var="user" varStatus="loop">
<tr>
<td><form:input path="list[${loop.index}].firstName" /></td>
<td><form:input path="list[${loop.index}].email" /></td>
<td><form:input path="list[${loop.index}].userName" /></td>
<td>
<span>
<form:radiobutton path="list[${loop.index}].gender" value="MALE" /><spring:message code="app.userform.gender.male.label"/>
</span>
<span>
<form:radiobutton path="list[${loop.index}].gender" value="FEMALE" /><spring:message code="app.userform.gender.female.label"/>
</span>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<div class="offset-11 col-md-1">
<button type="submit" class="btn btn-primary">SAVE ALL</button>
</div>
</form:form>
Javascript needs to be included in JSP
var currentIndex = 3; //equals to initialRow (Rows shown on page load)
function addRow()
{
var rowConstructed = constructRow(currentIndex++);
$("#tbodyContainer").append(rowConstructed);
}
function constructRow(index)
{
return '<tr>'+
'<td><input id="list'+ index +'.firstName" name="list['+ index +'].firstName" type="text" value=""/></td>'+
'<td><input id="list'+ index +'.email" name="list['+ index +'].email" type="text" value=""/></td>'+
'<td><input id="list'+ index +'.userName" name="list['+ index +'].userName" type="text" value=""/></td>'+
'<td>'+
'<span>'+
'<input id="list'+ index +'.gender1" name="list['+ index +'].gender" type="radio" value="MALE" checked="checked"/>Male'+
'</span>'+
'<span>'+
'<input id="list'+ index +'.gender'+ index +'" name="list['+ index +'].gender" type="radio" value="FEMALE"/>Female'+
'</span>'+
'</td>'+
'</tr>';
}