Class objects and JSP
I have a class Products, which has the attributes name, description and price.
I intend to populate products in the application scope of my project. How do I go about achieving that?
Secondly, upon populating the products, I want to be able to display each product in a table in a JSP page. Each product will have its own table, listing its name,descripti开发者_Go百科on and price and an add to cart button
I intend to populate products in the application scope of my project. How do I go about achieving that?
So you want to populate it once during webapp's lifetime? Use a ServletContextListener
.
@WebListener
public class StartupListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
List<Product> products = loadItSomehow();
event.getServletContext().setAttribute("products", products);
}
// ...
}
This way the products will be available in every servlet by
List<Product> products = (List<Product>) getServletContext().getAttribute("products");
and in every JSP by
${products}
Secondly, upon populating the products, I want to be able to display each product in a table in a JSP page. Each product will have its own table, listing its name,description and price and an add to cart button
So you want to categorize the products? Have a List<Category>
then where Category
class has a List<Product>
, or use a Map<String, List<Product>>
where the key is the category name.
As to how to display it, that's already been answered in your other question.
精彩评论