unable to bind ModelMap through ajax call in Spring MVC - java

MY JSP PAGE:
<form action="manageparentexamforchildren.htm" class="form-horizontal form-bordered" >
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-1"><spring:message code="label.parent.children"/></label>
<div class="col-md-3">
<select name="parent.children" class="form-control" id="children" required="true" >
<option value="">-<spring:message code="label.select"/>-</option>
<c:forEach items="${studentsOfThisParent}" var="student">
<option value="${student.id}">${student.firstName} ${student.lastName}</option>
</c:forEach>
</select>
</div>
</div>
</div>
<div class="form-actions fluid">
<div class="row">
<div class="col-md-12">
<div class="col-md-offset-3 col-md-9">
<button type="submit" class="btn blue"><i class="icon-ok"></i><spring:message code='button.search'/></button>
<button type="button" onclick="javascript:history.go(-1);" class="btn red default"><spring:message code='button.cancel'/></button>
</div>
</div>
</div>
</div>
</form>
<c:forEach items="${modelList}" var="examination">
<tr>
<td><b><spring:message code="label.examination.schoolexam"/></b>:<c:out value="${examination.schoolExam.name}" /></td>
</tr>
<table border="1" width="1000" height="200" class="table table-bordered table-hover">
<thead> <tr><th class="active"><spring:message code="label.examination.subjects"/></th><th class="active"><spring:message code="label.exam.Date"/></th><th class="active"><spring:message code="label.exam.maxmarks"/></th></tr></thead>
<tbody>
<c:forEach items="${examination.examinationSubjects}" var="examinationSubject" varStatus="status">
<tr>
<td class="success"><c:out value="${examinationSubject.subjects.name}" /></td>
<td class="success" ><c:out value="${examinationSubject.date}" /></td>
<td class="success"><c:out value="${examinationSubject.maxMarks}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</c:forEach>
MY CONTROLLER:
#RequestMapping(value="/manageparentexam.htm", method=RequestMethod.GET)
public String manageparentexam(ModelMap modelMap,HttpServletRequest request )
{
Parent parent = parentService.getParentById(getLoggedInUser().getId());
List <Student> studentsOfThisParent=parentService.getStudentsOfThisParent(getLoggedInUser().getId());
Student student=null;
student=parent.getStudentAdmission().get(0).getStudent();
modelMap.addAttribute("modelList",student.getStudentAdmission().getClasses().getExamination());
setupCreate(modelMap, request);
return "tileDefinition.manageparentexam-"+getNameSpace();
}
#RequestMapping(value="/manageparentexamforchildren.htm", method=RequestMethod.GET)
public void manageparentexamforchildren(ModelMap modelMap,HttpServletRequest request )
{
Long studentId=Long.valueOf(request.getParameter("parent.children"));
modelMap.addAttribute("modelList",studentService.getById(studentId).getStudentAdmission().getClasses().getExamination());
setupCreate(modelMap, request);
}
here my requirement is,when ever,i select a value in select box,then the table should get updated through ajax,here i am unable to bind the model list through ajax call . . .

What I would do is separate the table in another jsp. yourTable.jsp like this
<table border="1" width="1000" height="200" class="table table-bordered table-hover">
<thead> <tr><th class="active"><spring:message code="label.examination.subjects"/></th><th class="active"><spring:message code="label.exam.Date"/></th><th class="active"><spring:message code="label.exam.maxmarks"/></th></tr></thead>
<tbody>
<c:forEach items="${examination.examinationSubjects}" var="examinationSubject" varStatus="status">
<tr>
<td class="success"><c:out value="${examinationSubject.subjects.name}" /></td>
<td class="success" ><c:out value="${examinationSubject.date}" /></td>
<td class="success"><c:out value="${examinationSubject.maxMarks}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
Then you include this jsp in your main mapge inside a div
<div id="yourTable">
<c:jsp include="yourTable.jsp/>
</div>
Then in your select you have to add a listener and when something has change you need to make a JQuery load lo reload the table rendering the table from the controller again with all the changes that you want
$('#yourTable').load("url of your controller where you will render yourTable.jsp");
And in the controller you will render yourTable.jsp and you will add in the ModelAndView object the examinationSubject

Related

Retrieve input(s) from DataTable

