If you want to debug and see all data from array/list in Spring Boot, here are the best ways.
Suppose:
List<Student> students = service.getAllStudent();
1. Print Using forEach (Best)
students.forEach(System.out::println);
But for this your Student class needs toString().
2. Add toString() in Entity
In Student.java
@Override
public String toString() {
return "Student [id=" + id +
", firstName=" + firstName +
", lastName=" + lastName +
", email=" + Email + "]";
}
public String toString() {
return "Student [id=" + id +
", firstName=" + firstName +
", lastName=" + lastName +
", email=" + Email + "]";
}
Now console output:
Student [id=1, firstName=Lakhan, lastName=Thakur, email=test@gmail.com]
3. Traditional Loop
for(Student s : students){
System.out.println(s);
}
System.out.println(s);
}
4. Print Specific Values
for(Student s : students){
System.out.println(s.getFirstName());
System.out.println(s.getEmail());
}
System.out.println(s.getFirstName());
System.out.println(s.getEmail());
}
5. Debug in Controller
@GetMapping("/index")
public String getAllStudent(Model model) {
List<Student> students = service.getAllStudent();
students.forEach(System.out::println);
model.addAttribute("students", students);
return "studentPage";
}
public String getAllStudent(Model model) {
List<Student> students = service.getAllStudent();
students.forEach(System.out::println);
model.addAttribute("students", students);
return "studentPage";
}
6. See Data in IntelliJ/Eclipse Debugger
Add breakpoint
Click left side line number.
Example:
List<Student> students = service.getAllStudent();
Run Debug Mode
- Eclipse → Debug As → Spring Boot App
- IntelliJ → Debug button
Inspect Array/List
Hover mouse on:
students
You can expand all objects.
7. Convert List to JSON (Very Useful)
System.out.println(new ObjectMapper().writeValueAsString(students));
Import:
import com.fasterxml.jackson.databind.ObjectMapper;
Output:
[
{
"id":1,
"firstName":"Lakhan",
"lastName":"Thakur",
"email":"test@gmail.com"
}
]
{
"id":1,
"firstName":"Lakhan",
"lastName":"Thakur",
"email":"test@gmail.com"
}
]
8. Print Size
System.out.println(students.size());
9. Debug Thymeleaf Data
Inside HTML:
<p th:text="${students}"></p>
or
<p th:text="${studentData.firstName}"></p>
inside th:each.
No comments:
Post a Comment
If you have any problem please let me know.