Search code examples
jsfjsf-2cdishopping-cart

Doing something whenever user exits particular page


I have a internet shop application. I wanted to improve "removing from the cart" feature. I don't want to ask an user if he wants to "really remove" the position from the cart, instead I'd like to allow him cancel the operation.

Currently when user clicks "X" button at the product in the cart, row of table changes to "removed, click to cancel". In the back there is a list of CartPosition objects every with flag removed. Removed product is still on list, but the flag is set to true. It makes product still visible in proper position on the list, but on the view side I can render it another way. When user clicks another "X", previous one is premamently removed from the list and new one is marked as removed.

Shopping cart is session scoped CDI bean. It means, when I mark some position removed and go somewhere else, then go back to the cart, I'll still have one row marked as removed. I just don't want this.

I thought about changing the bean to JSF one, then create another view scoped which could keep record marked as removed and check if it's empty, if so I could remove the one from list. I have no idea if it's going to work. I'll try this approach, but I'd rather keep my beans managed by CDI.

Is there a way to handle this without implementing my above idea?

EDIT: @BalusC, your assumptions are wrong. You should rather suppose, that I don't exactly know how can I mix CDI and JSF. I actually use JSF 2.2, what means that javax.faces.view.ViewScoped annotation is available for me. Anyway I still don't understand the idea. I understood, that I have to rely on some ViewScoped bean. It's clear, but how it has to be composed. Can you explain your idea? I tried few things, but it looked it didn't work correctly. For example my @PreDestroy method of ViewScoped bean was never called and it's constructed lazily only when I try to use it.


Solution

  • Do the actual remove job in @PreDestroy annotated method of the session or view scoped bean.

    @PreDestroy
    public void destroy() {
        // Do the actual remove job here.
    }
    

    Given that your question implies that you don't have CDI based javax.faces.view.ViewScoped available, which is new since JSF 2.2, this in turn suggests that you're still on JSF 2.0/2.1 and thus only have JSF based javax.faces.bean.ViewScoped at hands, then it should be noted that its @PreDestroy is broken in several circumstances. You'd then best do the @PreDestroy in the CDI based @SessionScoped bean. Alternatively, you could use OmniFaces @ViewScoped which has fixed and improved the @PreDestroy of a @ViewScoped bean in several ways. It even gets invoked on window unload.