Passing list<object> to thymeleaf with Spring boot - java

I have part of the controller:
#RequestMapping(value = "1", method = RequestMethod.GET)
public String greeting(#RequestParam(value="1", required = false, defaultValue = "1") int id, Model model){
List<Question> survey = surveyDAO.getSurveyById(id);
model.addAttribute("survey", survey);
return "showSurvey";
}
where I try to addAttribute List<Question> to be passed on to thymeleaf page. But on the thymeleaf side I only get the "cannot resolve" error.
Part of the .html in showSurvey.html
<div class="col-sm-12">
<table class="table table-hover">
<tr th:each="survey: ${survey}">
<td th:text="${survey">1</td>
<!-- <td>Title ...</td>-->
</tr>
</table>
</div>
Packaging with mvn package and then running the jar starts up the application, and it works, but crashes when trying to resolve "survey" on showSurvey.html so SurveyDAO.GetSurveyById(id); actually comes back properly.
So how should I go about passing the list and then showing proper values out of it? It has two int and String for all that matters.

You are missing a right "}" - I have just tested this, and it works fine:
<table>
<tr th:each="survey : ${survey}">
<td th:text="${survey}">1</td>
</tr>
</table>
Just a typo.

Like I said in the comments your code doesn't look right.
Fix your code like so:
<div class="col-sm-12">
<table class="table table-hover">
<tr th:each="survey: ${survey}">
<td th:text="${survey.id}">1</td> // id is a property of the Question class
</tr>
</table>
</div>

Related

How to pass arguments to a java api from html code using play framework?

I want to pass arguments from HTML view to Java API in play framework.
I've written the following code. What changes should be done to successfully pass the arguments from Html view to API in java controller?.
When i tried passing it as #w.username and #w.email or by keeping '#w.username' or #w.username i've got error.
#import model.User
#(users: List[User])
<html>
<body>
<h1>Users</h1>
<table>
<thead>
<th>User Name</th>
<th>Email</th>
<th>Status</th>
</thead>
<tbody>
#for(w <- users) {
<tr>
<td>#w.username</td>
<td>#w.email</td>
<td>#w.status</td>
<td>
<form action="#routes.UserController.getUser(w.username,w.email)">
<input type = "submit" value="View Deatils">
</form>
</td>
</tr>
}
</tbody>
</table>
</body>
</html>
It must work just like you wrote it:
#routes.UserController.getUser(w.username,w.email)

adding an icon menu from another jsp file as a column to a datatable in liferay

There are 2 tables here:
The table below is using purely container to display populate the tables from database whereas the one above is using datatable.
However i wish to duplicate the last column of displaying a icon menu for edit and delete actions which is contained inside actions.jsp inside the table above.
This is my partial code in view.jsp displaying the datatables.
<%
List<Guestbook> guestbookList = GuestbookLocalServiceUtil.getGuestbooks(scopeGroupId);
request.setAttribute("guestbookList", guestbookList);
%>
<table id="gbdb" class="table table-bordered table-striped" style="width:100%">
<thead>
<tr>
<th>Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${guestbookList}" var="guestbook">
<tr>
<td>${guestbook.name}</td>
<td>${guestbook.status}</td>
<td><jsp:include page="${actions.jsp}" flush="true" /></td>
</tr>
</c:forEach>
</tbody>
</table>
However as you can see my function of diplaying actions.jsp is not similar to the method for using container where i can just referenced the path using
<td> <liferay-ui:search-container-column-jsp
align="right"
path="/guestbookadminportlet/guestbook_actions.jsp" /></td>
Please help me with the correct way of displaying by referencing to actions.jsp
You should not include whole jsp as an action column if using jQuery data-table,
Let's assume you need to add Delete book action so your td should be replace by following code.
<td>
<portlet:actionURL name="<%=DELETE_BOOK%>" var="deleteBookUrl">
<portlet:param name="bookId" value="${book.id}"/>
</portlet:actionURL>
<input type="button" onclick="location.href='${deleteBookUrl}'" value="Delete"/>
</td>
Hope this will help you.

