Spring Boot Update checkboxes - java

I have a problem with this method, I need to update the value of the "procesado" variable (the variable it starts being from false because its boolean type), I can select one or more checkboxes and when I click the button(Procesar), the value of the variable should change to true.
the problem is when i select the checkboxes that i can't update and display the results
This is my controller:
#RequestMapping(value = "/consulta/{id}", method = RequestMethod.PUT)
public String update(#RequestBody Usuario user, #PathVariable(value="id") List<Usuario> id) {
if(id != null) {
for(Usuario idInt: id) {
Usuario idValor= idInt;
user.setProcesado(true);
iusuarioServices.save(user);
}
}
return "consulta";
}
This is my html
<form action="#{/consulta/{id}}">
<table>
<thead>
<tr>
<th>ID</th>
<th>Nombre</th>
<th>Apellido</th>
<th>Procesado</th>
<th>Accion</th>
</tr>
</thead>
<tbody>
<tr th:each="usuarios: ${usuarios}">
<td th:text="${usuarios.id}"></td>
<td th:text="${usuarios.nombre}"></td>
<td th:text="${usuarios.apellido}"></td>
<td th:text="${usuarios.procesado}"></td>
<td><input type="checkbox" th:name="procesado" th:value="${usuarios.id}"></td>
</tr>
</tbody>
<tr>
<td><input type="submit" value="Procesar" /></td>
</tr>
</table>
</form>
enter image description here

Related

Receive parameters from Thymleaf page

I have tried to send a parameter from this thymleaf page
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form style='float:left; padding:5px; height:0px' th:object="${p}" th:method="post" th:action="#{/dashboard/makeAndSendInvoice/{email}(email=${p.email})}">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
and then I tried to receive the parameter (email) using this code
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#PathVariable("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}
The problem is when the value of p.email is something like myemail#gmail.com
what I receive in the method makeAndSendInvoice is only myemail#gmail
and it does not send me the .com part
How can I fix it?
(email=${p.email}) means , you are passing a query parameter.
So, how can you be able to catch the query param value using path variable?
We can use #RequestParam to catch the queryparam value in Spring
Try the below java code :
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#RequestParam("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}
The period in ".com" will need to be encoded to be used in the url to prevent it being parsed as the suffix
Your HTML:
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form method="post" th:action="#{/dashboard/makeAndSendInvoice/__${p.email}__} ">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
Your controller
#RequestMapping(value = "/dashboard")
#Controller
public class testController {
...
#RequestMapping(value = "/makeAndSendInvoice/{email}", method = RequestMethod.POST)
public ModelAndView makeAndSendInvoice(#PathVariable String email, ModelAndView mav) {
return mav; // <- Break point, debug !!
}
}

populating the uploaded file name and size in a html table, appending new values when user choose files at second time

