Answer the question
In order to leave comments, you need to log in
How to pass objects from server to JSP?
Suppose the servlet takes data from the database via JDBC (I'm not touching the ORM yet). This data is passed to objects that process it somehow. Then you need to somehow display the results on a JSP page. As far as I know, the only way to do this is request.setAttribute(name, object) and then use them on the page via EL expressions.
For example, there is a User class, with id and nickname fields. It is necessary to issue information about 5 users.
a) Attach exactly the internal objects that perform the logic?
b) Create special classes (of type UserData) that will be passed to the JSP and attach them?
c) Just send 2 List'a, in one - all id's, and in the other - all names?
d) Send Map(Integer, String)? I met the statement that only Lists need to be sent to JSP.
Answer the question
In order to leave comments, you need to log in
If you want the container to manage the life cycle of objects, you must use the directive
details here
However, no one bothers to create the necessary objects in the scriptlet inside the jsp page and output the values of their attributes / methods to the output stream of the servlet (jsp page), although in the general case this is not desirable.
In this case, I would recommend creating a separate class for accessing your objects, say UserDAO, which would receive data from the database and create instances of your User class. In the most trivial case, UserDAO will contain a single method, say list, which returns a list of all objects for which there are corresponding records in the database, something like
/**
*
* @return Список объектов User данные для которых имеются в БД
*/
public List<User> list()
{
List<User> result = new ArrayList<User>();
try // <-- вообще так делать не очень хорошо, но тут я просто избавил себя от лишней писанины
{
/*
* Структуру Вашей БД я не знаю, поэтому
* тупо выбираю значения колонок id и nickname
* из таблицы tbl_user.
* Если у Вас все организовано иначе, вставте свой SQL запрос.
*/
PreparedStatement statement = connection.prepareStatement(
"select id, nickname from tbl_user");
ResultSet r_set = statement.executeQuery();
/*
* Бежим по результирующей выборке и инициализируем объекты типа User,
* попутно добавляя их в список.
*/
while (r_set.next())
{
// предполагается, что у User имеется соответствующий конструктор
User p = new User(r_set.getString("id"), r_set.getString("nickname"));
result.add(p);
}
} catch (Exception e)
{
e.printStackTrace();
}
return result;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question