Java Spring Thymeleaf DataTable not working - java

I want to use dandelion datatables with thymeleaf.My html file is below:
<table id="myTableId"
dt:table="true"
dt:url="#{/dataTable}"
dt:serverside="true"
dt:processing="true"
dt:deferLoading="10">
<thead>
<tr>
<th dt:property="id">Id</th>
<th dt:property="name" dt:default="My default value !">name</th>
<th dt:property="state">state</th>
</tr>
</thead>
</table>
Controller :
#RequestMapping(value="/dataTable")
public #ResponseBody DatatablesResponse<ApplicationItem> allAppForTable(#DatatablesParams DatatablesCriterias criterias){
List<Application> appList=service.listApplications();
List<ApplicationItem> aa=new ArrayList<>();
for(Application a:appList){
ApplicationItem ai= new ApplicationItem();
ai.setId(a.getId());
ai.setName(a.getName());
ai.setState(a.getState());
aa.add(ai);
}
Long count=(long)appList.size();
DataSet<ApplicationItem> dataSet=new DataSet<ApplicationItem>(aa, count,null);
return DatatablesResponse.build(dataSet, criterias);
}
But when I enter this page ,table is empty.How can I initialize table when it loading first time.

According to documentation dt:deferLoadgin attribute:
... allows you to instruct DataTables to not make that initial request, rather it will use the data already on the page (no sorting etc will be applied to it).
Try to remove dt:deferLoading="10" attribute from deffinition of table.

Related

How to update automatically view after insert

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

How to submit table data in Spring Thymeleaf