Need some advice how should I retrieve a list of exhibits.
In my html template below, I only put one record of exhibit. If i were to put additional rows/records of exhibit, how do i go about mapping them to the controller.
HTML Template
<h3>Exhibit Details</h3>
<div class="table-responsive">
<table id="exhibitTable"
class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Exhibit Type</th>
<th>Description</th>
<th>Marking</th>
<th>Remarks</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group col-md-3">
<div class="cols-sm-10">
<select class="form-control selectpicker cols-md-3"
th:value="${exhibit.exhibitType}" id="exhibitType"
name="exhibitType" roleId="exhibitType">
<option value="">Select Type</option>
<option>Desktop</option>
<option>Laptop</option>
<option>Mobile Device</option>
<option>Portable Storage</option>
<option>Server</option>
<option>Video System</option>
<option>Save As</option>
<option>Others</option>
</select>
</div>
</div>
</td>
<td>
<div class="form-group col-md-3">
<input type="text" name="exhibitDescription"
id="exhibitDescription"
th:value="${exhibit.exhibitDescription}" />
</div>
</td>
<td>
<div class="form-group col-md-3">
<input type="text" name="exhibitMarking" id="exhibitMarking"
th:value="${exhibit.exhibitMarking}" />
</div>
</td>
<td><div class="form-group col-md-3">
<input type="text" name="exhibitRemarks" id="exhibitRemarks"
th:value="${exhibit.exhibitRemarks}" />
</div></td>
</tr>
</tbody>
</table>
</div>
Controller
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerIncidentPost(#ModelAttribute("incident") Incident incident,
#ModelAttribute("exhibit") Exhibit exhibit, Principal principal) throws Exception {
long year = Calendar.getInstance().get(Calendar.YEAR);
incident.setIncidentYear(year + "");
Long refNo = incidentService.findMaxRefNoCurrentYear(year + "");
if (refNo == null)
refNo = (long) 1;
else
refNo += 1;
incident.setIncidentRefNo(refNo);
incident.setIncidentStatus(Incident.INCIDENT_REGISTERED);
incident.setIncidentOpeningTimestamp(new Date());
User user = userService.findByUsername(principal.getName());
incident.setIncidentCreatedBy(user);
incidentService.createIncident(incident);
exhibitService.createExhibit(exhibit);
return "redirect:/incident";
}
I've attempted to add the following to my template
<tr data-th-each="exhibit:${exhibitList}">
and the following to my controller
#ModelAttribute("exhibitList") ArrayList<Exhibit> exhibitList
but did not work.
Thanks in advance.
I can only assume this is vb.net since you didn't specify. You need to pass in the complete dataset to the page. Each item in the dataset will be one pre-loaded instance of the model. Then you can do a for each loop on the page itself and generate the html dynamically. Hope this helps.

Removing just one Row in table - SpringBoot & Java & Thymeleaf

