sv13
sv13

Reputation: 176

Struts Tiles, how to handle this situation correctly?

i just started to learn struts(+spring) MVC, and I could use some explanation of this situation :

i am using Struts Tiles for my presentation layer and i want to display some data from database in few tiles that with main content tile will form complete page. I can't figure out proper way of doing this, that fits mvc pattern/best practices.

The content of those tiles is fetched form database, its not based on user input, e.g. tile that lists few latests products added to shop etc.

What i did: i have created class 'A' with static method that queries database and returns list of few latests products, and in jsp of this tile i have just put scriptlet like:
<% for each item in A.GetLastestProducts(); dispaly data %>

but i have been told thats bad way of doing this

Can someone explain me how to handle this situation properly, like "create class that will query your database, than create blach that will blach blach, then in your tile jsp blach blach"

thanks

Upvotes: 0

Views: 300

Answers (1)

Russell Shingleton
Russell Shingleton

Reputation: 3196

If you're using struts, I would suggest leveraging the struts architecture for your JSP. I would probably structure it similar to this:

public class MyStutsAction extends ActionSupport implements preparable{

    private List<MyNewProducts> newProducts;

    @Override
    public void prepare() throws Exception {
        if(products == null){
            products = MyNewProductsDAO.getProductList();
        }
    }

    //Struts action stuff

    public List<MyNewProducts> getNewProducts(){
        return newProducts;
    }

    public setNewProducts(List<MyNewProducts> newProdcuts){
        this.newProducts = newProducts;
    }

}

Then from your JSP page you would access it as such:

<s:iterator value="newProducts" status="stat">
    <div> <s:property value="%{attributeName}" /> </div>
</s:iterator>

This will eliminate some unnecessary database calls by maintaining your list of products in the value stack and the conditional in the prepare method will populate the list if for some reason it is null.

Upvotes: 1

Related Questions