Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@SessionScoped does not work when adding @Named

Consider the following backing bean:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class Counter {

    int counter;

    public Counter() {
        this.counter = 0;
    }

    public void Increment() {
        this.counter++;
    }

    public void Decrement() {
        this.counter--;
    }

    public int getCounter() {
        return this.counter;
    }

}

I have created a JSF-page that displays the value of the counter and has two buttons to increment and decrement it. It works as expected. However, when I add the annotation javax.inject.Named to the bean, it does not seem to have session scope anymore. The buttons still work (the click is handled on the server-side), but the value of the counter always remains zero. I am using the annotation because in my real application I need to inject other beans into this one, and this annotation seems to be required (please correct me if I am wrong). What is the reason for this behavior? What can I do to work around it?

like image 956
Björn Pollex Avatar asked Feb 23 '26 03:02

Björn Pollex


1 Answers

You cannot mix JSF with CDI annotations. Use the one or the other. In this case, you need to import javax.enterprise.context.SessionScoped instead of javax.faces.bean.SessionScoped.

like image 145
BalusC Avatar answered Feb 24 '26 16:02

BalusC