Issue
Problem
I send an array from StarConroller.java to Star.jsp page by **model.addAttribute**
StarConroller.java
List<Object> books = booksService.findAll();
model.addAttribute("books ", books);
I want to send this array of books to Star.js by clicking the "Show books" button in Star.jsp
Star.jsp
<button type="button" onclick="show(`${books}`)">Show books</button>
Star.js
function show(books) {
console.log(books);
}
Issue
When I click the "Show books" button I get the following log message instead of the book values:
[ [Ljava.lang.Object;@43395a7b, [Ljava.lang.Object;@aff89fb, [Ljava.lang.Object;@76f41bc8]
Solution
Your variable books
contains list of Object
. If you execute following line of code console.log(books);
, then Java will go to every object in that list and call toString()
method on every and each object. And Object by default returns that kind of the output which you can already see.
You should change List<Object> books = booksService.findAll();
to something more concrete, perhaps List<String> books = booksService.findAll();
?
To answer that question we should know what will be returned by your service.
You should create a DTO (Data transfer object (DTO), formerly known as value objects or VO, is a design pattern used to transfer data between software application subsystems. DTOs are often used in conjunction with data access objects to retrieve data from a database.) https://en.wikipedia.org/wiki/Data_transfer_object and use it instead of Object in your list.
Please remember to override toString method if you choose to use your own DTO, instead of String.
public class Books {
private String name;
private int length;
@Override
public String toString() {
return "Books{" +
"name='" + name + '\'' +
", length=" + length +
'}';
}
}
Answered By - nanomader