Question is i have table in which i want to populate the values of file name and file size after user click the choose file button and select any number of files, Now the issue is if the user click choose files button second time i want to append the new values in the table and add the new file in the array so that it can uploaded.. my code is,
html form code:
<form id="simpleuploadform" method="post" action="upload" enctype="multipart/form-data">
<table class="span10" border="0">
<tr>
<td colspan="3">
<legend>Simple Upload</legend>
</td>
</tr>
<tr>
<td>
<input type="file" name="files[]" multiple="multiple" onchange="getFileSizeandName(this);"/>
<div id="successdiv" hidden="true" class="label label-success">Image uploaded successfully</div>
<div id="errordiv" hidden="true" class="label label-error">Image not successfully uploaded</div>
<div id="streamdiv" hidden="true" class="label label-warning">Issue while uploading try again</div>
</td>
<td id="renameFile" align="right"></td>
<td id="removeFile" align="right"></td>
</tr>
<tr>
<td colspan="3">
<div id="uploaddiv">
<table id="uploadTable" class="table table-striped table-bordered" width="200" height="200" scrolling="yes">
<thead>
<tr>
<th>Title</th>
<th>Size</th>
</tr>
</thead>
<tbody id="tbodyid">
<tr id="tr0">
<td id="filetd0" height="10px" width="50px"></td>
<td id="filesizetd0" height="10px" width="5px"></td>
</tr>
<tr id="tr1">
<td id="filetd1" height="10px" width="50px"></td>
<td id="filesizetd1" height="10px" width="5px"></td>
</tr>
<tr id="tr2">
<td id="filetd2" height="10px" width="50px"></td>
<td id="filesizetd2" height="10px" width="5px"></td>
</tr>
<tr id="tr3">
<td id="filetd3" height="10px" width="50px"></td>
<td id="filesizetd3" height="10px" width="5px"></td>
</tr>
<tr id="tr4">
<td id="filetd4" height="10px" width="50px"></td>
<td id="filesizetd4" height="10px" width="5px"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td id="filecount" height="10px" width="50px"></td>
<td id="totalsize" height="10px" width="5px"></td>
</tr>
</tfoot>
</table>
</div>
</td>
</tr>
<tr>
<td colspan="3">
<input type="submit" class="btn btn-primary" onClick="CloseAndRefresh();" value="Start Upload" id="startButton" disabled>
<input type="reset" class="btn btn-primary" onClick="Clear();" value="Clear" id="clearButton" disabled>
<input type="button" class="btn" onClick="window.close();" value="Close">
</td>
</tr>
</table>
javascript code:
<script type="text/javascript">
var totalsizeOfUploadFiles = 0;
function getFileSizeandName(input)
{
var select = $('#uploadTable tbody');
$('#renameFile').empty();$('#removeFile').empty();
if(input.files.length > 0)
{
$('#renameFile').append($('<a id="renameRec">Rename Selected</a>'));
$('#removeFile').append($('<a id="removeRec">Remove Selected</a>'));
$('#startButton').removeAttr("disabled", "disabled");
$('#clearButton').removeAttr("disabled", "disabled");
}
//if(input.files.length <= 5)
//{
for(var i =0; i<input.files.length; i++)
{
var filesizeInBytes = input.files[i].size;
var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2);
var filename = input.files[i].name;
//alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");
if(i<=4)
{
$('#filetd'+i+'').text(filename);
$('#filesizetd'+i+'').text(filesizeInMB);
}
else if(i>4)
select.append($('<tr id=tr'+i+'><td id=filetd'+i+'>'+filename+'</td><td id=filesizetd'+i+'>'+filesizeInMB+'</td></tr>'));
totalsizeOfUploadFiles += parseFloat(filesizeInMB);
$('#totalsize').text(totalsizeOfUploadFiles.toFixed(2)+" MB");
if(i==0)
$('#filecount').text("1file");
else
{
var no = parseInt(i) + 1;
$('#filecount').text(no+"files");
}
}
//}
}
function CloseAndRefresh()
{
var daa = '<%=status%>';
if(daa == "true")
$('#successdiv').show();
else if(daa == "false")
$('#errordiv').show();
else
$('#streamdiv').show();
opener.location.reload(true);
self.close();
}
function Clear()
{
$('#uploadTable tbody tr td').each(function(){
$(this).text("");
});
$('#uploadTable tfoot tr td').each(function(){
$(this).text("");
});
}
i am trying to do as like this http://www.shutterfly.com/ image upload.
any help will be appreciated, thank you friends...
You are navigating away using javascript, function CloseAndRefresh on clicking submit button.
What actually happens is that the uploading request is being submitted while the CloseAndRefresh function is being executed at almost the same time using different thread. If the upload request is not fast enough, the web page will get refresh first and your upload request get terminated immediately. There is no easy way to prevent this using your existing code.
You should use advanced method of uploading like jQuery uploading plugin to send the request. The plugin provide an binder to execute function on successful/failed submittsion.
Thank you gigadot, i solve the issue as like below,
The html form have the same code as i posted earlier, in the previous js code i have the CloseAndRefresh() method i remove it now from js as well as from the submit button onclick event.
When the form action called the controller, in which i have the code
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String UploadReceipts(#RequestParam("files[]") List<MultipartFile> file, Model model) throws IOException {
boolean status = false;
try
{
for(int i=0; i< file.size(); i++)
{
if(!file.get(i).isEmpty())
{
CommonsMultipartFile cm = (CommonsMultipartFile) file.get(i);
status = simpleUploadService.uploadFileandSave(cm);
model.addAttribute("status", status);
}
}
}
catch (IOException e) {
status = false;
model.addAttribute("status", status);
}
return "pages/simpleUploadStatus";
}
Now i redirect it to another page in which i throws the appropriate messages for the user.
that's all...