List all available model attributes in Thymeleaf

For debugging purposes I would like to list all model attributes available to my thymeleaf template while it is rendering.
Something like:
<table>
<tr th:each="model : ${*}">
<td th:text="${model}"></td>
</tr>
</table>
But obviously that's nonsense, and I get a well-deserved error.
(org.springframework.expression.spel.SpelParseException: EL1070E:(pos 0): Problem parsing left operand)
Is there a way of outputting such debug information? I'd settle even for some logging output.
Or, does Thymeleaf provide something similar to Struts 2's struts.devMode where it added a debug section at the bottom of the page listing all available properties?
Try this:
<table>
<tr th:each="var : ${#vars}">
<td th:text="${var.key}"></td>
<td th:text="${var.value}"></td>
</tr>
</table>
The accepted answer does not seem to work for Thymeleaf 3; here's an update. Please note that I'm using Spring; this might not work for non-Spring apps.
<table>
<tr th:each="var : ${#vars.getVariableNames()}">
<td th:text="${var}"></td>
<td th:text="${#vars.getVariable(var)}"></td>
</tr>
<!--
Adding these manually because they are considered special.
see https://github.com/thymeleaf/thymeleaf/blob/thymeleaf-3.0.3.RELEASE/src/main/java/org/thymeleaf/context/WebEngineContext.java#L199
-->
<tr>
<td>param</td>
<td th:text="${#vars.getVariable('param')}"></td>
</tr>
<tr>
<td>session</td>
<td th:text="${#vars.getVariable('session')}"></td>
</tr>
<tr>
<td>application</td>
<td th:text="${#vars.getVariable('application')}"></td>
</tr>
</table>
That said, what I've done is created a standalone Bean that makes things a bit prettier and dumps to logs instead of to HTML:
#Component
public class ThymeleafDumper {
private Logger log = LoggerFactory.getLogger(ThymeleafDumper.class);
public void dumpToLog(WebEngineContext ctx) {
log.debug("Thymeleaf context: {}", formatThisUpNicely(ctx));
}
// ... etc
}
Where formatThisUpNicely can use ctx.getVariableNames(), put the results into a SortedMap, export to json, whatever. Don't forget those three 'special' variables!
Then expose an instance of it as a #ModelAttribute in a Controller or a ControllerAdvice:
#ControllerAdvice
public class SomeControllerAdvice {
#Autowired
private ThymeleafDumper thymeleafDumper;
#ModelAttribute("dumper")
public ThymeleafDumper dumper() {
return this.thymeleafDumper;
}
}
Then in my template run:
<div th:text="${dumper.dumpToLog(#vars)}"/>
these are all the logging available configurations :
log4j.logger.org.thymeleaf=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.CONFIG=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.TIMER=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.TEMPLATE_CACHE=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.FRAGMENT_CACHE=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.MESSAGE_CACHE=DEBUG
log4j.logger.org.thymeleaf.TemplateEngine.cache.EXPRESSION_CACHE=DEBUG
these will log all the thymeleaf actions. I hope it is helpful.
Thymeleaf 3.0:
To put it short, try the following:
<table>
<tr th:each="var : ${param.keySet()}">
<td th:text="${var}"></td>
<td th:text="${param.get(var)}"></td>
</tr>
</table>
When a #Controller returns some value stored in a Spring Model, the values are actually stored as request parameters, which is accessible using:
request.getParameter("paramName");
Thymeleaf provides a similar functionality: "Web context namespaces for request/session attributes", the syntax is as stated.
The Thymeleaf built-in ${param} kewords returns an WebRequestParamsVariablesMap extends VariablesMap<String,String[]> object,
whose keySet() method returns a String[], which contains those variable names within a httprequest.

How to implement edit functionality in ThymeLeaf in Spring MVC

