i got my student controller here and listStudent atribute
but in my index.html it cannot get atribute
Thanks for reading and helping me
as andrewJames mentioned already, you will need to access your List the same way you defined it.
Say you use the following Controller as you defined:
#GetMapping("/")
public String viewHomePage(Model model) {
model.addAttribute("students", studentService.getAllStudents());
return "index";
}
Then you will need to use "students" in your Thymleaf Template to access the List.
<tr th:each="student : ${students}">
<td th:text="${student.getScode()}">ID</td>
<td th:text="${student.getSname()}"></td>
<td th:text="${student.getDid()}"></td>
<td th:text="${student.getGid()}"></td>
<td th:text="${student.getSsid()()}"></td>
</tr>
Hope it helps.
Related
These are my simple Thymeleaf table HTML file and Spring MVC controller codes. First below is my table image.
I try to make some html codes to transfer the post id value to view codes when the 'Edit' or 'Delete' link are clicked, but I have no idea how to do. These are my Spring MVC Controller codes and view.html codes.
#Controller
public class PostController {
#Autowired
private PostService postService;
#RequestMapping("/posts/view/{id}")
public String view(#PathVariable("id") Long id, Model model) {
Post post = postService.findById(id);
model.addAttribute("post", post);
return "posts/view";
}
And,
<table id="blogTable" border="1" width ="1000" height="400" align = "center">
<thead>
<tr>
<th>Post ID</th>
<th>Post Title</th>
<th>Post Content</th>
<th>Date</th>
<th>Author</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr th:each="post : ${posts}">
<td th:text="${post.id}">Post ID</td>
<td th:text="${post.title}">Post Title</td>
<td th:text="${post.body}">Post Content</td>
<td th:text="${post.date}">Date</td>
<!-- <td th:text="${post.auther.userName()}">Author</td> -->
<td>
Edit<br/> ==> How to transfer the post.id parameter to th:href?
Delete ==> How to transfer the post.id parameter to th:href?
</td>
</tr>
</tbody>
</table>
I am a beginner in HTML and Spring. How can I put post.id value into view mvc controller through th:href tag?
Use th:href like described in the documentation
th:href is an attribute modifier attribute: once processed, it will compute the link URL to be used and set the href attribute of the tag to this URL.
We are allowed to use expressions for URL parameters (as you can see in orderId=${o.id}). The required URL-encoding operations will also be automatically performed.
If several parameters are needed, these will be separated by commas like #{/order/process(execId=${execId},execType='FAST')}
Variable templates are also allowed in URL paths, like #{/order/{orderId}/details(orderId=${orderId})}
For example (notice the th:href and the parameter postId that receives the value from your variable post):
<td>
Edit<br/> ==> How to transfer the post.id parameter to th:href?
</td>
You can add parameters in parentheses:
<a th:href="#{/index(param1='value1',param2='value2')}">
Thymeleaf evaluates the above to:
<a href="/index?param1=value1,m2=value2">
For example, suppose we set default value to two parameters; name="Dracula" and age = 25.
<a th:href=#{/person(name=${name},age=${age})}></a>
I used in this format and work fine.
<a th:href="#{${urlBase} + '/#!/pedido' + ${other.value}" target="_blank">Link</a>
You can something try like following:
Edit<br/>
Delete
I have a table filled with data from database, now I'm working on a method that deletes a row by giving its id:
#RequestMapping(value= "/appel/delete/{id}", method = RequestMethod.GET)
public String delete(#PathVariable("id") Long id ) {
appelService.deleteAppel(id);
return ("index");
}
the thymeleaf table is this:
<tbody>
<tr th:each="appel : ${list}">
<td th:text="${appel.id}"></td>
<td th:text="${appel.serviceCode}"></td>
<td th:text="${appel.description}"></td>
<td th:text="${appel.answer}"></td>
<td>Update</td>
<td><a th:href="#{'/appel/delete/' + appel.id}">Delete</a></td>
</tr>
</tbody>
Every time I click on the delete link I get this message:
I don't understand where the error is and what could I change.
It's seems to be a problem with the string concatenation in theth:href, try with something like this instead.
<td><a th:href="#{/appel/delete/{id}(id=${appel.id})}" >Delete</a></td>
Ok, its time to seek help; I am sending a (shopping) Cart ModelAttribute to my jsp, allowing the user to edit the quantity, when the Model is POST to the controller the fields are null except the editable (quantity) field. I have researched for days on similar issues but nothing is matching. I am using spring 3.1.
Here is my controller on the GET and POST:
#Controller
public class CartController {
#Autowired
private Cart cart;
#RequestMapping(value = "/cart", method = RequestMethod.GET)
public String showCart(Model model) {
logger.debug("CartController.showCart() Cart: {}", this.cart);
model.addAttribute(cart);
return "cart/cart";
}
and POST
#RequestMapping(value = "/cart", method = RequestMethod.POST, params = "update")
public String update(#ModelAttribute("cart") Cart cart, BindingResult result, Model model) {
logger.debug("CartController.update() Cart: {}", cart);
return "cart/cart";
}
my jsp:
<div class="container MainContent">
<form:form method="POST" modelAttribute="cart">
<fieldset>
<legend>Cart</legend>
<table class="table">
<thead>
<tr>
<th>Product Name</th>
<th>Quantity</th>
<th>Product Price</th>
</tr>
</thead>
<tbody>
<c:forEach items="${cart.cartDetails}" var="cartDetail" varStatus="status">
<tr>
<td>${cartDetail.product.name}</td>
<td><form:input path="cartDetails[${status.index}].quantity" size="1" /></td>
<td>${cartDetail.price}</td>
</c:forEach>
<tr>
<b><td colspan="2" align="right"><spring:message code="order.total" /></b>
</td>
<td>${cart.totalCartPrice}</td>
</tr>
</tbody>
</table>
</fieldset>
<div></div>
<button id="order" name="order">
<spring:message code="button.order" />
</button>
<button id="update" name="update">
<spring:message code="button.update" />
</button>
</form:form>
</div>
and the log results for cart before on GET:
CartController.showCart() Cart: Cart [cartDetails=[CartDetail
product=com.Product#c26440[name=My Name],
quantity=1]], totalCartPrice=10.00]
and after updating the quantity from 1 to 3 in the jsp and then POST to the controller:
CartController.update() Cart: Cart [cartDetails=[CartDetail
[product=null, quantity=3]], totalCartPrice=null]
I've read several similar post here and on the Spring forum and tried different suggested solutions with no luck. It seems like my edited quantity results are getting bound to the Object correctly but why aren’t the others?
Assuming you have all the necessary fields in your Form object;
You have to specify the form fields and fill the value with your data.
<td>${cartDetail.product.name}</td>
will only print the result to the screen. If you want to bind it to your form you have to put it in a spring form input such as:
<form:input path="productName" value="${cartDetail.product.name}"/>
If you don't want it to be editable then you can put it into a hidden field but in the end you'll have to put it in a form element in the jsp and have a corresponding field in your form POJO
Seems other fields aren't bound, try to bind for example product name
<td>${cartDetail.product.name}
<form:hidden path="cartDetails[${status.index}].product.name" value="${cartDetail.product.name}"/></td>
I once spent a lot of time investigating a similar issue. Finally I found the culprit inside a Binder's initialization method:
#InitBinder
void initBinder(final WebDataBinder binder) {
binder.setAllowedFields("name", ...);
}
This method sets a restriction on fields that are allowed for binding. And all the other fields are unbound, naturally resulting in null values.
The other possible reason: incorrect setters in a Bean annotated with #ModelAttribute. For example, Object setName(String name) instead of void setName(String).
I have got webapp in spring 3 mvc. The case is that I have index page with url, when user click on them should be display another page with details of choosed information. Now the details page is shown but without any information (on index page is creating model with correct variable but not in details controller - in debug mode).
index controller method:
#RequestMapping(value="/{site}", method = RequestMethod.GET)
public String showDetails(#RequestParam(value = "site", required = true) String site, Model model){
Catalog product = catalogEndpoint.getByTitle(site);
model.addAttribute("product", product);
return "details";
}
index html:
<form action="#" th:object="${product}" method="post" th:action="#{/details}">
<table border="0" width="600" th:each="sb, poz : ${product}" >
<tr >
<td rowspan="3" width="20"><span th:text="${poz.count}"></span></td>
<td>
<a th:href="#{/details/(site=${sb.tytul})}" th:value="${site}"><span th:text="${sb.tytul}"></span></a>
</td>
</tr>
<tr >
<td><span th:text="${sb.adres}"></span></td>
</tr>
<tr>
<td>category:<b><span th:text="${sb.category.name}"></span></b></td>
</tr>
</table>
</form>
details controller method:
#RequestMapping(value = "details/{site}", method = RequestMethod.GET)
public String showHomePage(#PathVariable(value = "site") String site, Model model){
model.addAttribute("product");
return "details";
}
details html:
<form th:object="${product}" method="get" th:action="#{/details}">
<table border="1" width="600" >
<tr >
<td ><span th:text="${tytul}"></span></td>
<td>
<span th:text="${opis}"></span>
</td>
<td><span th:text="${adres}"></span></td>
</tr>
</table>
</form>
I don't have any ideas how to map the details site (I tried a lot of solution but nothing). Thanks for help.
With thymeleaf, using th:object, you need to reference the fields of that object with *{}
<form th:object="${product}" method="get" th:action="#{/details}">
<table border="1" width="600" >
<tr >
<td ><span th:text="*{tytul}"></span></td>
<td>
<span th:text="*{opis}"></span>
</td>
<td><span th:text="*{adres}"></span></td>
</tr>
</table>
</form>
assuming tytul, opis, and adres are fields of product. Unless it's a type, don't forget
Catalog product = catalogEndpoint.getByTitle(site);
model.addAttribute("product", product);
in your details controller method, otherwise you won't have a Catalog model attribute.
inside your details controller where are you setting product object in your model ?
model.addAttribute("product");
is just settingstring object "product", fetch the product object and set it in details controller like you have done in showDetails method
Change
model.addAttribute("product");
To
Catalog product = catalogEndpoint.getByTitle(site);
model.addAttribute("product", product);
in "showPage" method.
I am developing an application in which i am using spring framework 3.1.1 and rest api. In it i have developed one rest controller which will on receiving "GET" request of url "/rest/host/{id}" will redirect the control to my view(form). Now after user fills up the form the posted data is also handled using rest. But in the method which i have written to handle post request all the parameters i am getting in one string which i want to parse and insert into the database. Can anybody tell which is the proper way to parse this spring data ? I can do it using String.split("&") but i don't think it is correct way to do that. Here is my code.
<form:form method="POST" action="/nagios-sms-1.0/rest/snooze/host/" commandName="snoozeBean">
<table width="100%" border="5" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table width="50%" border="5">
<tr>
<td colspan="3"></td>
</tr>
<tr>
<td width="30%"><form:label path="contactNumber">Enter host address</form:label></td>
<td width="30%"><form:input path="contactNumber" /></td>
<td />
</tr>
<tr>
<td width="30%"><form:label path="snoozeTimeoutValue">Enter Snooze time</form:label></td>
<td width="30%"><form:input path="snoozeTimeoutValue" /></td>
<td />
</tr>
<tr>
<td colspan="3">
<div id="buttons"
style="margin-left: 20Px; margin-right: 100px;">
<input type="submit" value="ok" /> <input type="reset" />
</div>
</td>
</tr>
</table>
</td>
</tr>
</table>
REST code..
1) GET handler method
#RequestMapping(value = "/host/{hostId}", method = RequestMethod.GET)
public String snoozeHost(#PathVariable int hostId, ModelMap map) {
Snooze snooze = new Snooze();
snooze.setHost_id(hostId);
map.put("snoozeBean", snooze);
return "host";
}
2) POST handler method
#RequestMapping(value = "/host", method = RequestMethod.POST)
#ResponseBody
public String snoozeHostOK(#RequestBody String payload) {
// i want to parse this payload data which contains my form fields.
System.out.println("data : " + payload);
return payload;
}
Any kind of help will be appreciated. Thanks in advance.
Instead of request body you can use #ModelAttribute and get all the form data bind in one pojo(snooze) filled by Spring Framework on post of the form.
You need to declare snooze in your get and post request mapped method as #ModelAttribute. That will let you get all your values from the form.
UPDATE
See your modified code here.
GET handler method
#RequestMapping(value = "/host/{hostId}", method = RequestMethod.GET)
public String snoozeHost(#PathVariable int hostId, #ModelAttribute Snooze snooze, ModelMap map) {
snooze.setHost_id(hostId);
return "host";
}
POST handler method
#RequestMapping(value = "/host", method = RequestMethod.POST)
#ResponseBody
public String snoozeHostOK(#ModelAttribute Snooze snooze) {
// you can use the setter methods of snooze object to retrieve the field values.
return payload;
}
Hope this helps you. Cheers.