New to Spring-boot and Java and Thymeleaf...Trying to make it so the trash button deletes only one row in this table. Right now it if any trash button is clicked, all table rows are deleted.
I ran the debugger and my controller is picking up the rowId for whichever button is clicked, so not sure why it's deleting all rows and not just the one. Any ideas?
//code that loads form and table (table is made up of Ams360Policies)
#GetMapping("/directBind")
public String getDirectBind(Model model){
List<String> businessAgencies = new ArrayList<String>();
businessAgencies.add("Personal");
businessAgencies.add("Commercial");
businessAgencies.add("Life");
businessAgencies.add("Benefits");
businessAgencies.add("Health");
businessAgencies.add("Non P and C");
model.addAttribute("businessAgencies", businessAgencies);
DirectBind directBind = new DirectBind();
List<Ams360Policy> ams360Policies = new ArrayList();
Ams360Policy ams360Policy = new Ams360Policy();
ams360Policies.add(ams360Policy);
model.addAttribute("ams360Policies", ams360Policy);
List<String> billTypeList = new ArrayList<String>();
billTypeList.add("Direct Bill");
billTypeList.add("Agency Bill");
model.addAttribute("billTypeList", billTypeList);
ams360Policy.setBillTypeOptions(billTypeList);
List<String> businessAgencyList = new ArrayList<String>();
directBind.setBusinessAgencyList(businessAgencyList);
model.addAttribute("directBind", directBind);
return "directBind";
}
//code to add a Row to table
#RequestMapping(value="/directBind", params="addPolicy")
public String addPolicy(final DirectBind directBind, Model model){
List<Ams360Policy> ams360Policies = directBind.getAms360Policies();
Ams360Policy ams360Policy = new Ams360Policy();
ams360Policies.add(ams360Policy);
model.addAttribute("ams360Policies", ams360Policies);
List<String> billTypeList = new ArrayList<String>();
billTypeList.add("Direct Bill");
billTypeList.add("Agency Bill");
model.addAttribute("billTypeList", billTypeList);
ams360Policy.setBillTypeOptions(billTypeList);
List<String> businessAgencyList = new ArrayList<String>();
directBind.setBusinessAgencyList(businessAgencyList);
return "directBind";
}
//code to Remove row of table
#RequestMapping(value = "/directBind", params="removeRow")
public String removeRow(final DirectBind directBind, final HttpServletRequest req, Model model){
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
List<Ams360Policy> ams360Policies = directBind.getAms360Policies();
model.addAttribute("ams360Policies", ams360Policies);
directBind.setAms360Policies(ams360Policies);
Ams360Policy ams360Policy = new Ams360Policy();
List<String> billTypeList = new ArrayList<String>();
billTypeList.add("Direct Bill");
billTypeList.add("Agency Bill");
model.addAttribute("billTypeList", billTypeList);
ams360Policy.setBillTypeOptions(billTypeList);
List<String> businessAgencyList = new ArrayList<String>();
directBind.setBusinessAgencyList(businessAgencyList);
directBind.getAms360Policies().remove(1);
model.addAttribute("directBind", directBind);
return "directBind";
}
//html code for table
<div>
<h4 style="display: inline;">AMS360 Policy Setup</h4>
<input type="submit" formnovalidate="formnovalidate" name="addPolicy" class="btn btn-default" style="margin-left: 1rem; margin-bottom: 1rem;" value="+"></input>
</div>
<div class="col-sm-12">
<hr/>
<table class="table table-striped AMSTable" data-classes="table-no-bordered" data-striped="true" data-show-columns="true" data-pagination="true">
<thead>
<tr>
<th>Policy Number</th>
<th>Policy Term Start Date</th>
<th>Policy Term End Date</th>
<th>Line of Coverage</th>
<th>Parent Company</th>
<th>Writing Company</th>
<th>Bill Type</th>
<th>Quote Premium</th>
<th>Commission</th>
</tr>
</thead>
<tbody>
<tr id="newPolicyRow" th:each="ams360Policy, stat : ${ams360Policies}">
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].policyNumber}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].policyTermDateStart}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].policyTermDateEnd}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].lineOfCoverage}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].parentCompany}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].writingCompany}"/></td>
<td id="billTypeCell">
<div th:each="billType : ${billTypeList}">
<input type="checkbox" th:field="*{ams360Policies[__${stat.index}__].billTypeOptions}" th:value="${billType}"/>
<label th:text="${billType}" id="billTypeLabel"></label>
</div>
</td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].quotePremium}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].commission}"/></td>
<td class="text-right"> <button type="submit" name="removeRow" th:value="${stat.index}" class="btn btn-danger" ><span class="fa fa-trash"></span></button></td>
</tr>
</tbody>
</table>
</div>
When I debug I get the following...
//html code for table
<div>
<h4 style="display: inline;">AMS360 Policy Setup</h4>
<input type="submit" formnovalidate="formnovalidate" name="addPolicy" class="btn btn-default" style="margin-left: 1rem; margin-bottom: 1rem;" value="+"></input>
</div>
<div class="col-sm-12">
<hr/>
<table class="table table-striped AMSTable" data-classes="table-no-bordered" data-striped="true" data-show-columns="true" data-pagination="true">
<thead>
<tr>
<th>Policy Number</th>
<th>Policy Term Start Date</th>
<th>Policy Term End Date</th>
<th>Line of Coverage</th>
<th>Parent Company</th>
<th>Writing Company</th>
<th>Bill Type</th>
<th>Quote Premium</th>
<th>Commission</th>
</tr>
</thead>
<tbody>
<tr id="newPolicyRow" th:each="ams360Policy, stat : ${ams360Policies}">
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].policyNumber}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].policyTermDateStart}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].policyTermDateEnd}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].lineOfCoverage}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].parentCompany}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].writingCompany}"/></td>
<td id="billTypeCell">
<div th:each="billType : ${billTypeList}">
<input type="checkbox" th:field="*{ams360Policies[__${stat.index}__].billTypeOptions}" th:value="${billType}"/>
<label th:text="${billType}" id="billTypeLabel"></label>
</div>
</td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].quotePremium}"/></td>
<td> <input type="text" class="form-control" th:field="*{ams360Policies[__${stat.index}__].commission}"/></td>
<td class="text-right"> <button type="submit" name="removeRow" th:value="${stat.index}" class="btn btn-danger" ><span class="fa fa-trash"></span></button></td>
</tr>
</tbody>
</table>
</div>