I am using this tutorial
I see delete functionality for each row:
7.6 Dynamic fields
Thanks to the advanced form-field binding capabilities in Spring MVC,
we can use complex Spring EL expressions to bind dynamic form fields
to our form-backing bean. This will allow us to create new Row objects
in our SeedStarter bean, and to add those rows’ fields to our form at
user request.
In order to do this, we will need a couple of new mapped methods in
our controller, which will add or remove a row from our SeedStarter
depending on the existence of specific request parameters:
#RequestMapping(value="/seedstartermng", params={"addRow"})
public String addRow(final SeedStarter seedStarter, final BindingResult bindingResult) {
seedStarter.getRows().add(new Row());
return "seedstartermng";
}
#RequestMapping(value="/seedstartermng", params={"removeRow"})
public String removeRow(
final SeedStarter seedStarter, final BindingResult bindingResult,
final HttpServletRequest req) {
final Integer rowId = Integer.valueOf(req.getParameter("removeRow"));
seedStarter.getRows().remove(rowId.intValue());
return "seedstartermng";
}
And now we can add a dynamic table to our form:
<table>
<thead>
<tr>
<th th:text="#{seedstarter.rows.head.rownum}">Row</th>
<th th:text="#{seedstarter.rows.head.variety}">Variety</th>
<th th:text="#{seedstarter.rows.head.seedsPerCell}">Seeds per cell</th>
<th>
<button type="submit" name="addRow" th:text="#{seedstarter.row.add}">Add row</button>
</th>
</tr>
</thead>
<tbody>
<tr th:each="row,rowStat : *{rows}">
<td th:text="${rowStat.count}">1</td>
<td>
<select th:field="*{rows[__${rowStat.index}__].variety}">
<option th:each="var : ${allVarieties}"
th:value="${var.id}"
th:text="${var.name}">Thymus Thymi</option>
</select>
</td>
<td>
<input type="text" th:field="*{rows[__${rowStat.index}__].seedsPerCell}" />
</td>
<td>
<button type="submit" name="removeRow"
th:value="${rowStat.index}" th:text="#{seedstarter.row.remove}">Remove row</button>
</td>
</tr>
</tbody>
</table>
Quite a lot of things to see here, but not much we should not
understand by now… except for one strange thing:
Now I won't implement edit functionality.
Ideas?

do log-out from a selected session id from a View in spring mvc

I don't know if the titles says what i'm looking for.
Basically i got a table that shows current logged-in sessions. I'd like to be able to change their status and log them out. This is the JSTL code:
<div id="users_table_div">
<table id="box-table" style="width: 690px">
<thead>
<tr>
<th>IP</th>
<th>USER NAME</th>
<th>LAST ACTIVITY</th>
<th>LOGIN STATUS</th>
</tr>
</thead>
<tbody>
<c:forEach var="userDetail" items="${userSessionData}">
<tr>
<td><c:out value="${userDetail.ip}"/></td>
<td><c:out value="${userDetail.username}"/></td>
<td><c:out value="${userDetail.lastActivity}"/></td>
<td><img src="images/sign-out.png" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
Currently i've set a javascript function in the sessionId, but there might be another way to log out a selected user by its sessionId using spring security MVC.
So from the controller, i get different session data from all the users.
IP, Username, LastActivity and their SessionId (to log them out)
Is there a nice way to manage this?
This has been already resolved.
Just in case other is under the same issue:
I just made another #RequestMapping in the Controller with the sessionId passed from the view as the following:
<a href="<c:url value='/endsession?sessionId=${userDetail.sessionId}' />">
Then in the Controller the code was very simple:
#RequestMapping(value="/endsession", method = RequestMethod.GET)
public String endSession(String sessionId, Principal principal) {
logger.info("Removing sessionID = " + sessionId);
sessionRegistry.getSessionInformation(sessionId).expireNow();
return "activeusers";
}
And taraam :D
Hope it helps to others as well.

Categories