I have a list of objects and I want to display the values of those objects in a table using thymeleaf, this is what I have so far:
Here is my controller class that adds my list of objects:
#RequestMapping(value = "/showTableWithValues", method = RequestMethod.GET)
public String showTableWithValues(Model model)
{
//list with Persons
ArrayList<Persons> personsList=
new ArrayList<Persons>();
personsList= this.getListOfPersons();
model.addAttribute("list", personsList);
return "showTableWithValues";
}
This is my .html file where i want to show my values:
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
</head>
<body>
<h1>
Show Values
</h1>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Cost</th>
<th>Mins to prepare</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr th:each="persons : ${list}">
</tr>
</tbody>
</table>
</body>
</html>
And my Person.java class:
public class Person {
private String name;
private String last_name;
private String nickname;
.....get,setters and constructor
}
You are missing your <TD> tags providing the template which fields to print where. See the Iteration Basics of the documentation
Add <td> tags under <th> and then use the <td th:text="${persons.ID}"></td> respectively to display the relevant data in the table.
Related
I'm working on a problem where I have a program to manage course. I have to create a lesson with a teacher & student, although when I have added a lesson to the DB & want it to show up on the frontend website, although it's not happening.
Student & Teacher are working fine, after adding a new Student/Teacher it redirects to the main page & the new list is available.
Data is visible in SQL Workbench & I can see the records adding.
Could you advise why the list is not showing up in front end?
LessonController class:
#Controller
#RequiredArgsConstructor
#RequestMapping("/lessons")
public class LessonController {
private final LessonService lessonService;
private final TeacherService teacherService;
private final StudentService studentService;
#GetMapping
public String getLessonList(Model model){
model.addAttribute("lessons",lessonService.findAll());
return "lesson/list";
}
#GetMapping("/create")
public String getLessonCreateForm(Model model){
model.addAttribute("teachers", teacherService.findAll());
model.addAttribute("students", studentService.findAll());
return "lesson/form";
}
#PostMapping("/create")
public String createLesson(Lesson lesson,
#RequestParam("studentId") int studentId,
#RequestParam("teacherId") int teacherId) {
lessonService.save(lesson,studentId,teacherId);
return "redirect:/lessons";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Lekcje</title>
</head>
<body>
<h1>Lekcje</h1>
</br>
<p2>dodaj</p2>
</br>
</br>
<table>
<thead>
<tr>
<th>ID</th>
<th>Student</th>
<th>Nauczyciel</th>
</tr>
</thead>
<tbody>
<tr th:each="lesson : ${lesson}">
<td th:text="${lesson.id}"></td>
<td th:text="${student.firstName} + ' ' + ${student.lastName}"></td>
<td th:text="${teacher.firstName} + ' ' + ${teacher.lastName}"></td>
</tr>
</tbody>
</table>
</body>
</html>
This is the desired output for the lessons front end is to display the lessons from the DB. Here is a screenshot of the students front end:
Try to add URL to #GetMapping annotation above getLessonList method, I believe it should be #GetMapping("lesson/list") or #GetMapping("lessons")
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->
<!DOCTYPE html>
<html>
<head>
<title>Mail Registration</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="newcss.css">
<link rel="text/javascript" href="validateForm.js">
</head>
<body>
<div id="container">
<div id="header">
<h1>Online Book Store Mailing Registration</h1>
</div>
<div id="content">
<div id ="leftSide">
<p>Welcome to the Online Book Store Registration.
In order to join our mailing list you must complete the form. Then press the Submit button.</p>
</div>
<div id="rightSide">
<h2>Thanks for joining our email list</h2>
<h3>Here is the information that you entered:</h3>
<%# page import="user.User" %>
<% User user = (User) request.getAttribute("User");%>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<th align="right">First Name:</th>
<th>${user.getFirstName}</th>
</tr>
<tr>
<th align="right">Last Name:</th>
<th>${user.getLastName}</th>
</tr>
<tr>
<th align="right">Town:</th>
<th>${user.getTown}</th>
</tr>
<tr>
<th align="right">Country:</th>
<th>${user.getCountry}</th>
</tr>
<tr>
<th align="right">Email Address:</th>
<th>${user.getEmailAddress}</th>
</tr>
</table>
</form>
<br />
</div>
</div>
<div id="footer">
<h2>xxx</h2>
</div>
</div>
</body>
</html>
This is my first time working with JSP, I have to display user details that have been added to database. I have been looking for some time now at other questions asked here about displaying details and I have not found an answer yet.
I have java class called User.java in user Package.
If anyone could point me where I went wrong I would be thankful.
I have this in my servlet
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String town = request.getParameter("town");
String country = request.getParameter("country");
String emailAddress = request.getParameter("emailAddress");
// create the User object
User User = new User();
User.setFirstName(firstName);
User.setLastName(lastName);
User.setTown(town);
User.setCountry(country);
User.setEmailAddress(emailAddress);
MailDB.insert(User);
request.setAttribute("User", User);
String url = "/return_user_details.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
dispatcher.forward(request, response);
I suppose that your User class is like this :
Class User {
private String firstName;
private String lastName;
private String country;
.
.
.
/*generating getters & setters*/
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
}
So the problem you're having is here ${user.getFirstName} this will never work unless your attribute is named getFirstName which I don't think you did so to solve this issue you simply have to :
replace
${user.getFirstName} with ${user.firstName} , generally use the attribute name and not the getters and setters methods name.
i have problem with display data on jsp page from using jstl.
This is my page, and displayed information:
EMPTY !!!
Name Email Action
get-user.jsp
<html>
<head>
<title>All users</title>
</head>
<body>
<c:if test="${empty webModels}">
<h3>EMPTY !!!</h3>
</c:if>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${webModels}" var="web">
<tr>
<td>${web.userName}</td>
<td>${web.userEmail}</td>
<td>${web.Action}</td>
</tr>
</c:forEach>
</tbody>
</table>
</body>
</html>
controller print information size 4
#RequestMapping(value = "/get-user", method = RequestMethod.GET)
public List<WebModel> getWebModels(){
List<WebModel> webModels = serviceWeb.getAllUser();
System.out.println(webModels.size()); //not empty
return webModels;
}
WebModel i getting data from database from a few table and main data i set in WebModel
public class WebModel {
private String userName;
private String userEmail;
private String Action;
//getter setter constructor
}
The documentation about return types of controller methods says:
Any other return type is considered to be a single model attribute to be exposed to the view, using the attribute name specified through #ModelAttribute at the method level (or the default attribute name based on the return type class name). The model is implicitly enriched with command objects and the results of #ModelAttribute annotated reference data accessor methods.
So, if I read it correctly, you should use list instead of webModels in your JSP, or you should annotate the method with
#ModelAttribute("webModels")
I'm trying to submit selected items from a table and moake some modifications on them but I couldn't get it work.
MyObject.java
public class MyObject{
boolean checkControl = true; //default true
private String name;
private String code;
//getters & setters
}
MyObjectForm.java
public class MyObjectForm {
private List<MyObject> myList;
public List<MyObject> getMyList() {
return myList;
}
public void setMyList(List<MyObject> myList) {
this.myList= myList;
}
}
list-myObjects.jsp
<form:form action="submitList" method="post" modelAttribute="myObjectForm">
<table>
<tbody>
<c:forEach items="${myObjectForm.myList}" var="row" varStatus="status">
<tr>
<td>
<spring:bind path="myList[${status.index}].checkControl">
<input type="checkbox" value="<c:out value="${status.value}"/>" name="isChecked" <c:if test="${row.checkControl}"> checked="checked" </c:if> />
</spring:bind>
</td>
<td>${row.name}</td>
<td>${row.code}</td>
</tr>
</c:forEach>
</tbody>
</table>
<button type="submit">Submit</button>
</form:form>
And the controller
#RequestMapping(value = "/submitList", method = RequestMethod.POST)
public String save(#ModelAttribute("myObjectForm") MyObjectForm myObjectForm, Model model) {
List<MyObject> selectedtList = myObjectForm.getMyList(); //returns null
if (selectedtList == null) {
System.out.println("no objects selected");
}
else {
//Make some computation
}
model.addAttribute("resultArray", selectedtList);
return "display-items";
}
Some users asked me to explain this in more detail by email. So I decided to submit it here, Hope this helps.
I'm using spring annotations, to do the job. here is what I did to process selected checkboxes,
I have a java entity class which includes a boolean value for the checkbox, for example a Person class
// Person.java
class Person {
private Long id;
private String name;
private boolean check;
//here goes getters and setters
}
than I have a form object in java, which contains a list of Person
//PersonForm.java
class PersonForm {
private List<Person> personList;
//getters and setters here
}
in my case, there are two jsp pages, the first one lists items, with checkboxes, and the second one lists selected items.
the first jsp file is list.jsp
//list.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="datatables" uri="http://github.com/dandelion/datatables"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
....
<body>
<form:form action="sent-list" method="post" modelAttribute="personForm">
<table id="item-list" class="table table-striped table-bordered">
<thead class="dataTableHeader">
<tr>
<th width="10%" style="text-align:center">
CheckBox
</th>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<c:forEach items="${personForm.personList}" var="listItem" varStatus="status">
<tr>
<td style="text-align:center">
<form:checkbox path="listItem[${status.index}].check"/>
</td>
<td>${listItem.id} <form:hidden path="listItem[${status.index}].id"/></td>
<td>${listItem.name} <form:hidden path="listItem[${status.index}].name"/></td>
</tr>
</c:forEach>
</tbody>
</table>
<button class="btn btn-large btn-success pull-right" type="submit">POST</button>
</form:form>
</body>
</html>
the second jsp file is as follows
//sent-list.jsp
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# taglib prefix="datatables" uri="http://github.com/dandelion/datatables"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
.....
<body>
<form:form action="#" method="post" modelAttribute="personForm">
<table id="item-list" class="table table-striped table-bordered">
<thead class="dataTableHeader">
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
<tbody>
<c:forEach items="${resultList}" var="personItem" varStatus="status">
<tr>
<td>${personItem.id}</td>
<td>${personItem.name}</td>
</tr>
</c:forEach>
</tbody>
</table>
</form:form>
</body>
</html>
and finally there is a controller, which makes the computation
//PersonController.java
#Controller
class PersonController {
#RequestMapping(value = "/sent-list", method = RequestMethod.POST)
public String save(#ModelAttribute("personForm") PersonForm personForm, Model model){
for(Person personItem : personForm.getPersonList){
//make some computation here
}
}
}
I hope this helps.
Sounds like a binding issue. Have you tried using Spring's <form:checkbox> tag rather than <spring:bind>? It will automatically generate the checkbox attributes as well as adding a hidden field that Spring uses to determine whether the checkbox is 'on' or 'off'.
<form:form action="submitList" method="post" modelAttribute="myObjectForm">
<table>
<tbody>
<c:forEach items="${myObjectForm.myList}" var="row" varStatus="status">
<tr>
<td>
<form:checkbox path="myList[${status.index}].checkControl"/>
</td>
<td>${row.name}</td>
<td>${row.code}</td>
</tr>
</c:forEach>
</tbody>
</table>
<button type="submit">Submit</button>
</form:form>
I am studying Spring MVC, and I have a problem with understanding how to use my classes in jsp, here is my controller:
#Controller
public class BusinessController {
#Autowired
private BusinessService businessService;
#RequestMapping("/index")
public String listContacts(Map<String, Object> map) {
map.put("business", new Business());
map.put("businessList", businessService.listBusiness());
return "business";
}
#RequestMapping("/find/{businessDate}")
public String listContactsByDate(#PathVariable("businessDate") Map<String, Object> map, String businessDate) {
map.put("businessByDate", new Business());
map.put("businessByDateList", businessService.listBusinessByDate(businessDate));
return "businessByDate";
}
#RequestMapping("/")
public String home() {
return "redirect:/index";
}
#RequestMapping(value = "/add", method = RequestMethod.POST)
public String addBusiness(#ModelAttribute("business") Business business, BindingResult result) {
businessService.addBusiness(business);
return "redirect:/index";
}
#RequestMapping("/delete/{businessId}")
public String deleteBusiness(#PathVariable("businessId") Integer businessId) {
businessService.removeBusiness(businessId);
return "redirect:/index";
}
}
And here is my jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<title><spring:message code="label.title" /></title>
</head>
<body>
<h2>
<spring:message code="label.title" />
</h2>
<form:form method="post" action="add" commandName="business">
<table>
<tr>
<td><form:label path="businessDate">
<spring:message code="label.date" />
</form:label></td>
<td><form:input path="businessDate" /></td>
</tr>
<tr>
<td><form:label path="description">
<spring:message code="label.description" />
</form:label></td>
<td><form:input path="description" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="<spring:message code="label.addbusiness"/>" /></td>
</tr>
</table>
</form:form>
<form:form method="post" action="/find/{$businessDate}"
commandName="businessByDate">
<table>
<tr>
<td><form:label path="businessDate">
<spring:message code="label.date" />
</form:label></td>
<td><form:input path="businessDate" /></td>
</tr>
</table>
<c:if test="${!empty businessByDateList}">
<table class="data">
<tr>
<th><spring:message code="label.date" /></th>
<th><spring:message code="label.description" /></th>
<th> </th>
</tr>
<c:forEach items="${businessByDate}" var="business">
<tr>
<td>${businessByDate.businessDate}</td>
<td>${businessByDate.description}</td>
<td><a href="delete/${businessByDate.id}"><spring:message
code="label.delete" /></a></td>
</tr>
</c:forEach>
</table>
</c:if>
</form:form>
<h3>
<spring:message code="label.businesses" />
</h3>
<c:if test="${!empty businessList}">
<table class="data">
<tr>
<th><spring:message code="label.date" /></th>
<th><spring:message code="label.description" /></th>
<th> </th>
</tr>
<c:forEach items="${businessList}" var="business">
<tr>
<td>${business.businessDate}</td>
<td>${business.description}</td>
<td><a href="delete/${business.id}"><spring:message
code="label.delete" /></a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
And, here is my service implementation class:
#Repository
public class BusinessDAOImpl implements BusinessDAO{
#Autowired
private SessionFactory sessionFactory;
public void addBusiness(Business business){
sessionFactory.getCurrentSession().save(business);
}
#SuppressWarnings("unchecked")
public List<Business> listBusinessByDate(String businessDate){
String hql = "from Business B where B.date = :business_date";
Query query = sessionFactory.getCurrentSession().createQuery(hql);
query.setParameter("business_date", businessDate);
return query.list();
}
#SuppressWarnings("unchecked")
public List<Business> listBusiness(){
return sessionFactory.getCurrentSession().createQuery("from Business").list();
}
public void removeBusiness(Integer id){
Business business = (Business) sessionFactory.getCurrentSession().load(
Business.class, id);
if (null != business) {
sessionFactory.getCurrentSession().delete(business);
}
}
}
Without the part of jsp, where I try to list businesses for date everything works fine, I can add a business and it will be immediately listed in a table below, but if I add a part with businessByDate I'll get
Neither BindingResult nor plain target object for bean name 'businessByDate' available as request attribute
How can I solve that? Thank you
enter code here
That's coming out of this form tag:
<form:form method="post" action="/find/{$businessDate}"
commandName="businessByDate">
It looks like you only do:
map.put("businessByDate", new Business());
In the method that is this form's action. You need to add that object to the map in the method that actually loads the page!