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

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();
}
}

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

how to create Multiple EmployeeBean objects

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>

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 retrieve "Grouped" items from HTML form using Servlet?

I am having an issue with retriving "grouped" data from HTML form to servlet. I will describve the scenario below.
In companies, they record the salary of the employees once a month.When they record it, they do not do it by visiting each an every employees personal "profile" (or whatever according to the system). Instead what they do is apply the salaries of all of them in one page.
To do the above thing they prefer excel like tabular sheets.
Now, I have a html form, where the form content is a table. One row is dedicated to a one employee.
Below is my form.
<%--
Document : index2
Created on : Mar 5, 2015, 10:04:45 AM
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form method="post" action="EmployeeSampleServlet">
<table border="1" style="width:100%">
<thead>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</thead>
<tbody name="tableBody" value="1">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="2">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="3">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="4">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
<tbody name="tableBody" value="5">
<tr>
<td><input type="text" name="nameTxt" style="width:100%"/></td>
<td><input type="text" name="positionTxt" style="width:100%"/></td>
<td><input type="text" name="salaryTxt" style="width:100%"/></td>
</tr>
</tbody>
</table>
<br/>
<input type="submit" value="Submit">
</form>
</body>
</html>
As you can see, I have wrapped every row with a <tbody>. The value attribute of the <tbody> will contain the employee id.
Once the form is submitted, the below servlet will capture it.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class EmployeeSampleServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String[]empId = request.getParameterValues("tableBody");
for(int i=0;i<empId.length;i++)
{
out.println(empId[i]);
}
}
// <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 {
processRequest(request, response);
}
/**
* 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 {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
What I was trying is get the value attribute of <tbody> (so I can identify the id of the employee) and get the data inside that <tbody>. However this didn't work, because I ended up with NullpointerException because it failed to read the <tbody> value.
So, how can I pass the data from table to servlet where it can clearly understand that one row is representing data belong to a one employee? If this is not the way to do it, I am also open for other methods.
That is obviously not going to work as only the input field values are submitted to the server.
You will need to discriminate the names of each input field in some way as currently you cannot match these to individual employees:
I assume you generate the table from some kind of list of employees so you could do this something like below:
<tr>
<td><input type="text" name="nameTxt_${employee.employeeId}" style="width:100%"/></td>
<td><input type="text" name="positionTxt_${employee.employeeId}" style="width:100%"/></td>
<td><input type="text" name="salaryTxt_${employee.employeeId}" style="width:100%"/></td>
</tr>
Now instead of receiving a bunch of random parameters 'nameTxt' etc., you reeive 'nameText_21', 'salaryText_21' etc. and have a means to identify the input with an employee. How you do this will depend on whether you have the list of Employees available in the Servlet on form submission.
e.g.
//employees = load the same list originally loaded for edit
for(Employee e : employees){
e.setSalary(Double.parseDouble(request.getParameter("salaryTxt_" + e.getid())));
}
Otherwise you will need to iterate the parameters for some field and proceed that way.
for(String s: request.getParameterNames()){
if(s.startsWith("nameTxt")){
//extract suffix
//load the employee with corresponding ID
//get the other params with same id
}
}
Look the below HTML, this will get all the table row-wise value and convert that as a json array. Now you can pass this array to servlet via ajax.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sample</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<table border="1" id="mytable" border="1" >
<thead>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</thead>
<tbody>
<tr>
<td><input type="text" name="nameTxt" value="12" /></td>
<td><input type="text" name="positionTxt" value="13" /></td>
<td><input type="text" name="salaryTxt" value="14" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="21" /></td>
<td><input type="text" name="positionTxt" value="22" /></td>
<td><input type="text" name="salaryTxt" value="23" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="31" /></td>
<td><input type="text" name="positionTxt" value="32" /></td>
<td><input type="text" name="salaryTxt" value="33" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="41" /></td>
<td><input type="text" name="positionTxt" value="42" /></td>
<td><input type="text" name="salaryTxt" value="43" /></td>
</tr>
<tr>
<td><input type="text" name="nameTxt" value="51" /></td>
<td><input type="text" name="positionTxt" value="52" /></td>
<td><input type="text" name="salaryTxt" value="53" /></td>
</tr>
</tbody>
</table>
<br/>
<input type="button" value="Submit" onclick="convertValuesToJson();">
</body>
</html>
And you script looks like,
<script>
function convertValuesToJson(){
var myStringArray = [];
// Iterate each row
$('#mytable tbody tr').each(function() {
var myObject = new Object();
myObject.name = $(this).find("input[name='nameTxt']").val();
myObject.position = $(this).find("input[name='positionTxt']").val();
myObject.salary = $(this).find("input[name='salaryTxt']").val();
myStringArray.push(JSON.stringify(myObject));
});
// function for ajax goes here...
jQuery.ajax({
url: "ServletURL",
type : 'POST',
dataType: "json",
data : {"myData" : myStringArray},
error : function(jqXHR, textStatus, errorThrown) {
alert("error occurred");
}
});
}
</script>
See my updated Demo

Categories

Resources