I cannot pass the message to my jsp - spring

my controller
#RequestMapping("/")
public String loadHome(#RequestParam(value="tab",defaultValue="pending_users") String tab,Model model) {
UsersManager um = new UsersManager();
TagsManager tm = new TagsManager();
if(tab.equals("pending_users"))
model.addAttribute("pending_users",um.getPendingUsers(""));
else if(tab.equals("registered_users"))
model.addAttribute("registered_users",ForumUserUtility.sortPointEarned(um.getUsers(0,um.getNoOfUsers(""),"")));
else if(tab.equals("suspended_users"))
model.addAttribute("suspended_users",ForumUserUtility.sortPointEarned(um.getSuspendedUsers(0,um.getNoOfUsers(""),"")));
else if(tab.equals("tags"))
model.addAttribute("tags",tm.getTagsPopular(""));
else if(tab.equals("admins")){
model.addAttribute("admins",ForumUserUtility.sortPointEarned(um.getAdminList(0,um.getNoOfUsers(""),"")));
}
model.addAttribute("tab",tab);
return "admin_view";
}
#RequestMapping("/DeleteAdmin")
public String deleteAdmin(#RequestParam(value="user_id") String userId, Model model){
UsersManager um = new UsersManager();
um.deleteAdmin(Integer.parseInt(userId));
model.addAttribute("messageAdmin", "Admin Successfully Deleted");
return loadHome("admins", model);
}
my jsp
<c:if test="${loggedInUserType == 'master_admin' }">
<c:if test="${tab == 'admins'}">
${messageAdmin }
<div>
<input onkeyup="showAdmins(this.value)" placeholder="Search Admin" type="text"/>
<div id="admin_box">
<c:if test="${not empty admins}">
<table class='table table-bordered' id="admins">
<tr>
<th colspan='6' style='text-align:center'>Admins</th>
</tr>
<tr>
<th style='text-align:center'>Username</th>
<th style='text-align:center'>First Name</th>
<th style='text-align:center'>Last Name</th>
<th style='text-align:center'>Email</th>
<th style='text-align:center' colspan="2">Action</th>
</tr>
<c:forEach var="user" items="${admins}">
<tr>
<td>${user.username}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.emailAddress}</td>
<td>
<a href="" onclick="return suspendUser(${user.userId})">
Suspend
</a>
</td>
<td>
<a href="" onclick="return deleteAdmin(${user.userId})">
Delete Admin
</a>
</td>
</tr>
</c:forEach>
</table>
</c:if>
</div>
<c:if test="${empty admins}">
<h1>No Suspended User</h1>
</c:if>
</div>
</c:if>
</c:if>
i need to send a message in my jsp notifying the user that the admin was already deleted but the ${messageAdmin} cannot be seen in my view. what do you think is wrong in my code? here is my jsp too.

Related

Delete mapping doesn't work, I'm getting 405 error

I have this controller:
#DeleteMapping("/delete/{id}")
public String deleteWallet(#PathVariable("id") long id, Model model) {
Wallet wallet = walletRepository.findById(id)
.orElseThrow(() -> new IllegalArgumentException("Invalid wallet Id:" + id));
walletRepository.delete(wallet);
model.addAttribute("wallets", walletRepository.findAll());
return "redirect:/";
}
And this is HTML:
<table class="table table-striped table-hover" id="productTable">
<thead>
<tr class="success">
<th>Wallet Name</th>
<th>Initial Balance</th>
</tr>
</thead>
<tbody>
<tr th:each="wallet : ${wallet}">
<td th:text="${wallet.walletName}"></td>
<td th:text="${wallet.initialBalance}"></td>
<td>
<a th:href="#{/api/wallet/delete/{id}(id = ${wallet.id})}">Delete</a>
</td>
</tr>
</tbody>
But when I press delete button its says:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]
I'm confused, my method is #DeleteMapping
Anyway, I found a way:
HTML:
<form th:action="#{/api/wallet/delete/{id}(id=${wallet.id})}"
th:object="${wallet}" method="post">
<input type="hidden" th:field="${wallet}">Delete</input>
<button type="submit" onClick="return confirm('sure?')"/>
</form>
Controller:
#PostMapping("/delete/{id}")
public String deleteWallet(#PathVariable("id") long id, Model model) {
walletService.deleteWalletById(id);
return "redirect:/";
}

