how to create Multiple EmployeeBean objects - java

jsp page:
<%#page language="java" contentType="text/html charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Timesheet Page</title>
</head>
<body>
<header>
<h2>WEEKLY TIME SHEET MANAGEMENT V 1.0</h2>
</header>
<form action="TimeSheet" method="post">
<fieldset style="width: 90%">
<legend>Timesheet</legend>
<h2>Time Sheet application</h2>
<table border=1>
<tr><th>Employee ID</th><th>Date</th><th>Time In</th><th>Time Out</th><th>Lunch</th><th>After Lunch Time in</th><th>After Lunch Time out</th><th>Task Description</th><th>Total Hours</th><th>Overtime</th> </tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
</table>
</fieldset>
<input type="submit" value="Submit">
</form>
Logout
</body>
</html>
EmployeeBean:
Its for only one row.
package com.eis.bean;
public class EmployeeBean {
private String empid;
private java.sql.Date logindate;
private String logintime;
private String logouttime;
private String lunch;
private String afterlunchlogin;
private String afterlunchlogout;
private String task;
private String total;
private String overtime;
public String getEmpid() {
return empid;
}
public void setEmpid(String empid) {
this.empid = empid;
}
public java.sql.Date getLogindate() {
return logindate;
}
public void setLogindate(java.sql.Date logindate) {
this.logindate = logindate;
}
public String getLogintime() {
return logintime;
}
public void setLogintime(String logintime) {
this.logintime = logintime;
}
public String getLogouttime() {
return logouttime;
}
public void setLogouttime(String logouttime) {
this.logouttime = logouttime;
}
public String getLunch() {
return lunch;
}
public void setLunch(String lunch) {
this.lunch = lunch;
}
public String getAfterlunchlogin() {
return afterlunchlogin;
}
public void setAfterlunchlogin(String afterlunchlogin) {
this.afterlunchlogin = afterlunchlogin;
}
public String getAfterlunchlogout() {
return afterlunchlogout;
}
public void setAfterlunchlogout(String afterlunchlogout) {
this.afterlunchlogout = afterlunchlogout;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getOvertime() {
return overtime;
}
public void setOvertime(String overtime) {
this.overtime = overtime;
}
#Override
public String toString() {
return "EmployeeBean [empid=" + empid + ",logindate=" + logindate + ", logintime=" + logintime+ ", logouttime=" + logouttime + ", lunch=" + lunch+ ", afterlunchlogin=" + afterlunchlogin+ ", afterlunchlogout=" + afterlunchlogout+ ", task=" + task+ ", total=" + total+ ",overtime=" + overtime+ "]";
}
}
this EmployeeBean is only for 1 row table, but i want to make that for five rows that to I wanted to know how to create multiple EmployeeBean Objects. please help...
Thnaks!

can you try this,
<%! int TOTAL_NUMBER_OF_ROW = 10; %>
<form action="TimeSheet" method="post">
<fieldset style="width: 90%">
<legend>Timesheet</legend>
<h2>Time Sheet application</h2>
<table border=1>
<tr><th>Employee ID</th><th>Date</th><th>Time In</th><th>Time Out</th><th>Lunch</th><th>After Lunch Time in</th><th>After Lunch Time out</th><th>Task Description</th><th>Total Hours</th><th>Overtime</th> </tr>
<%for(int j =0;j<TOTAL_NUMBER_OF_ROW;j++){ %>
<tr>
<td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td>
</tr>
<%}%>
</table>
</fieldset>
<input type="submit" value="Submit">
</form>

Related

how to set each row to pass its values to servlet - whatever input I click, I have always first row

Why I can only count value for first row, though Jsp displays every row with correct values.
It always pass first row of data to the Servlet. If I choose first row it works, but if I choose any other it takes values of first row and program collapse due to empty string.
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
PrintWriter printWriter = response.getWriter();
String currency = request.getParameter("currency");
int id = Integer.parseInt(request.getParameter("id"));
float rates = Float.parseFloat(request.getParameter("rates"));
float amount =
Float.parseFloat(request.getParameter("amount"));;
float euro = amount * rates;
printWriter.append(String.valueOf(id)).append(" : ");
printWriter.append(currency).append(" - ");
printWriter.append("rate : ").append(String.valueOf(rates));
printWriter.append(" ---> You have got
").append(String.valueOf(euro)).append("
Euros");
}
<form action="/exchangeServlet" method="post">
<table border="1">
<tr>
<th>Currency</th>
<th>Rate</th>
<th>Amount</th>
<th>Action</th>
</tr>
<c:forEach var="tempValue" items="${kalkulatorList}"
varStatus="counter">
<tr>
<input type="hidden" name="id" value="${tempValue.id}">
<td><input type="hidden" name="currency"
value="${tempValue.currency}">${tempValue.currency}</td>
<td><input type="hidden" name="rates"
value="${tempValue.rates}">${tempValue.rates}</td>
<td><input type="number" name="amount" placeholder="enter
amount"/></td>
<td><input type="submit" value="Exchange"></td>
</tr>
</c:forEach>
</table>
</form>
JSP view after loaded data from a xml file:
<tr>
<td><input type="hidden" name="currency"
value="USD">USD</td>
<td><input type="hidden" name="rates"
value="1.0067">1.0067</td>
<td><input type="number" name="amount" value="0.0"
placeholder="enter amount"/></td>
<td><a href="/exchangeServlet?
command=Exchange&currencyId=2">Exchange</a></td>
</tr>
<tr>
<td><input type="hidden" name="currency"
value="JPY">JPY</td>
<td><input type="hidden" name="rates"
value="138.02">138.02</td>
<td><input type="number" name="amount" value="0.0"
placeholder="enter amount"/></td>
<td><a href="/exchangeServlet?
command=Exchange&currencyId=3">Exchange</a></td>
</tr>
<tr>
<td><input type="hidden" name="currency"
value="BGN">BGN</td>
<td><input type="hidden" name="rates"
value="1.9558">1.9558</td>
<td><input type="number" name="amount" value="0.0"
placeholder="enter amount"/></td>
<td><a href="/exchangeServlet?
command=Exchange&currencyId=4">Exchange</a></td>
</tr>

Thymeleaf Map Form Binding

db.html
<div th:each="pr, stat: *{mergeMap}">
<tr>
<td><input type="text" name="key" th:value="${pr.key}" /></td>
<td><input type="text" name="value" th:value="${pr.value}" /></td>
</tr>
</div>
On submitting this input, i always get mergeMap to be empty at the Spring Controller. What should be done to get the value of mergeMap?
Controller.java
#RequestMapping(value = "/shot")
public String saveMergeProducts(#ModelAttribute(value="prod") MergedProductInfoDTO prod, BindingResult bindingResult,
Model model, HttpServletRequest request) {
System.out.println(prod.toString());
return "forward:/backoffice/db";
}
HTML
<form action="#" th:action="#{shot}" method="POST" th:object="${prod}">
<tr>
<td><span th:text="${index.index}"></span></td>
<td><input type="text" name="id" th:value="*{id}" th:readonly="readonly" /></td>
<td><input type="text" name="categoryName" th:value="*{categoryName}" th:readonly="readonly" /></td>
<td><input type="text" name="subCategoryName" th:value="*{subCategoryName}" th:readonly="readonly" /></td>
<td><input type="text" name="productBrand" th:value="*{productBrand}" /></td>
<td><input type="text" name="productSubBrand" th:value="*{productSubBrand}" /></td>
<td><input type="text" name="series" th:value="*{series}" /></td>
<td><input type="text" name="model" th:value="*{model}" /></td>
</tr>
<tr>
<td colspan="7">
<tr>
<th>KEY</th>
<th>VALUE</th>
</tr>
<div th:each="pr, stat: *{mergeMap}">
<tr>
<td><input type="text" name="mergeMapKey" th:value="${pr.key}" /></td>
<td><input type="text" name="mergeMapValue" th:value="${pr.value}" /></td>
</tr>
</div>
</table>
</td>
<td><input type="text" name="tags" th:value="*{tags}" /></td>
<td><input type="submit" value="Submit" /></td>
</tr>
To access the Map property of the form-backing bean, use the __${...}__ preprocessor
<div th:each="pr, stat: *{mergeMap}">
<tr>
<td><input type="text" name="value" th:value="${pr.key}" readonly="true"/></td>
<td><input type="text" name="value" th:field="*{mergeMap[__${pr.key}__]}"/></td>
</tr>
</div>
What it does it evaluates the inner expression first before evaluating the whole expression. Note that in this case, ${pr.key} should not be modified so that the update will be reflected to the map property of the bean bound to the form.
Reference : http://www.thymeleaf.org/doc/tutorials/2.1/thymeleafspring.html#dynamic-fields

insert 5 rows of data in the database using servlet and jsp

I want to insert 5 rows of data in mysql database. I know how to do it for 1 row at a time but I dont know how to send more than one row.
timesheet.jsp
<%#page language="java" contentType="text/html charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
function updateHours(row){
var $date = row.find('[name="date"]');
var $time1 = row.find('[name="logintime"]');
var $time2 = row.find('[name="logouttime"]');
var $time3 = row.find('[name="lunch"]');
var $time4 = row.find('[name="afterlunchlogin"]');
var $time5 = row.find('[name="afterlunchlogout"]');
var $diff = row.find('.totalTime');
var $over = row.find('.overTime');
if($time1.val() && $time2.val() && $time3.val() && $time4.val() && $time5.val())
{
var dateInput = $date.val();
var dtStart = new Date(dateInput + " " + $time1.val());
var dtEnd = new Date(dateInput + " " + $time2.val());
var dtLunch= new Date(dateInput + " " + $time3.val());
var dtStartafterlunch = new Date(dateInput + " " + $time4.val());
var dtEndafterlunch = new Date(dateInput + " " + $time5.val());
var diff = ((dtEnd - dtStart)+(dtEndafterlunch-dtStartafterlunch)) / 1000;
var totalTime = 0;
var overTime = 0;
if (diff > 60*60*8) {
overTime = formatDate(diff - 60*60*8);
} else {
totalTime = formatDate(diff);
}
totalTime = formatDate(diff);
$diff.val(totalTime);
$over.val(overTime);
}
}
function formatDate(diff){
var hours = parseInt( diff / 3600 ) % 24;
var minutes = parseInt( diff / 60 ) % 60;
var seconds = diff % 60;
return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
}
$(".start, .end, .lunch, .startafterlunch, .endafterlunch, .totalTime").on("change, keyup", function(){
debugger
updateHours($(this).closest('tr'));
});
});
</script>
<title>Timesheet Page</title>
</head>
<body>
<header>
<h2>WEEKLY TIME SHEET MANAGEMENT V 1.0</h2>
</header>
<form action="TimeSheet" method="post">
<fieldset style="width: 90%">
<legend>Timesheet</legend>
<h2>Time Sheet application</h2>
<table border=1>
<tr><th>Employee ID</th><th>Date</th><th>Time In</th><th>Time Out</th><th>Lunch</th><th>After Lunch Time in</th><th>After Lunch Time out</th><th>Task Description</th><th>Total Hours</th><th>Overtime</th> </tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
<tr> <td><input type="text" name="empid" required="required" /></td>
<td><input type="date" id="date" name="date"/></td>
<td><input type="time" class="start" name="logintime"/></td>
<td><input type="time" class="end"name="logouttime" /></td>
<td><input type="time" class="lunch" name="lunch" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin"/></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout"/></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input class="totalTime" readonly="readonly" /></td>
<td><input class="overTime" readonly="readonly" /></td></tr>
</table>
</fieldset>
<input type="submit" value="Submit">
</form>
Logout
</body>
</html>
In TimsheetDao.java
package com.eis.Dao;
import com.eis.bean.ConnectionProvider;
import com.eis.bean.EmployeeBean;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class TimeSheetDao {
public static int insert(EmployeeBean eb,String sql) throws Exception {
int i=0;
PreparedStatement ps=null;
System.out.println("In TimesheetDao");
Connection conn=ConnectionProvider.getConn();
try{
System.out.println(" in try in Timesheetdao");
ps = conn.prepareStatement(sql);
ps.setString(1,eb.getEmpid());
// ps.setDate(2, (java.sql.Date) eb.getLoginDate());
// ps.setDate(3, (Date) eb.getLoginTime());
// ps.setDate(4, (Date) eb.getLogoutTime());
ps.setDate(2,new Date(eb.getLogindate().getTime()));
ps.setString(3,eb.getLogintime());
ps.setString(4,eb.getLogouttime());
ps.setString(5,eb.getLunch());
ps.setString(6,eb.getAfterlunchlogin());
ps.setString(7,eb.getAfterlunchlogout());
ps.setString(8,eb.getTask());
ps.setString(9,eb.getTotal());
ps.setString(10,eb.getOvertime());
i=ps.executeUpdate();
/*rs = pst.executeQuery();
status = rs.next(); */
}
catch(Exception e){
System.out.println(e);
}
finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return i;
}
}
In TimeSheetServlet.java
package com.eis.servlet;
import com.eis.Dao.TimeSheetDao;
import com.eis.bean.EmployeeBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class TimeSheet extends HttpServlet {
private static final long serialVersionUID = 1L;
private TimeSheetDao dao;
public TimeSheet() {
super();
dao = new TimeSheetDao();
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ParseException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
EmployeeBean eb = new EmployeeBean();
String Emp_id=request.getParameter("empid");
eb.setEmpid(Emp_id);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
Date logindate = new java.sql.Date(formatter.parse(request.getParameter("logindate")).getTime());
eb.setLogindate((java.sql.Date) logindate);
String LoginTime=request.getParameter("logintime");
eb.setLogintime(LoginTime);
String LogoutTime=request.getParameter("logouttime"); eb.setLogouttime(LogoutTime);
String Lunch=request.getParameter("lunch"); eb.setLunch(Lunch);
String AfterLunchLogin=request.getParameter("afterlunchlogin"); eb.setAfterlunchlogin(AfterLunchLogin);
String AfterLunchLogout=request.getParameter("afterlunchlogout"); eb.setAfterlunchlogout(AfterLunchLogout);
String TaskDescription=request.getParameter("task"); eb.setTask(TaskDescription);
String TotalHours=request.getParameter("total"); eb.setTotal(TotalHours);
String OverTime=request.getParameter("overtime"); eb.setOvertime(OverTime);
System.out.println(request.getParameter("empid"));
HttpSession session = request.getSession(true);
try{if (Emp_id!=null){
session.setAttribute("Emp_id",Emp_id);}
}catch(Exception e){e.printStackTrace();}
try{if (logindate!=null){
session.setAttribute("LoginDate",logindate);}
}catch(Exception e){e.printStackTrace();}
try{if (LoginTime!=null){
session.setAttribute("LoginTime",LoginTime);}
}catch(Exception e){e.printStackTrace();}
try{if (LogoutTime!=null){
session.setAttribute("LogoutTime",LogoutTime);}
}catch(Exception e){e.printStackTrace();}
try{if (Lunch!=null){
session.setAttribute("Lunch",Lunch);}
}catch(Exception e){e.printStackTrace();}
try{if (AfterLunchLogin!=null){
session.setAttribute("AfterLunchLogin",AfterLunchLogin);}
}catch(Exception e){e.printStackTrace();}
try{if (AfterLunchLogout!=null){
session.setAttribute("AfterLunchLogout",AfterLunchLogout);}
}catch(Exception e){e.printStackTrace();}
try{if (TaskDescription!=null){
session.setAttribute("TaskDescription",TaskDescription);}
}catch(Exception e){e.printStackTrace();}
try{if (TotalHours!=null){
session.setAttribute("TotalHours",TotalHours);}
}catch(Exception e){e.printStackTrace();}
try{if (OverTime!=null){
session.setAttribute("OverTime",OverTime);}
}catch(Exception e){e.printStackTrace();}
TimeSheetDao dao = new TimeSheetDao();
System.out.println("before sql");
String sql= "insert into logintable values(?,?,?,?,?,?,?,?,?,?)";
System.out.println("after sql");
try {
System.out.println("in try servlet after sql");
int status = TimeSheetDao.insert(eb, sql);
System.out.println("in try dao after sql");
if(status!=0){
out.print("<p style=\"color:Green\">Record saved successfully!!</p>");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
else{
out.print("<p style=\"color:red\">**Record cannot be saved!**</p>");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
}
catch(Exception e){
e.printStackTrace();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ParseException ex) {
Logger.getLogger(TimeSheet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ParseException ex) {
Logger.getLogger(TimeSheet.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
EmployeeBean:
package com.eis.bean;
import java.util.Date;
public class EmployeeBean {
private String empid;
private java.sql.Date logindate;
private String logintime;
private String logouttime;
private String lunch;
private String afterlunchlogin;
private String afterlunchlogout;
private String task;
private String total;
private String overtime;
public String getEmpid() {
return empid;
}
public void setEmpid(String empid) {
this.empid = empid;
}
public java.sql.Date getLogindate() {
return logindate;
}
public void setLogindate(java.sql.Date logindate) {
this.logindate = logindate;
}
public String getLogintime() {
return logintime;
}
public void setLogintime(String logintime) {
this.logintime = logintime;
}
public String getLogouttime() {
return logouttime;
}
public void setLogouttime(String logouttime) {
this.logouttime = logouttime;
}
public String getLunch() {
return lunch;
}
public void setLunch(String lunch) {
this.lunch = lunch;
}
public String getAfterlunchlogin() {
return afterlunchlogin;
}
public void setAfterlunchlogin(String afterlunchlogin) {
this.afterlunchlogin = afterlunchlogin;
}
public String getAfterlunchlogout() {
return afterlunchlogout;
}
public void setAfterlunchlogout(String afterlunchlogout) {
this.afterlunchlogout = afterlunchlogout;
}
public String getTask() {
return task;
}
public void setTask(String task) {
this.task = task;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getOvertime() {
return overtime;
}
public void setOvertime(String overtime) {
this.overtime = overtime;
}
#Override
public String toString() {
return "EmployeeBean [empid=" + empid + ",logindate=" + logindate + ", logintime=" + logintime+ ", logouttime=" + logouttime + ", lunch=" + lunch+ ", afterlunchlogin=" + afterlunchlogin+ ", afterlunchlogout=" + afterlunchlogout+ ", task=" + task+ ", total=" + total+ ",overtime=" + overtime+ "]";
}
}
I dont know how to make employeebean to list type... pelase check the Timesheetservlet and timesheetdao.
please help me to insert 5 rows in database.
thanks!
I have changed your jsp to have different names for the different rows.
and also changed the serverlet code to read and build the list of employee bean.
once you do these changes you can use the logic mentioned by the chrisI08 abovve.
timesheet.jsp.
<%#page language="java" contentType="text/html charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Timesheet Page</title>
</head>
<body>
<form action="TimeSheetServlet" method="post">
<fieldset style="width: 90%">
<legend>Timesheet</legend>
<table>
<thead><tr><th>Employee ID</th><th>Date</th><th>Time In</th><th>Time Out</th><th>Lunch</th><th>After Lunch Time in</th><th>After Lunch Time out</th><th>Task Description</th><th>Total Hours</th><th>Overtime</th> </tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="empid1" required="required" /></td>
<td><input type="date" id="date" name="logindate1" required="required" /></td>
<td><input type="time" class="start" name="logintime1" required="required" /></td>
<td><input type="time" class="end" name="logouttime1" required="required" /></td>
<td><input type="time" class="lunch" name="lunch1" required="required" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin1" required="required" /></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout1" required="required" /></td>
<td><input type="textarea" name="1" required="required" /></td>
<td><input type="time" class="totalTime" name="total1" /></td>
<td><input type="time" class="overTime" name="overtime1" required="required" /></td>
</tr>
<tr>
<td><input type="text" name="empid2" required="required" /></td>
<td><input type="date" id="date" name="logindate2" required="required" /></td>
<td><input type="time" class="start" name="logintime2" required="required" /></td>
<td><input type="time" class="end" name="logouttime2" required="required" /></td>
<td><input type="time" class="lunch" name="lunch2" required="required" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin2" required="required" /></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout2" required="required" /></td>
<td><input type="textarea" name="task2" required="required" /></td>
<td><input type="time" class="totalTime" name="total2" /></td>
<td><input type="time" class="overTime" name="overtime2" required="required" /></td>
</tr>
<tr>
<td><input type="text" name="empid3" required="required" /></td>
<td><input type="date" id="date" name="logindate3" required="required" /></td>
<td><input type="time" class="start" name="logintime3" required="required" /></td>
<td><input type="time" class="end" name="logouttime3" required="required" /></td>
<td><input type="time" class="lunch" name="lunch3" required="required" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin3" required="required" /></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout3" required="required" /></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input type="time" class="totalTime" name="total3" /></td>
<td><input type="time" class="overTime" name="overtime3" required="required" /></td>
</tr>
<tr>
<td><input type="text" name="empid4" required="required" /></td>
<td><input type="date" id="date" name="logindate4" required="required" /></td>
<td><input type="time" class="start" name="logintime4" required="required" /></td>
<td><input type="time" class="end" name="logouttime4" required="required" /></td>
<td><input type="time" class="lunch" name="lunch4" required="required" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin4" required="required" /></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout4" required="required" /></td>
<td><input type="textarea" name="task" required="required" /></td>
<td><input type="time" class="totalTime" name="total4" /></td>
<td><input type="time" class="overTime" name="overtime4" required="required" /></td>
</tr>
<tr>
<td><input type="text" name="empid5" required="required" /></td>
<td><input type="date" id="date" name="logindate5" required="required" /></td>
<td><input type="time" class="start" name="logintime5" required="required" /></td>
<td><input type="time" class="end" name="logouttime5" required="required" /></td>
<td><input type="time" class="lunch" name="lunch5" required="required" /></td>
<td><input type="time" class="startafterlunch" name="afterlunchlogin5" required="required" /></td>
<td><input type="time" class="endafterlunch" name="afterlunchlogout5" required="required" /></td>
<td><input type="textarea" name="task5" required="required" /></td>
<td><input type="time" class="totalTime" name="total5" /></td>
<td><input type="time" class="overTime" name="overtime5" required="required" /></td>
</tr>
</tbody>
</table>
</fieldset>
<input type="submit" value="Submit">
</form>
Logout
</body>
</html>
servlet:
List<EmployeeBean> ebList= ArrayList<EmployeeBean>();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
for(int i=1;i<=5;i++){
EmployeeBean eb = new EmployeeBean();
eb.setEmpid(Emp_id);
Date logindate = new java.sql.Date(formatter.parse(request.getParameter("logindate"+i)).getTime());
eb.setLogindate((java.sql.Date) logindate);
//String Date=request.getParameter("logindate");
String LoginTime=request.getParameter("logintime"+i);
eb.setLogintime(LoginTime);
eb.setLogouttime(request.getParameter("logouttime"+i));
eb.setLunch(request.getParameter("lunch"+i));
eb.setAfterlunchlogin(request.getParameter("afterlunchlogin"+i));
eb.setAfterlunchlogout(request.getParameter("afterlunchlogout"+i));
eb.setTask(request.getParameter("task"+i));
eb.setTotal(request.getParameter("total"+i));
eb.setOvertime(request.getParameter("overtime"+i));
}
TimeSheetDao.insert(ebList);
Note: I have not compiled this code.you may need to change few things.
You need to use batch inserts: http://viralpatel.net/blogs/batch-insert-in-java-jdbc/ Look at "SQL Injection Safe Batch" section. I have modified the TimeSheetDao.insert method as below:
import java.sql.Connection;
import java.sql.PreparedStatement;
public class TimeSheetDao {
// this sql string can be static final
public static final String sql= "insert into logintable values(?,?,?,?,?,?,?,?,?,?)";
public static int insert(List<EmployeeBean> employees) throws Exception {
Connection connection = new getConnection();
PreparedStatement ps = connection.prepareStatement(sql);
try {
for (EmployeeBean employee: employees) {
// set parameters here
ps.setDate(2,new Date(eb.getLogindate().getTime()));
ps.setString(3,eb.getLogintime());
ps.setString(4,eb.getLogouttime());
ps.setString(5,eb.getLunch());
ps.setString(6,eb.getAfterlunchlogin());
ps.setString(7,eb.getAfterlunchlogout());
ps.setString(8,eb.getTask());
ps.setString(9,eb.getTotal());
ps.setString(10,eb.getOvertime());
ps.addBatch();
}
ps.executeBatch();
} finally {
ps.close();
connection.close();
}
}

Cannot add data into database for crud using servlet

<form action="addCustServlet" method="POST" name="frmAddUser">
<table>
<tr>
<td><h3 class="templatemo-gold">ID Number: </h3></td>
<td>
<input type="text" name="cust_id" size="12" value="<c:out value="${customer.cust_id}" />" /> <br/><br/></td>
</tr>
<tr>
<td><h3 class="templatemo-gold">Name: </h3></td>
<td><input type="text" name="custName" size="50"
value="<c:out value="${customer.custName}" />" /> <br/><br/></td>
</tr>
<tr>
<td><h3 class="templatemo-gold">Address: </h3></td>
<td><input type="text" name="custAdd" size="50"
value="<c:out value="${customer.custAdd}" />" /><br/><br/></td>
</tr>
<tr>
<td><h3 class="templatemo-gold">Region: </h3></td>
<td><input type="text" name="custRegion" size="50"
value="<c:out value="${customer.custRegion}" />" /><br/><br/></td>
</tr>
<tr>
<td><h3 class="templatemo-gold">Handphone No: </h3></td>
<td><input type="text" name="custHandphoneNo" size="50"
value="<c:out value="${customer.custHandphoneNo}" />" />><br/><br/></td>
</tr>
<tr>
<td><h3 class="templatemo-gold">Phone No: </h3></td>
<td><input type="text" name="custPhoneNo" size="50"
value="<c:out value="${customer.custPhoneNo}" />" /><br/><br/></td>
</tr>
<tr>
<td><h3 class="templatemo-gold">Email: </h3></td>
<td><input type="text" name="custEmail" size="50"
value="<c:out value="${customer.custEmail}" />" /><br/><br/></td>
</tr>
<tr>
<td> <input type="submit" name="submit" class="btn text-uppercase templatemo-btn templatemo-info-btn">Submit </td>
</tr>
</table>
</form>
Whenever I try to insert data using jsp form, it keeps executing nullPointerException as my cust_id is not auto generated or auto increment.
After I click addbutton, servlet sent to updateUser and data cannot be inserted.
Customer customer = new Customer();
customer.setCustName(request.getParameter("custName"));
customer.setCustAdd(request.getParameter("custAdd"));
customer.setCustRegion(request.getParameter("custRegion"));
customer.setCustHandphoneNo(request.getParameter("custHandphoneNo"));
customer.setCustPhoneNo(request.getParameter("custPhoneNo"));
customer.setCustEmail(request.getParameter("custEmail"));
String cust_id = request.getParameter("cust_id");
if(cust_id == null || cust_id.isEmpty())
{
dao.addUser(customer);
}
else
{
customer.setCust_id(cust_id);
dao.updateUser(customer);
}
RequestDispatcher view = request.getRequestDispatcher(LIST_USER);
request.setAttribute("customer", dao.getAllCustomer());
view.forward(request, response);
}

how to delete data from different <div>

i am loading two <div> on single page, both holding same userID. I want to delete user data from 2nd <div>. how is it possible. Here is my controller code for delete..
HTML
<div id="tab1">
<br/>
<font color="#3b73af" size="4">Partner Detail</font>
#if($editPartnerDetail)
<form id="editPartnerDetail" class="aui" onsubmit="return validateEditForm()">
<div id="Partner_Detail">
<table style="width:80%;border:none;" cellspacing="0" cellpadding="0">
<tr>
<td>Admin Name:</td><td><input type="text" value="$editPartnerDetail.adminName" id="editAdminName" name="editAdminName" size="55" /></td>
</tr>
<tr>
<td>Email:</td><td><input type="text" value="$editPartnerDetail.email" id="editEmail" name="editEmail" size="55" /></td>
</tr>
<tr>
<td>Phone:</td><td><input type="text" value="$editPartnerDetail.phone" id="editPhone" name="editPhone" size="55" /></td>
</tr>
<input type="hidden" value="$editPartnerDetail.partnerDetailId" id="editPartnerDetailId" name="editPartnerDetailId" size="55" />
<input type="hidden" value="$editPartnerDetail.partnerSiteId" id="editPartnerSiteId" name="editPartnerSiteId" size="55" />
<tr>
<td></td><td><input type="submit" value="Update" class="button" /> Cancel</td>
</tr>
</table>
</div> <br/><br/><br/>
</form>
#else
<form id="addPartnerDetail" class="aui" onsubmit="return validateForm()">
<div id="Partner_Detail">
<table style="width:80%;border:none;" cellspacing="0" cellpadding="0">
<tr>
<td>Admin Name:</td><td><input type="text" value="" id="adminName" name="adminName" size="55" autocomplete="off"/></td>
</tr>
<tr>
<td>Email:</td><td><input type="text" value="" id="email" name="email" size="55" autocomplete="off"/></td>
</tr>
<tr>
<td>Phone:</td><td><input type="text" value="" id="phone" name="phone" size="55" autocomplete="off"/></td>
</tr>
<input type="hidden" value="$siteId" id="addPartnerSiteId" name="addPartnerSiteId" size="55" />
<tr>
<td></td><td><input type="submit" value="Add" class="button" /></td>
</tr>
</table>
</div> <br/><br/><br/>
</form>
#end
<div id="Partner_Detail">
<table style="width:80%">
<tr>
<th bgcolor="#F2F5A9">Admin Name</th>
<th bgcolor="#F2F5A9">Email</th>
<th bgcolor="#F2F5A9">Phone</th>
<th bgcolor="#F2F5A9">Action</th>
</tr>
#foreach( $partnerDetail in $partnerDetailList )
<tr>
<td>$partnerDetail.adminName</td>
<td>$partnerDetail.email</td>
<td>$partnerDetail.phone</td>
<td align="center">Edit | Delete</td>
</tr>
#end
</table>
</div>
</div>
<div id="tab2">
#if($editPartnerSite2)
<form id="editsite2" class="aui">
<div id="edit_Partner_site2">
<input type="text" value="$editPartnerSite2.partnerSite" id="editPartnerSite" name="editPartnerSite" size="55" />
<input type="hidden" value="$editPartnerSite2.partnerId" id="editPartnerSiteId" name="editPartnerSiteId" size="55" />
<input type="hidden" value="site" id="page" name="page" size="55" />
<input type="submit" value="Update" class="button">
Cancel
#if($isSiteupdated == false)
<div style="color:red;">Cannot Edit. Same partner site already exist.</div>
#end
</div>
</br>
</form>
#else
<form id="addsite" class="aui">
<div id="add_Partner_Site">
<input type="hidden" value="site" id="page" name="page" size="55" />
<input type="text" id="partnersite" name="partnersite" size="55" autocomplete="off" value="$!existingSite"/>
<br/><br/><input type="submit" value="Add" class="button" /></td>
#if($isSiteAdded == false)
<div style="color:red;">Cannot add. Same partner site already exist.</div>
#end
</div> <br/><br/><br/>
</form>
#end
<table>
<tr>
<th bgcolor="#F2F5A9">Partner Site</th>
<th bgcolor="#F2F5A9">Action</th>
</tr>
#foreach( $partnerSite in $partnerSiteList )
<tr>
<td>$partnerSite.partnerSite</td>
<td align="center">Edit | Delete</td>
</tr>
#end
</table>
<div>
Controller
else if (pageName != null && pageName.equals("partnerDetail")) {
Map<String, Object> context = new HashMap<String, Object>();
if (request.getParameter("nameId") != null && request.getParameter("nameId") != "") {
siteId = Integer.parseInt(request.getParameter("nameId"));
String mode = request.getParameter("mode");
if (mode != null && mode.equals("delete")) {
String pdId = request.getParameter("pdId");
if (pdId != null && pdId != "") {
partnerDetailService.deletePartneDetail(Integer.parseInt(pdId));
}
}
if (mode != null && mode.equals("edit")) {
String pdId = request.getParameter("pdId");
int partnerDetailID = Integer.parseInt(pdId);
if (pdId != null && pdId != "") {
PartnerDetail editPartnerDetail = partnerDetailService.getPartneDetailById(partnerDetailID);
context.put("editPartnerDetail", editPartnerDetail);
}
}
}
if (request.getParameter("nameId") != null && request.getParameter("nameId") != "") {
siteId = Integer.parseInt(request.getParameter("nameId"));
String mode = request.getParameter("mode");
if (mode != null && mode.equals("deleteTab2")) {
String sId = request.getParameter("sId");
if (sId != null && sId != "") {
partnerSiteService.deletePartnerSite(Integer.parseInt(sId));
}
}
}
//===========================
context.put("siteId", siteId);
List<PartnerDetail> partnerDetailList = partnerDetailService.getAllDetailByPartnerSiteID(siteId);
context.put("partnerDetailList", partnerDetailList);
String partnerId = request.getParameter("nameId");
int pID = Integer.parseInt(partnerId);
List<PartnerSite> partnerSiteList = partnerDetailService.getAllPartnerSiteById(pID);
context.put("partnerSiteList", partnerSiteList);
response.setContentType("text/html;charset=utf-8");
renderer.render("templates/admin/partnerDetail.vm", context,response.getWriter());
help me out..
You should never use the same ID on two elements!
It's better to use class instead. The id-attribute is reserved for unique idintifiers

Categories

Resources