I have read other posts on this but I still dont get it. I have this class:
import java.util.List;
import javax.annotation.ManagedBean;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
@ManagedBean
@RequestScoped
public class ManagedBean{
private UserService userService;
@Inject
public void setUserService(UserService userService) {
this.userService = userService;
}
private User user;
private List<User> list;
public ManagedBean() {
}
@PostConstruct
public void init() {
user = userService.returnUserById(1);
list = userService.returnAllUsers();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getList() {
return list;
}
public void setList(List<User> list) {
this.list = list;
}
}
And then this class:
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
@Named
@SessionScoped
public class TestBean implements Serializable {
private static final long serialVersionUID = 1L;
private int num = 6;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num ;
}
public void setNum(int num) {
this.num = num;
}
}
And then this .xhtml page:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head />
<h:body>
TEST
Welcome #{testBean.num}
<h:form>
<h:inputText value="#{testBean.name}"></h:inputText>
<h:commandButton value="Welcome Me" action="xhtml/second"></h:commandButton>
</h:form>
<h3>Return All Users</h3>
<h:dataTable value="#{homeManagedBean.list}" var="user">
<h:column>
<h:outputText
value="User Id= #{user.userId} + User Name = #{user.userName}" />
</h:column>
</h:dataTable>
<h3>Return User By Id 2</h3>
<h:outputText value="User Id #{homeManagedBean.user.userId}" />
<h:outputText value="User Name #{homeManagedBean.user.userId}" />
</h:body>
</html>
When I change the @ManagedBean to @Named in the first class, I get the following error from glassfish:
WELD-000049 Unable to invoke public void a.ManagedBean.init() on a.ManagedBean@3b26b9ca
And when I change the @Named to @ManagedBean in the second class, I can call the page in the browser, but when I click on "Welcome me", I get the following error:
/index.xhtml @16,41 value="#{testBean.name}": Target Unreachable, identifier 'testBean' resolved to null
When do I use which annotation??
Thanks for help!