Getting the selected values from a checkbox list to the controller with Spring Boot

I'm using Spring Boot with Thymeleaf as viewer, and I want to delete all selected items from a table. Therefore, I need to pass to the controller a list with the values from the selected checkboxes.
This is my approach for the controller:
#PostMapping("/admin/rates/prices/delete")
public String delete(#ModelAttribute Rate price, ServletWebRequest request){
if(request.getParameterValues("idChecked") != null){
for(String idCheckedStr : request.getParameterValues("idChecked")){
int idrate = Integer.getInteger(idCheckedStr);
rateRepository.deleteRate(idrate);
}
}
return "redirect:/admin/rates/prices";
}
I get a Null Pointer Exception:
java.lang.NullPointerException: null
at com.rentalwebs.controllers.rates.PriceListController.delete(PriceListController.java:42)
I think this method should collet the values::
request.getParameterValues("idChecked")
This is the line at the form, which creates each checkbox with the Thymeleaf annotations:
<input type="checkbox" th:name="idChecked" th:value="${price.idrate}"/>
That's the view code for the form:
<form th:action='#{/admin/rates/prices/delete}'
method="POST"
th:object="${rate}">
<button type="submit" name='delete' value="delete"
class='btn btn-secondary btn-sm'
th:text="#{delete}"
data-toggle="tooltip" data-placement="right"
th:title="#{delete.selected}">
</button>
<p></p>
<table class='table table-sm responsive'>
<thead class='thead-default'>
<tr>
<th><input type="checkbox" id="checkAll"/></th>
<th th:text='#{from}'></th>
<th th:text='#{to}'></th>
<th th:text='#{price}'></th>
</tr>
</thead>
<tbody>
<tr th:each="price : ${prices}">
<td>
<input type="checkbox" th:name="idChecked" th:value="${price.idrate}"/>
</td>
<td th:text="${#temporals.format(price.datefrom, 'dd/MM/yyyy')}"></td>
<td th:text="${#temporals.format(price.dateto, 'dd/MM/yyyy')}"></td>
<td th:text="${price.price} + ' €'"></td>
</tr>
</tbody>
</table>
</form>
Thank you in advance for your help :-)
This is the code with the solution, taken from the comments:
#PostMapping("/admin/rates/prices")
public String delete(#RequestParam("idChecked") List<String> idrates){
if(idrates != null){
for(String idrateStr : idrates){
int idrate = Integer.parseInt(idrateStr);
rateRepository.deleteRate(idrate);
}
}
return "redirect:/admin/rates/prices";
}

Spring-MVC model updating only after page refresh

