I'm trying to automatically update view (here list named emprunts) after insert into my database. I use Springboot, H2, JPA, Thymeleaf, ...
There is a way to do it? Or have I to refresh the page with Get request after the insert ?
Thanks a lot!
HTML / View
...
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionEmprunts">
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">Usager</th>
<th scope="col">Exemplaire</th>
<th scope="col">Date de rendu</th>
<th scope="col">Statut</th>
</tr>
</thead>
<tbody>
<th:block th:each="emprunt : ${emprunts}">
<tr>
<!--/*#thymesVar id="emprunt" type="bibliotheque.model.Emprunt"*/-->
<td th:text="${emprunt.getUsager().getMail()}"></td>
<td th:text="${emprunt.getExemplaire().getOeuvre().getTitre()}"></td>
<td th:text="${emprunt.getDaterendu()}"></td>
<td th:text="${emprunt.getStatut()}"></td>
</tr>
</th:block>
</tbody>
</table>
</div>
</div>
...
Controller
#PostMapping
public ResponseEntity<?> newEmprunt(HttpEntity<String> infoEmprunt) throws IOException {
...
repository.save(object);
return new ResponseEntity<>(HttpStatus.CREATED);
}
If your view technology is thymeleaf then return html page instead of returning ResponseEntity(because response entity will return data in json format) and add data in model attribute.
There is a way to do it? Or have I to refresh the page with Get request after the insert ?
No need to refresh page just return html page from controller like below.
Emprunt emprunt = repository.save(object);
model.addAttribute("emprunt", emprunt);
return "show"; //show.html page
Related
This is my controller class read data method. I cant read spring data from requesting. when I do it from postman it works fine but cant read using html page.
#RequestMapping("/index")
public String ItemList(Model model) {
model.addAttribute("itemList", repository.findAll());
return "index";
}
Like this I try to read data using my index.html page
<h2>Medicine List</h2>
<form action="/index" method="POST">
<table>
<thead>
<tr>
<th>ID</th>
<th>MedicineName</th>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
<th>ExDate</th>
</tr>
</thead>
<tbody>
<tr th:each="item:${itemList}">
<td th:text="${item.id}"></td>
<td th:text="${item.MedicineName}"></td>
<td th:text="${item.Description}"></td>
<td th:text="${item.Quantity}"></td>
<td th:text="${item.Price}"></td>
<td th:text="${item.ExDate}"></td>
<td><form action="/delete/item:${itemList}" method="Delete"><input type="submit" value="Delete" /></form></td>
</tr>
</tbody>
</table>
</form>
Goal
After a POST request, I want to update a list. For example, if a user is added, so user list must be refresh.
So I do the post request, then I do a get request to update the content.
There is a way to do it without reload the page?
Thanks for your answer!
Ajax calls
function rafraichirContenu(url, type) {
$.ajax({
url: url,
type: type
}).done(function (response) {
$(document).html(response)
});
}
postRequest().done(function(response) {
rafraichirContenu('/emprunts/encours', 'GET');
...
});
Get Mapping
#GetMapping(value = "/encours")
public ModelAndView findAllEnCours() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("emprunts", empruntResource.getEmpruntsByStatutEquals(StatutEmprunt.EN_COURS));
modelAndView.setViewName("webapp/pages/emprunts");
return modelAndView;
}
HTML
<div id="collapseThree" class="collapse" aria-labelledby="headingThree" data-parent="#accordionEmprunts">
<div class="card-body">
<table class="table">
<thead>
<tr>
<th scope="col">Usager</th>
<th scope="col">Exemplaire</th>
<th scope="col">Date de rendu</th>
<th scope="col">Statut</th>
</tr>
</thead>
<tbody>
<th:block th:each="emprunt : ${emprunts}">
<tr>
<!--/*#thymesVar id="emprunt" type="bibliotheque.model.Emprunt"*/-->
<td th:text="${emprunt.getUsager().getMail()}"></td>
<td th:text="${emprunt.getExemplaire().getOeuvre().getTitre()}"></td>
<td th:text="${emprunt.getDaterendu()}"></td>
<td th:text="${emprunt.getStatut()}"></td>
</tr>
</th:block>
</tbody>
</table>
</div>
</div>
Console error
jquery.min.js:2 Uncaught TypeError: Cannot read property 'createDocumentFragment' of null
<table class="table">
<tr>
<th>Name</th>
</tr>
<tr th:each="recipe : ${recipes}">
<td th:text="${recipe.Name}"></td>
<td>
<span th:each="recipe,iterStat : ${recipes}">
</span>
</td>
<td>
<a th:href="#{/recipe/food/{id}(id=${recipe.id})}">view</a>
</td>
</tr>
I am trying to click this link above, utilizing this controller
#RequestMapping(value="recipe/food/{id}", method = RequestMethod.POST)
public String viewRecipe(#PathVariable int id, Model model){
model.addAttribute("name", recipeDao.findOne(id));
model.addAttribute("recipeText", recipeDao.findOne(id));
return "Recipes/food" ;
}
to display a single item, based on its id here
<table class="table">
<tr>
<th>Name</th>
</tr>
<form method ="post" th:action="recipe/food/{id}" th:object=${recipe}">
<tr th:each="recipe : ${recipes}">
<td th:text="${recipe.name}">text</td>
<td th:text="${recipe.recipeText}">text</td>
</tr>
<span th:errors="*{recipeText}" class="error"></span>
</form>
however i only get a 404, but the url information is correct
When you click the link it will execute a GET-request, so try changing the method in the Controller to method = RequestMethod.GET or simply remove method = RequestMethod.POST.
Update:
The part of the food template that is in the third code snippet is looping over a list named recipes, but the Controller method isn't adding a list as an attribute to the model only "name" and "recipeText". What you want is probably the template to display the recipe that you clicked the link for? Something like <h4 th:text="${name}"></h4> <span th:text="${recipeText}" />
I'm using thymeleaf as template engine. Now i want to return a single object from a list when submitting a form.
But i get this error message:
Failed to instantiate [here.my.object]: Is it an abstract class?; nested exception is java.lang.InstantiationException] with root cause
The object i want to return inherit from an abstract class, but it's already initialized, because it comes from the list. So why it doesn't work?
Here some code:
<div th:each="tool : ${toolList}">
<form th:action="#{/execute}" method="POST" th:object="${tool}">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th th:text="${tool.name}"></th>
</tr>
</thead>
<tbody>
<tr>
<td>Some output</td>
</tr>
<tr>
<td><button class="btn">Execute</button></td>
</tr>
</tbody>
</table>
</form>
</div>
And here the method from the controller:
#PostMapping("/execute")
public ModelAndView executeMethod(Tool tool) {
tool.execute();
return new ModelAndView("view/overview");
}
"Tool" is the abstract class.
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 !!
}
}