I am following given link to submit table data to be saved in database
http://viralpatel.net/blogs/spring-mvc-multi-row-submit-java-list/
But the difference between given link and my implementation is that the front-end of link uses JSTL (JSP) while i am using Thymeleaf (HTML)
Below are the files being used
HTML Form :
<form method="POST" th:action="#{/updateAllRules}" th:field="${ruleForm}">
<table>
<thead>
<tr>
<th>S No</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr th:each="ruleModel,iteration : ${allRules}">
<td th:text="${ruleModel.id}"></td>
<td><input type="text" th:name="${'rule'+iteration.index+'.title'}" th:value="${ruleModel.title}"></td>
<td><input type="text" th:name="${'rule'+iteration.index+'.body'}" th:value="${ruleModel.body}"></td>
</tr>
</tbody>
</table>
<br>
<input type="submit" value="Update All">
</form>
Model Class :
public class Rule {
private Integer id;
private Date timestamp;
private String title;
private String body;
// constructor and Getter/Setters
}
Form Class :
public class RuleForm {
private List<Rule> rule;
public List<Rule> getRule() {
return rule;
}
public void setRule(List<Rule> rule) {
this.rule = rule;
}
}
Controller Method :
#RequestMapping(value = "/updateAllRules", method = RequestMethod.POST)
public String updateAllRules(#ModelAttribute("ruleForm") RuleForm ruleForm) throws IOException
{
System.out.println(ruleForm); // this prints com.web.model.RuleForm#235f9fcb
System.out.println(ruleForm.getRule()); //this prints null
return "redirect:/admin";
}
Please let me know what i am missing.
UPDATE 1:
Made changes as suggested. My new HTML form is as below
<form method="POST" th:action="#{/updateAllRules}" th:object="${ruleForm}">
<table>
<thead>
<tr>
<th>S No</th>
<th>Title</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr th:each="rule,iteration : ${ruleForm}">
<td th:field="*{rule[__${iteration.index}__].id}"></td>
<td><input type="text" th:field="*{rule[__${iteration.index}__].title}"></td>
<td><input type="text" th:field="*{rule[__${iteration.index}__].body}"></td>
</tr>
</tbody>
</table>
<br>
<input type="submit" value="Update All">
</form>
On making these changes following exception is being received when the page loads.
org.springframework.expression.spel.SpelEvaluationException: EL1008E: Property or field 'rule' cannot be found on object of type 'java.util.ArrayList' - maybe not public?
Please see that i am sending original list in model attribute "ruleForm" on page load. Once page loads the data and user make changes , i want to POST complete table back to controller.
Forms should have a th:object, rather than a th:field:
<form method="POST" th:action="#{/updateAllRules}" th:object="${ruleForm}">
Instead of using th:name and th:value, you should instead be using th:field which does both of those for you. Fields also should be specified using the *{...} syntax, which assumes the th:object automatically.
<input type="text" th:field="*{rule[__${iteration.index}__].title}" />
Everything else looks correct to me.

Thymeleaf table not displaying on html page in Spring Boot app

I have a table which is populated via a custom select statement to a database.
This has previously worked but now it is not displaying any values, not even the defaults.
I have created the table headings and here is the content declaration in the HTML:
<tr th:each="user : ${listUser}">
<td>
<a th:href="#{/editUser(user_id=${user.user_id})}">
<span th:text="${user.user_id}">Default ID</span>
</a>
</td>
<td th:text="${user.username}">Default username</td>
<td th:text="${user.email_address}">Default email</td>
<td th:text="${user.role_code}">Default role code</td>
<td th:text="${user.enabled_ind}">Default enabled</td>
<td>Default enabled</td>
</tr>
Here are the declarations in the Web Controller (The problems started when I added #GetMapping and #PostMapping, it seems to be ignoring #RequestMapping.
#GetMapping("/admin")
public String greetingForm(Model model) {
model.addAttribute("searchuser", new Searchuser());
return "admin";
}
#PostMapping("/userresults")
public String greetingSubmit(#ModelAttribute Searchuser searchuser) {
return "userresults";
}
#RequestMapping(value = "/userresults")
public ModelAndView listUser(ModelAndView model) throws IOException {
List<User> listUser = userDAO.loadAllUser();
model.addObject("listUser", listUser);
model.setViewName("userresults");
return model;
}
I know the SQL method is working as I have previously called it from another page.
Try this table structure for displaying your data.
<table border="1" style="width: 300px">
<tr>
<th>User name</th>
<th>Default Heading</th>
</tr>
<tr th:each="user : ${listUser}">
<td th:text="${user.username}">Default username</td>
<td>Default enabled</td>
</tr>
</table>
PS: I tested your code with the above table structure and both #GetMapping and #RequestMapping is working fine. Also make sure the listUser has atleast one User otherwise even the default won't be displayed.

How to display TABLE dynamically in JSP using SPRING MVC

I want to create a table dynamically in such a way that no of headers and data i can pass from JAVA class and on no. basis, jsp should create a table accordingly.
I have controller class in which i am returning model object which is my bean class. In that i have a list attribute in which i have hardcoded some values.These values should be by header names in the JSP table.
When i am rendering this model object to jsp then i am not able to retrieve the headers info. Plz suggest.
My contrller class loooks like this:
#RequestMapping
public ModelAndView getHeaders(PortletRequest portlestRequest, PortletResponse portletResponse){
ModelAndView mv = new ModelAndView();
TableDAO dao = new TableDAO();
List<String> headersList = dao.getHeaders();
TableView tableView = new TableView();
tableView.setTableHeaders(headersList);
mv.addObject("tableView",tableView);
mv.setView("tableView");
return mv;
}
My jsp:
<table>
<c:forEach var = "listValue" items = "${tableView.tableHeaders}">
<tr>
<%for(int i = 0;i<5;i++){ %>
<td>
<%=${listValue.get(i)} %>
</td>
<%} %>
</tr>
</c:forEach>
</table>
Someone plz help me on this.
Why are you looking over the list of headers twice? You dont need that scriptlet code.
Since tableView.tableHeaders returns a list of strings, you just need :
<table>
<tr>
<c:forEach var = "listValue" items = "${tableView.tableHeaders}">
<td>
<c:out value="${listValue}"/>
</td>
</c:forEach>
</tr>
</table>

Java EE and struts and JSP: java form population - action bean etc

HI everyone.
ISSUE-
Error populating nl.strohalm.cyclos.controls.cv.CvUploadForm#317bdd in /member/cvUpload
javax.servlet.ServletException: BeanUtils.populate
I am working on a opensource wep app, and trying to teach my self some skills by adding new functionality.
Now The web app is called cyclos and uses - Java EE, Struts, Hibernate, JSP, Tiles-def (spring, MySql JavaScript) SETUP: controls, DAO's, services, entities etc.
I am trying to add new functionality such as a CV database for users to save a template and file.
My sample JSP form looks as follows:
<ssl:form method="post" action="/member/cvUpload" enctype="multipart/form-data">
<html:hidden property="id" />
<html:hidden property="owner" />
<html:hidden property="uploadDate" />
<table class="defaultTableContent" cellspacing="0" cellpadding="0">
<tr>
<td class="tdHeaderTable">TITLE HERE PLEASE !!!></td>
</tr>
<tr>
<td colspan="2" align="left" class="tdContentTableLists">
<table class="defaultTable">
<tr>
<th class="tdHeaderContents" width="30%"> CV Upload -> needs properties copy / ref !!!</th>
<th class="tdHeaderContents" width="60%"> </th>
</tr>
<tr>
<td>Notes </td>
<td><cyclos:richTextArea name="notes" styleId="descriptionText"/></td>
</tr>
<tr>
<td>Address</td>
<td><html:text value="address" size="25" property="address" /><br>
<html:text value="address" size="25" property="address2" />
<html:text value="address" size="25" property="address3" />
</td>
</tr>
<tr>
<td>Phone Number</td>
<td><html:text value="0791 000 000" size="15" property="phoneNumber"/></td>
</tr>
<tr>
<td>Field of interest / industry</td>
<td><c:forEach var="industry" items="${industries}">
<label>
<html:radio property="industry" value="${industry}" styleClass="radio" /><bean:message key="cv.industries.${industry}" />
</label>
</c:forEach>
</td>
</tr>
<tr>
<td>CV upload</td>
<td><html:file property="cvContent" /></td>
</tr>
<tr>
<td>
<input type="submit" id="saveButton" value="<bean:message key="global.submit"/>" align="center">
</td>
</tr>
</table>
</td>
</tr>
</table>
And my java form populated by struts or how ever looks as follows:
public class CvUploadForm extends BaseBindingForm {
private Long id;
#IndexedEmbedded(depth = 4)
private Member owner;
// private Calendar creationDate;
// private Member memberId;
private FormFile cvContent;
private Calendar uploadDate;
private long memberId;
public CvUploadForm() {
}
public CvUploadForm(Long id, Member owner, FormFile cvContent, Calendar uploadDate) {
this.id = id;
this.owner = owner;
this.cvContent = cvContent;
this.uploadDate = uploadDate;
}
public Map<String, Object> getCv() {
return values;
}
public void setCv(final Map<String, Object> map) {
values = map;
}
public void setCv(final String key, final Object value) {
values.put(key, value);
}
// ++ GETTERS AND SETTERS ++
// =============================================
Now I can display my template, but my submit wont work -> and i would like to understand the issue / error shown im my output window !! (see at top and following error )
the next error shown is as follows :
Caused by: java.lang.IllegalArgumentException: Cannot invoke nl.strohalm.cyclos.controls.cv.CvUploadForm.setOwner - argument type mismatch
Plus couple more errors. (owner ov cv refers to different member table as ID - uses java enum - relationships... fetch
I am very grateful for any reply ! And mybe some clarification about the setup. I thought I onlu use the form to display bits on JSP, and the use the CV.java entity file for the maaping etc . . so I am a little lost on getting all files and the connection right as wel las understanding the error here
Thanks for any reply, if you need additional info pls let me know.
Alex
You have to see what is the type of object it attempts to pass to the setOwner method. It is not an object of type Member.
Use your debugger and try to see what is trying to pass.
you should precise if it's Struts 1 or struts 2.
struts 1 maps proprities to actionForm ,if it's the case you should use primitive types in form action ( not objects like member) .
Struts 2 uses OGNL to map complex object to their specific bean.
this my first post on stack over flow , i hope that it khelps you.

Categories