I am working on a spring-mvc project which adds notes using a JSP file. Right now, all CRUD operations work in the project. The only problem is to see the updated information in the database, I have to hit refresh browser button everytime. I checked flashattributes, but as I am not redirecting, just returning the object, I don't find that useful. I am posting my controller code along with JSP code. Any ideas why I need to hit refresh.
P.S : Refresh is not necessary for delete function, and yes, I tried using redirect already for other functions.
COntroller code :
#RequestMapping(value= "/note/add")
public String addNote(#ModelAttribute("notices") Notes p,Model model) {
Person person = personService.getCurrentlyAuthenticatedUser();
model.addAttribute("notices", new Notes());
model.addAttribute("listNotes",this.notesService.listNotes());
model.addAttribute("listNotes", this.notesService.listNotePerson(person));
model.addAttribute("section1",this.notesService.listNotesBySectionId(1,person));
model.addAttribute("section2",this.notesService.listNotesBySectionId(2,person));
model.addAttribute("section3",this.notesService.listNotesBySectionId(3,person));
}
#RequestMapping("/editnote/{id}")
public String editNote(#PathVariable("id") Integer id, Model model){
Person person = personService.getCurrentlyAuthenticatedUser();
model.addAttribute("notices", this.notesService.getNoteById(id));
model.addAttribute("section1",this.notesService.listNotesBySectionId(1,person));
model.addAttribute("section2",this.notesService.listNotesBySectionId(2,person));
model.addAttribute("section3",this.notesService.listNotesBySectionId(3,person));
}
#RequestMapping(value = "/note/listing", method=RequestMethod.GET)
public String listNotices(Model model) {
Person person = personService.getCurrentlyAuthenticatedUser();
model.addAttribute("notices",new Notes());
model.addAttribute("listNotes", this.notesService.listNotePerson(person));
model.addAttribute("section1",this.notesService.listNotesBySectionId(1,person));
model.addAttribute("section2",this.notesService.listNotesBySectionId(2,person));
model.addAttribute("section3",this.notesService.listNotesBySectionId(3,person));
}
JSP code :
<c:url var="addAction" value="/note/add" ></c:url>
<form:form action="${addAction}" commandName="notices">
<table>
<c:if test="${!empty notices.notetext}">
<tr>
<td>
<form:label path="noticesid">
<spring:message text="noticesid"/>
</form:label>
</td>
<td>
<form:input path="noticesid" readonly="true" size="8" disabled="true" />
<form:hidden path="noticesid" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="notetext">
<spring:message text="notetext"/>
</form:label>
</td>
<td>
<form:input path="notetext" />
</td>
</tr>
<tr>
<td>
<form:label path="notetag" >
<spring:message text="notetag"/>
</form:label>
</td>
<td>
<form:input path="notetag"/>
</td>
</tr>
<tr>
<td>
<form:label path="notecolor">
<spring:message text="notecolor"/>
</form:label>
</td>
<td>
<form:input path="notecolor" />
</td>
</tr>
<tr>
<td>
<form:label path="canvasid">
<spring:message text="canvasid"/>
</form:label>
</td>
<td>
<form:input path="canvasid" />
</td>
</tr>
<tr>
<td>
<form:label path="sectionid">
<spring:message text="sectionid"/>
</form:label>
</td>
<td>
<form:input path="sectionid" />
</td>
</tr>
<tr>
<td>
<form:label path="canvasnName">
<spring:message text="canvasnName"/>
</form:label>
</td>
<td>
<form:input path="canvasnName" />
</td>
</tr>
<tr>
<td colspan="2">
<c:if test="${!empty notices.noticesid}">
<input type="submit"
value="<spring:message text="Edit note"/>" />
</c:if>
<c:if test="${empty notices.notetext}">
<input type="submit"
value="<spring:message text="Add note"/>" />
</c:if>
</td>
</tr>
</table>
</form:form>
<br>
<h3>Notes List</h3>
<c:url var="listAction" value="/note/listing" ></c:url>
<form:form action="${section1}" commandName="notices" method="post"> // Same code with section2 and section3
<c:if test="${!empty notices.noticesid}">
<table class="tg">
<tr>
<th width="80">Notes ID</th>
<th width="120">Notes text</th>
<th width="120">Note Tag</th>
<th width="120">Note color</th>
<th width="120">Note section</th>
<th width="120">Canvas id</th>
<th width="120">Canvas name</th>
<th width="120">Other id</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${section1}" var="notices">
<tr>
<td>${notices.noticesid}</td>
<td>${notices.notetext}</td>
<td>${notices.notetag}</td>
<td>${notices.notecolor}</td>
<td>${notices.sectionid}</td>
<td>${notices.canvasid}</td>
<td>${notices.canvasnName}</td>
<td>${notices.personid}</td>
<td><a href="<c:url value='/editnote/${notices.noticesid}' />" >Edit</a></td>
<td><a href="<c:url value='/removenote/${notices.noticesid}' />" >Delete</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</form:form>
So I was able to solve it finally by calling return "redirect:/note/listing" at end of/note/add function.
To be completely clear on this answer, simply create:
ModelAndView controller, and at the end of your controller, please, add:
ModelAndView mv = new ModelAndView("redirect:/note/listing");
return mv;

share 'form fragment' between createForm.html, updateForm.html on thymeleaf