input map value into another map name in jsp page

I want to generate tables in jsp page using data I got from Map in java. I use which use map value for define 'item'. But, The name of map value that I want to put on 'item' needs value from another map.
To be clear, here my jsp code;
<c:forEach var="wilayahProvinsi" items="${model.kodeKabupatenList}">
<div data-role="page" id="kode${wilayahProvinsi.ID2012}">
<div data-role="header" data-position="inline" data-fullscreen="true">
Back
<h1>${wilayahProvinsi.NAMA}</h1>
</div>
<div class="container">
<table id="example1" class="display nowrap" >
<thead>
<tr>
<th>Kode Komoditas</th>
<th>Jenis Barang</th>
<th>Nilai Konsumsi</th>
<th>Nilai Imputasi</th>
<th>Nilai Konsumsi Akhir</th>
<th>Persentase trhdp Total</th>
<th>Persentase trhdp Kelompok</th>
<th>Persentase trhdp Subkelompok</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<tbody>
<!-- this is the problem -->
<c:forEach var="pekerjaanku" items="${model.pekerjaankuList$wilayahProvinsi.ID2012}">
<tr>
<td>${pekerjaanku.kode_komoditas}</td>
<td id="jenis_barang">${pekerjaanku.jenis_barang}</td>
<td style="text-align: right">${pekerjaanku.nilai_konsumsi}</td>
<td style="text-align: right">${pekerjaanku.nilai_imputasi}</td>
<td style="text-align: right">${pekerjaanku.nilai_konsumsi_akhir}</td>
<td style="text-align: right">${pekerjaanku.persentase_total}</td>
<td style="text-align: right">${pekerjaanku.persentase_kelompok}</td>
<td style="text-align: right">${pekerjaanku.persentase_subkelompok}</td>
<td><a href="kotaEdit?id=${pekerjaanku.kode_komoditas}" class="ui-btn ui-mini ui-corner-all ui-icon-edit
ui-btn-icon-left">Edit</a></td>
<td><a href="kotaDelete?id=${pekerjaanku.kode_komoditas}" class="ui-btn ui-mini ui-corner-all ui-icon-delete
ui-btn-icon-left" onclick="return confirm('Yakin ingin menghapus komoditas ${pekerjaanku.jenis_barang}?')">
Delete</a></td>
</tr>
</c:forEach>
</tbody>
</table>
<table>
<tr>
<td colspan="8">Tambah Komoditas Baru</td>
<td colspan="2">Download CSV</td>
</tr>
</table>
</div>
</div>
</c:forEach>
This is my Java code;
#RequestMapping("/jelajahPekerjaanKota")
public ModelAndView getPekerjaanKotaList() {
List<KodeKabupaten> kodeKabupatenList = usersService.getSpecifiedKodeKabupatenList();
Map<String, Object> model = new HashMap<String, Object>();
model.put("kodeKabupatenList", kodeKabupatenList);
for(KodeKabupaten kodeKabupaten : kodeKabupatenList){
model.put("pekerjaankuList" + kodeKabupaten.getID2012(), pekerjaankuService.getPekerjaankuList(kodeKabupaten.getID2012()));
}
return new ModelAndView("/provinsi/jelajahPekerjaanKota", "model", model);
}
To be clear, the objects in Map model is;
model.kodeKabupatenList which has attributes: NAMA, ID2012, PROV, and KAB
model.pekerjaankuList3171 which has attributes: kode_komoditas, jenis_barang, ...
model.pekerjaankuList3172 , the attributes are same with above
model.pekerjaankuList3173 , same with above
my problem is how to get all model.pekerjaankuList** in jsp with looping? I can not run this code in jsp;
<c:forEach var="pekerjaanku" items="${model.pekerjaankuList$wilayahProvinsi.ID2012}">