#RequestParam is null (Spring MVC)

I'm trying to add an edit function to my web app but I'm having some problems using #RequestParam. The parameter it is getting is null which it shouldn't be. I'm hoping someone can point out where I have made a mistake.
Here are the methods from the controller :
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEdit(#RequestParam("customerId") Integer customerId, Model model) {
Customer existingCustomer = customerService.retrieveCustomer(customerId);
model.addAttribute("customerAttribute", existingCustomer);
return "edit-customer";
}
#RequestMapping(value = "/edit", method = RequestMethod.POST)
public String postEdit(#RequestParam("customerId") Integer customerId,
#ModelAttribute("customerAttribute") #Valid Customer customer, BindingResult result) {
if (result.hasErrors()) {
return "edit-customer";
}
customer.setCustomerId(customerId);
customerService.editCustomer(customer);
return "redirect:/test/customer/list";
and the two jsp pages
edit-customer.jsp :
<body>
<h1>Edit Existing Customer</h1>
<c:url var="saveUrl" value="/test/customer/edit?customerId=${customerAttribute.customerId}" />
<form:form modelAttribute="customerAttribute" method="POST" action="${saveUrl}">
<table>
<tr>
<td><form:label path="customerId">Customer Id:</form:label></td>
<td><form:input path="customerId" disabled="true"/></td>
</tr>
<tr>
<td><form:label path="customerCountry">Customer Country</form:label></td>
<td><form:input path="customerCountry"/></td>
</tr>
<tr>
<td><form:label path="customerName">Customer Name:</form:label></td>
<td><form:input path="customerName"/></td>
</tr>
</table>
<input type="submit" value="Save" />
</form:form>
</body>
view-all-customers.jsp :
<body>
Home
<h1>Customers</h1>
<c:url var="addUrl" value="/test/customer/add" />
<c:url var="editUrl" value="/test/customer/edit?customerId=${customer.customerId}"/>
<c:if test="${!empty customers}">
Add
</c:if>
<table style="border: 1px solid; width: 500px; text-align:center">
<thead style="background:#ccc">
<tr>
<th>Customer Id</th>
<th>Customer Country</th>
<th>Customer Name</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<c:forEach items="${customers}" var="customer">
<tr>
<td><c:out value="${customer.customerId}" /></td>
<td><c:out value="${customer.customerCountry}" /></td>
<td><c:out value="${customer.customerName}" /></td>
<td>Edit</td>
</tr>
</c:forEach>
</tbody>
</table>
<c:if test="${empty customers}">
There are currently no customers in the list. Add a customers.
</c:if>
</body>
Can anyone see why Integer customerId in the GET method is null?
Thank you,
D
You're using ${customer.customerId} before it's initialized:
<!-- you use it here -->
<c:url var="editUrl" value="/test/customer/edit?customerId=${customer.customerId}"/>
<c:if test="${!empty customers}">
....
<tbody>
<!-- and initialize it here -->
<c:forEach items="${customers}" var="customer">
<tr>
<td><c:out value="${customer.customerId}" /></td>
<td><c:out value="${customer.customerCountry}" /></td>
<td><c:out value="${customer.customerName}" /></td>
<td>Edit</td>
</tr>
</c:forEach>
</tbody>
</table>
Simply set editUrl inside the loop:
<c:if test="${!empty customers}">
....
<tbody>
<c:forEach items="${customers}" var="customer">
<c:url var="editUrl" value="/test/customer/edit?customerId=${customer.customerId}"/>
<tr>
<td><c:out value="${customer.customerId}" /></td>
<td><c:out value="${customer.customerCountry}" /></td>
<td><c:out value="${customer.customerName}" /></td>
<td>Edit</td>
</tr>
</c:forEach>
</tbody>
</table>
and it should work. You'd have to reset the editUrl for each customer anyway.
It may be because of you are accepting customerId as Integer, try to accept it as String.
try this one :
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEdit(#RequestParam("customerId") String customerId, Model model) {
Customer existingCustomer = customerService.retrieveCustomer(Integer.parseInt(customerId));
model.addAttribute("customerAttribute", existingCustomer);
return "edit-customer";
}
#RequestMapping(value = "/edit", method = RequestMethod.POST)
public String postEdit(#RequestParam("customerId") String customerId,
#ModelAttribute("customerAttribute") #Valid Customer customer, BindingResult result) {
if (result.hasErrors()) {
return "edit-customer";
}
customer.setCustomerId(Integer.parseInt(customerId));
customerService.editCustomer(customer);
return "redirect:/test/customer/list";

How to fetch from a jquery datatable an array of second colum cells subject to checkbox in first column

I have a table as follows
<table id="vainTbl6" class="dtable" cellpadding="3" cellspacing="1" border="0">
<thead>
<tr><th>check</td><th>Morphosal</th><th>goat </th><th>the other</th></tr>
</thead>
<tbody id="tbdy">
<tr class="gradeX">
<td><input type="checkbox" class = "chcktbl" /></td>
<td style="width:55%">-Approve the femuneration Gommiqee purpirt</td>
<td>pontpose</td></tr>
<tr class="gradeX">
<td><input type="checkbox" class = "chcktbl" /></td>
<td style="width:55%">-Declare a final truce</td>
<td>More</td></tr>
<tr class="gradeX"><td><input type="checkbox" class = "chcktbl" /></td>
<td style="width:55%">-Amend the articles of asscotonation</td>
<td>Four</td></tr>
<tr class="gradeX"><td><input type="checkbox" class = "chcktbl" /></td>
<td style="width:55%">-Re-elect Bandanna la banana for warden</td>
<td>Floor</td></tr>
</tbody>
</table>
and the first column is a checkbox. I need to fetch all the second column cells where the checkbox in the first column is set to true
I tried using this, but to no avail.
function extractRowCell(divNode){
alert(divNode.id);
$('#tbdy tr td').each(function() {
alert('hello');
var aRowData = this.cells
alert(aRowData[1].firstChild.value);
return aRowData;
});
}
The call is as follows:
<a id="la" href='#' onclick='extractRowCell(this.parentNode)' style="position:absolute; top:280px; left:350px;">Votes & Concerns</a>
The alert in the function triggers though with the correct value.
TIA
To iterate over the td's simply do the following.
$('#tbdy tr td').each(function() {
alert( $(this).text() );
});
You can do this
<table><tbody id="tbdy">
<tr class="gradeX">
<td><input type="checkbox" class = "chcktbl" /></td>
<td style="width:55%" class="item">-Approve the femuneration Gommiqee purpirt</td>
<td>pontpose</td></tr>
<tr class="gradeX">
<td><input type="checkbox" class = "chcktbl" /></td>
<td style="width:55%" class="item">-Declare a final truce</td>
<td>More</td></tr>
<tr class="gradeX"><td><input type="checkbox" class = "chcktbl" /></td>
<td style="width:55%" class="item">-Amend the articles of asscotonation</td>
<td>Four</td></tr>
<tr class="gradeX"><td><input type="checkbox" class = "chcktbl" /></td>
<td style="width:55%" class="item">-Re-elect Bandanna la banana for warden</td>
<td>Floor</td></tr>
</tbody>
</table>
<button>Get</button>
<script>
$("button").click(function(){
var ret="";
$("#tbdy tr td:first").each(function()
{
if($("input:checked").length!=0)
{
ret=$("input:checked").parent().parent().find("td.item").text();
}
});
alert(ret);
});
</script>

Web Flow problems from GET Jsp to a POST JSP (Form) - Spring MVC Annotated

i have a JSP with hyperlink
<table>
<tr>
<td>Product Name : </td>
<td>${product.name}</td>
</tr>
<tr>
<td>Description:</td>
<td>${product.description}</td>
</tr>
<tr>
<td>Price:</td>
<td>${product.price}</td>
</tr>
<tr><td> </td></tr>
<tr>
<td>
Add to shopping basket
</td>
</tr>
<tr><td> </td></tr>
<tr><td> </td></tr>
<tr>
<td>
<table>
<tr>
<td>Return to Home Page</td>
<td> </td>
<td>Logout
(<security:authentication property="principal.username" />)
</td>
</tr>
</table>
</td>
</tr>
And the controller
#Controller
#SessionAttributes("basket")
public class ShopBasketController {
private BasketManager basketManager;
private CustomerManager customerManager;
private CategoryManager categoryManager;
#Autowired
public ShopBasketController(BasketManager basketManager, CustomerManager customerManager, CategoryManager categoryManager) {
this.basketManager = basketManager;
this.customerManager = customerManager;
this.categoryManager = categoryManager;
}
#RequestMapping(value="/basketItems", method=RequestMethod.POST)
public String removeProduct(#ModelAttribute("basket") Basket basket, BindingResult bindingResult, Model model) {
Basket newBasket = ShoppingBasketUtils.removeFromBasket(basket, basketManager);
basketManager.update(newBasket);
model.addAttribute("basket",newBasket);
model.addAttribute("customer", "Sonx"+" Nkuks");
model.addAttribute("totalItems", basketManager.getTotalNumberOfItems(basket));
model.addAttribute("totalPrice", ShoppingBasketUtils.currencyFormat(basketManager.getTotalProductPrice(basket)));
return "basketItems";
}
#RequestMapping("/populateBasket")
public String populateBasket(#RequestParam("code") String productCode, #RequestParam("name") String categoryName, Model model) {
Customer customer = customerManager.getCustomer("Sonx", "Nkuks");
if(customer != null) {
Basket shopBasket = ShoppingBasketUtils.addToBasket(productCode, categoryManager.getCategory(categoryName),
basketManager.getBasket(customer.getReferenceNumber()), basketManager);
basketManager.update(shopBasket);
model.addAttribute("basket",shopBasket);
model.addAttribute("customer", customer.getFirstName()+" "+customer.getLastName());
model.addAttribute("totalItems", basketManager.getTotalNumberOfItems(shopBasket));
model.addAttribute("totalPrice", ShoppingBasketUtils.currencyFormat(basketManager.getTotalProductPrice(shopBasket)));
return "basketItems";
}
model.addAttribute("customer", "test".concat(" test"));
return "/error";
}
}
Then the form ...
<form:form commandName="basket">
<table>
<tr>
<td>
<table>
<tr>
<td>Customer Name : </td>
<td>${customer}</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="600" border="1" cellspacing="0" cellpadding="2"
border="0">
<thead>
<tr>
<td>Products:</td>
</tr>
<tr>
<td>Product Name</td>
<td>Product Code</td>
<td>Description</td>
<td>Price</td>
<td>Remove</td>
</tr>
</thead>
<tbody>
<c:forEach items="${basket.products}" var="product">
<tr>
<td>${product.name}</td>
<td>${product.productCode}</td>
<td>${product.description}</td>
<td>${product.price}</td>
<td><form:checkbox path="removeItemCodes" value="${product.productCode}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<table>
<tr>
<td>Total Price</td>
<td> </td>
<td>${totalPrice}</td>
</tr>
<tr>
<td>Total Items</td>
<td> </td>
<td>${totalItems}</td>
</tr>
</table>
</td>
</tr>
<tr><td> </td></tr>
<tr>
<td><input type="submit" value="Remove Items" /></td>
</tr>
<tr><td> </td></tr>
<tr><td> </td></tr>
<tr>
<td>
<table>
<tr>
<td>Return to Home Page</td>
<td> </td>
<td>Logout
(<security:authentication property="principal.username" />)
</td>
</tr>
</table>
</td>
</tr>
</table>
When i press the link from the first JSP "" the controller succesfully execute the method populateBasket and loads the Form. But when i submit the form, i want it to call the POST method (basketItems)... But it doesn't, pressng the submit button always executes the GET method (populateBasket) .. This doesn't happen if i load the form directly from the index page, it loads successfully . Problem is when coming from that JSP ?
If you want the form to submit to a different URL from the one that was used to retrieve the page, you need to explicitly set the action on it. Otherwise Spring is going to just fill it in with the current URL.

Categories