I use thymeleaf on spring.
I don't want to produce duplicated html page createForm.html and updateForm.html.
Maybe It requires copy & paste.
My code is below.
<form class="form-horizontal" role="form" th:action="${!template.new#{/templates}" method="post"
th:object="${template}">
...
</form>
When template is before saving(=create), action is '/templates'.
When tempalte is after saving(=update), action is '/templates/UUID/edit'.
=> It is rails convention.
You can also add this address to the ModelMap:
modelMap.add("address", "/templates")
th:action="#{${address}}"
HTML
<div class="form-group">
<label for="objectName">Name</label>
<input type="text" class="form-control" th:value="${object.name}" name="name"
id="objectName" placeholder="Name"/>
</div>
bottom HTML
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>Name 1</th>
<th>Name 2</th>
<th>Name 3</th>
</tr>
</thead>
<tbody>
<tr data-th-each="eachObject : ${obj}">
<td><a data-th-text="${eachObject.name}" th:href="#PATH/edit?Name=}+${eachObject.name}">...</a></td>
<td data-th-text="${eachObject.name2}">...</td>
<td data-th-text="${eachObject.name3}">...</td>
<td><a th:href="#{/PATH/delete?objname=}+${eachObject.name}">delete</a></td>
</tr>
</tbody>
</table>
</div>
Controller
#RequestMapping(value = "/create",method = RequestMethod.GET)
public String createMethod(Model model) {
Object obj = new Object();
model.addAttribute("Object", obj);
return "htmlpage";
}
controller
#RequestMapping(value = "/form/save", method = RequestMethod.POST)
public String campaignPost(#ModelAttribute("object") Object obj, Principle prin, Model model){
service.save(obj);
}

MVC3 ASP Replace null value with empty space on the view