JSP getParameterValues Returns Null

Im using JSTL tags and EL to get the values out of my database. I added a checkbox to the data table on the U.I for the functionality of deleting a record. The problem is the String[] in the servlet always comes out as null and I have no idea why. I even tried dummy data in the 'value' attribute on the checkbox element and the array was still null.
HTML
<div id="authorTable" >
<table style="text-align: center;">
<thead>
<th>Book ID</th>
<th>Title</th>
<th>Date Published</th>
<th>Author ID</th>
<th>Author First Name</th>
<th>Author Last Name</th>
<th>Delete</th>
</thead>
<tbody>
<c:forEach var="record" items="${bookRecordsResult}">
<tr>
<td>${record.bookID}</td>
<td>${record.title}</td>
<td>${record.datePublished}</td>
<td>${record.author.firstName}</td>
<td>${record.author.lastName}</td>
<td>${record.author.id}</td>
This Line ------> <td> <input type="checkbox" name="boxes" id="boxes" class="boxes" value="${record.bookID}" /> </td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
<div id="deleteContainer">
<form id="deleteForm" method="POST" action="bookAuthorControls">
<button type="submit" id="deleteButton" name="deleteButton" >Delete</button>
</form>
</div>
Java Servlet
String delete = request.getParameter("deleteButton");
if (delete != null) {
And This Line ----> String[] checkValues = request.getParameterValues("boxes");
try {
service.deleteRecords(Arrays.asList(checkValues));
bookRecords = service.getAllBookRecords();
request.setAttribute("bookRecordsResult", bookRecords);
} catch (SQLException | ClassNotFoundException | ParseException ex) {
request.setAttribute("error", ex.getLocalizedMessage());
}
}
Once again the String[] comes back null no matter what I try, any ideas?
The checkbox input elements are not contained in the form element which is submitted.
You need to wrap the form around all input elements:
<form id="deleteForm" method="POST" action="bookAuthorControls">
<div id="authorTable">
...
<td><input type="checkbox" name="boxes" id="boxes" class="boxes" value="${record.bookID}" /> </td>
...
</div>
<div id="deleteContainer">
<button type="submit" id="deleteButton" name="deleteButton" >Delete</button>
</div>
</form>

How to validate jsp page using HTMl5

I have two submit button in one form,if I click on first submit button(i.e cashPaymentDiv save butoon) both submit buttons fields are validating. I want to validate only one div while submitting form.
<form name="customerForm" action="saveTransactionBill.do">
<div id="paymentModeDiv">
<table>
<tr>
<td><label
style="margin: 0; width: 100px; display: block; padding: 5px 0; color: #737373; font: bold 12px Arial, Helvetica, sans-serif; float: left;">Payment
Mode:</label></td>
<td><select onchange="showPaymentDivs();"
name="paymentMode">
<option value="">--Select--</option>
<option value="cash">Cash</option>
<option value="cheque">Cheque</option>
</select></td>
</tr>
</table>
</div>
<div id="cashPaymentDiv" class="required">
<table>
<tr>
<td><label>Amount Paid:</label></td>
<td><input name="amountPaid" id="cashPaymentForBillWise" onchange="calculateBalAmount();"
required x-moz-errormessage="Enter Username" pattern="[0-9]{0,20}"
title="Please enter only numrics." ></td>
</tr>
<tr>
<td><input type="submit" value="cash Save"></td>
</tr>
</table>
</div>
<div id="chequePaymentDiv" class="required">
<table>
<tr>
<td><label>Amount Paid:</label></td>
<td><input name="amountPaid" id="cashPaymentForBillWise" onchange="calculateBalAmount();"
required x-moz-errormessage="Enter Username" pattern="[0-9]{0,20}"
title="Please enter only numrics." ></td>
</tr>
<tr>
<td><input type="submit" value="cheque Save"></td>
</tr>
</table>
</div>
</form>

Categories

Resources