ZZ 5
ZZ 5

Reputation: 1964

PostConstruct is called twice

I use,

I've noticed that my beans invoke @PostConstruct's init() method twice. Here's sample bean that got initialized twice, if you'll need web.xml or anything else, just post it - I ran out of ideas.

@ManagedBean(name = "userBean")
public class UserBean implements Serializable {

    private static final long serialVersionUID = -1347081883455053542L;
    @ManagedProperty(value = "#{param.username}")
    private String username;
    private Users user;
    private Authentication authentication;
    private StreamedContent avatar;

    @PostConstruct
    public void init() {
        System.out.println("userbean init and username: " + username);
        user = Users.findByUsername(username);
        authentication = SecurityContextHolder.getContext()
                .getAuthentication();
        if (user == null) {
            Navigator.redirect("/601");
            return;
        }
        if (user.isKeepPrivate() == true && !username.equals(authentication.getName())) {
            Navigator.redirect("/600");
            return;
        }
        avatar = new DefaultStreamedContent(UserUtils.getAvatar(user), "image/png");
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public StreamedContent getAvatar() {
        return avatar;
    }

    public void setAvatar(StreamedContent avatar) {
        this.avatar = avatar;
    }
}

Upvotes: 1

Views: 6217

Answers (1)

xild
xild

Reputation: 187

we have this problem here, but is a problem with WebSphere 6. (runaway from websphere :D)

So... we do a little workaround to use @PostConstruct...
Maybe can help you...

public boolean firstInit() {
    boolean firstInit= false;
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            firstInit= context != null  && context.getExternalContext().getRequestParameterMap().containsKey(ResponseStateManager.VIEW_STATE_PARAM);
        } catch (Exception e) {
            firstInit= false;
        }
        return firstInit;
    }
public void init(){
if (firstInit()) return;
//init methods
}

And @PostConstruct method called twice for the same request this can help you too...

obs: i cant write comments :/

Upvotes: 2

Related Questions