I have the following view which returns some text if the POnumber is null.
What I think I need to have instead of the if(Model.Invoice.PONumber == null) is a check mechanism ( maybe multiple if statements ) that will check the fields LineNumber, Description, UnitOfMeasure, QtyOrdered and if any of them is null it will replace it with N/A or empty space but it will still allow the user to see the rest of information available.
Do you have any sugestions? I am new to MVC and any help will be apreciated.
Thank you in advance for your time and help,Bobby
<div class="contentWrapper2">
<div class="content2">
<div class="clr lfl w100">
<h1>Invoice Detail</h1>
<div class="return-btn">
<a class="btn btnStyleC btn-back-invoice" href="#Url.Action("InvoiceHistory", "Account")">
Back to Invoice List</a>
</div>
</div>
#if (Model.ErpError.Length > 0)
{
<div class="clr lfl w100 error">
#Html.Raw(Model.ErpError)
</div>
}
else
{
if(Model.Invoice.PONumber == null)
{
<div class="lfl w100 clr messaging">
<p>No information available at the moment for current invoice.
Please call our sales department for further assistance.
</p>
</div>
}
else
{
<div class="clr lfl w100">
<div class="order-number-date">
<table>
<tr>
<th class="col-1">
<h3>Invoice #:</h3>
</th>
<td class="col-2">
<h3>#Model.Invoice.InvoiceNumber</h3>
</td>
</tr>
<tr>
<th class="col-1">
<h3>Invoice Date:</h3>
</th>
<td class="col-2">
<h3>#Model.Invoice.InvoiceDate.ToShortDateString()</h3>
</td>
</tr>
</table>
</div>
<div class="order-number-date">
<table>
<tr>
<th class="col-1">
<h3>Order #:</h3>
</th>
<td class="col-2">
<h3>#Model.Invoice.OrderNumber</h3>
</td>
</tr>
<tr>
<th class="col-1">
<h3>PO #:</h3>
</th>
<td class="col-2">
<h3>#Model.Invoice.PONumber</h3>
</td>
</tr>
<tr>
<th class="col-1">
<h3>Due Date:</h3>
</th>
<td class="col-2">
<h3>#Model.Invoice.DueDate.ToShortDateString()</h3>
</td>
</tr>
</table>
</div>
</div>
<div class="clr lfl w100">
<div class="bill-ship">
<table>
<tr>
<th>
<h4>Billing Information</h4>
</th>
</tr>
<tr>
<td>#Model.Invoice.BTDisplayName
</td>
</tr>
<tr>
<td>
<#Html.Raw(Model.Invoice.BTAddress1)
</td>
</tr>
#if (!string.IsNullOrEmpty(Model.Invoice.BTAddress2))
{
<tr>
<td>#Html.Raw(Model.Invoice.BTAddress2)
</td>
</tr>
}
<tr>
<td>#Html.CityCommaStateZip(Model.Invoice.BTCity, Model.Invoice.BTState, Model.Invoice.BTZip)</td>
</tr>
<tr>
<td>#Model.Invoice.BTCountry
</td>
</tr>
<tr>
<td>#Model.Invoice.BTPhone1</td>
</tr>
<tr>
<td>#Model.Invoice.BTEmail
</td>
</tr>
</table>
</div>
</div>
if (Model.Invoice.InvoiceLines.Count > 0)
{
<div class="clr lfl w100 line-item-detail">
<table class="info-tbl">
<tr>
<th class="vid-item">Item #</th>
<th class="vid-desc">Description</th>
<th class="vid-um">
U/M
</th>
<th class="vid-qty">
Qty
</th>
<th class="vid-ship">
Ship Date
</th>
#if (Model.ShowPackslip)
{
<th class="vid-pack">Pack Slip</th>
}
<th class="vid-unit">Unit Price</th>
<th class="vid-ext">Ext Price</th>
</tr>
#foreach (var invoiceLine in Model.Invoice.InvoiceLines)
{
<tr>
<td class="vid-line">#invoiceLine.LineNumber</td>
<td class="vid-desc">#invoiceLine.Description</td>
<td class="vid-um">#invoiceLine.UnitOfMeasure</td>
<td class="vid-qty">#invoiceLine.QtyOrdered</td>
<td class="vid-ship">
#if (invoiceLine.ShipDate.ToShortDateString() == "1/1/0001")
{
}
else
{
#invoiceLine.ShipDate.ToShortDateString()
}
</td>
#if (Model.ShowPackslip)
{
<td class="vid-pack">
#invoiceLine.PackSlip
</td>
}
<td class="vid-unit">#invoiceLine.UnitPrice.ToCurrency()
</td>
<td class="vid-ext">#invoiceLine.ExtendedPrice.ToCurrency()
</td>
</tr>
}
</table>
</div>
}
<div class="clr lfl w100">
<table class="tbl-total">
<tr class="subtotal">
<th class="col-1">Subtotal</th>
<td class="col-2">#Model.Invoice.OrderSubTotal.ToCurrency()
</td>
</tr>
#if (Model.Invoice.DollarOffOrder > 0)
{
<tr>
<th class="col-1">Order Discount</th>
<td class="col-2">#Model.Invoice.DollarOffOrder.ToCurrency()</td>
</tr>
}
#if (Model.Invoice.ShippingAndHandling > 0)
{
<tr>
<th class="col-1">Shipping</th>
<td class="col-2">#Model.Invoice.ShippingAndHandling.ToCurrency()
</td>
</tr>
}
#if (Model.Invoice.MiscCharges > 0)
{
<tr>
<th class="col-1">Misc. Charges</th>
<td class="col-2">#Model.Invoice.MiscCharges.ToCurrency()</td>
</tr>
}
<tr>
<th class="col-1">Sales Tax</th>
<td class="col-2">#Model.Invoice.TotalTax.ToCurrency()</td>
</tr>
<tr>
<th class="col-1">Invoice Total</th>
<td class="col-2">#Model.Invoice.InvoiceTotal.ToCurrency()</td>
</tr>
</table>
</div>
<div class="clr lfl w100">
<a class="btn btnStyleB btn-print" href="javascript:window.print();">Print</a>
</div>
}
}
</div>
</div>
You could create a template called for example "nullcheck.cshtml" like:
#if (ViewBag.ValueToCheck == null) {
<div class="lfl w100 clr messaging">
<p>
No information available at the moment for #(ViewBag.Field).
Please call our sales department for further assistance.
</p>
</div>
}
else {
#Html.Partial(ViewBag.TargetTemplate, Model)
}
Then you call it from your main view:
#{
ViewBag.TargetTemplate = "okModel";
ViewBag.Field = "P.O.Number";
ViewBag.ValueToCheck = Model.Invoice.PONumber;
Html.RenderPartial("nullCheck", Model, ViewBag);
}
okModel.cshtml should be the part of your template you will display when the value is not null...
I haven't tested this myself but it should give you some ideas... contact me if things go wrong XD
Cheers!
This seems like something you should take care of in your controller.
public ActionResult YourControllerAction()
{
var myViewModel = SomeService.GetMyViewModel();
if (myViewModel.Invoice.PONumber == null)
{
myViewModel.Invoice.PONumber = "N/A";
}
//etc
}
This leaves your view clearer (my personal preference)
However in the view you could simply use the null coalescing operator like so:
#Model.Invoice.PONumber ?? "NA"

Resources