Passing instance variable between managed beans - jsf

I am trying to get the UserBeans instance variables from LoginBean class. I want to use instance variable of Userbean into LoginBean class. Someone helps me.
Here, UserBean.java class :
#ManagedBean
#SessionScoped
public class UserBean {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And, Here's LoginBean.java class :
public class LoginBean {
public String login_check() {
if(name.equals("mahbub")){
return "success";
}else
return "fail";
}

Inject your UserBean class into LoginBean class and generate its getter and setter. So, your code should look like this.
public class LoginBean {
#ManagedProperty(value = "#{userBean}")
private UserBean userBean;
public String login_check() {
if(name.equals("mahbub")) {
return "success";
} else {
return "fail";
}
}
// userBean getter and setter here
}
Hope this would work for you. Cheers!

Use something like this
public class LoginBean {
#ManagedProperty(value = "#{userBean}")
private UserBean userBean;
public String login_check() {
if(userBean.getName().equals("mahbub")){
return "success";
}else
return "fail";
}
}
But you should rethink your design pattern

Related

Set value to ManagedProperty

I'm trying to set a value to my ManagedProperty but I'm getting the null result when I try to print this.
I'd like to set the Bean Class to use it in my query.
I've been tryin' set String, Class, but all the times it returned a null value.
Can anyone help me?
#ManagedBean
public class FilialBean extends BaseBean implements Serializable{
private Filial filial;
private List<Filial> filiais;
#ManagedProperty("#{entidadeService}")
private EntidadeService service;
#PostConstruct
public void init(){
service.setFaces(Filial.class);
filial = new Filial();
filiais = (List<Filial>) (List) service.getbasesEntidades();
}
//GETTERS AND SETTERS
}
#ManagedBean(name="entidadeService", eager=true)
#ApplicationScoped
public class EntidadeService implements Serializable{
private List<EntidadeBase> basesEntidades;
private Class faces;
#PostConstruct
public void init(){
System.out.println(faces.getSimpleName());
try{
EntityManager manager = JPAUtil.getEntityManager();
Query query = manager.createQuery("SELECT e FROM Filial e WHERE e.ativo = :ativo");
query.setParameter("ativo", true);
this.basesEntidades = query.getResultList();
}
catch(Exception e){
e.printStackTrace();
}
}
public List<EntidadeBase> getbasesEntidades() {
return basesEntidades;
}
public Class getFaces() {
return faces;
}
public void setFaces(Class faces) {
this.faces = faces;
}
}
Have you check that #ManagedBean has same package in both classes?
I ran into same problem, a property with null value executing Post Construct method and this is the problem, one class had javax.annotation.ManagedBean (CDI) annotation and the other had javax.faces.bean.ManagedBean (JSF) annotation.
In my case I needed both classes with JSF annotations...

Injecting beans in JSF

I have a Session scoped bean
#ManagedBean(name = "ficheCultureActionController")
#SessionScoped
public class FicheCultureActionController implements Serializable {}
I want to injected in two other beans.
#ManagedBean(name = "semenceActionController")
#ViewScoped
public class SemenceActionController implements Serializable {
#ManagedProperty(value = "#{ficheCultureActionController}")
private FicheCultureActionController ficheCultureActionController;
public FicheCultureActionController getFicheCultureActionController() {
return ficheCultureActionController;
}
public void setFicheCultureActionController(FicheCultureActionController ficheCultureActionController) {
this.ficheCultureActionController = ficheCultureActionController;
}
public List<SemenceAction> getListSemenceParFicheCulture() {
if (ficheCultureActionController.getSelected() != null) {
listSemenceParFicheCulture = getFacade().getSemenceParFicheCulture();
}
return listSemenceParFicheCulture;
}
}
and
#ManagedBean(name = "engraisActionController")
#ViewScoped
public class EngraisActionController implements Serializable {
#ManagedProperty(value = "#{ficheCultureActionController}")
private FicheCultureActionController ficheCultureActionController;
public FicheCultureActionController getFicheCultureActionController() {
return ficheCultureActionController;
}
public void setFicheCultureActionController(FicheCultureActionController ficheCultureActionController) {
this.ficheCultureActionController = ficheCultureActionController;
}
}
but the property returns null in the method getListSemenceParFicheCulture().

Access Session Bean Property/Inject Session Bean

Still learning JSF and Java and having trouble understanding how to access a session bean property.
I have a LoggedUser session bean which sets the user that is logged in(using the login method).
#ManagedBean(name="loggedUser")
#Stateless
#LocalBean
#SessionScoped
public class LoggedUser {
#EJB
UserEJB userEJB;
#PersistenceContext
private EntityManager em;
private UserEntity loggedUser;
private String loginUserName;
private String loginPassword;
public LoggedUser() {}
public UserEntity getLoggedUser() {
return loggedUser;
}
public void setLoggedUser(UserEntity loggedUser) {
this.loggedUser = loggedUser;
}
public String authenticate() {
if (loggedUser == null) {
return "login.xhtml";
} else {
return "";
}
}
public String login() {
if (userEJB.validateLogin(loginUserName, loginPassword)) {
setLoggedUser(userEJB.fetchUser(loginUserName));
return "index.xhtml";
}
return "";
}
public String getLoginUserName() {
return loginUserName;
}
public void setLoginUserName(String loginUserName) {
this.loginUserName = loginUserName;
}
public String getLoginPassword() {
return loginPassword;
}
public void setLoginPassword(String loginPassword) {
this.loginPassword = loginPassword;
}
}
I want to be able to view the logged user from other areas in the application. I think I am injecting it incorrectly because loggedUser is always null when I am in a different bean for example something like..
#Stateless
#LocalBean
public class HistoryEJB {
#PersistenceContext
EntityManager em;
#ManagedProperty(value = "#{loggedUser}")
private LoggedUser loggedUser;
public LoggedUser getLoggedUser() {
return loggedUser;
}
public void setLoggedUser(LoggedUser loggedUser) {
this.loggedUser = loggedUser;
}
public void testLoggedUser() {
loggedUser.getLoggedUser();
// Just an example but would be null here - why?
}
}
How can I access this property from other areas in my application? Thanks for any help.
You can't use #ManagedProperty in an EJB and you shouldn't inject a view component into a business-tier component, period. #ManagedProperty is strictly web-tier stuff and is able to inject only and into web-tier, JSF components.
Your EJB ought to have a method that accepts a LoggedUser. This way, you can then pass your logged-in user to the EJB (which is the proper flow of data in a web application). What you have now is just turning best practice on its head.
So
Add a provideLoggedUser(LoggedUser loggedUser) method to your EJB
Call that method on your instance of UserEJB from within your managed bean
Rule of Thumb: Your EJB should not be aware of the web application
It seems you are missing the setter and getter for loggedUser. In principe it is there but it is convention to name it as follows
setProperty
and
setProperty
for a field named property. Note the capital first letter of the field name in the setter and getter!

How to use CDI and Dependency Injection

I want to use the same object "User" within the Farma and the Pata objects. The object user is first initialized inside the Farma object. I tried to annotated with #inject, but the object user inside Pata, has the name with null value. Please, can anyone help me understand what I am doing wrong? Thank!
#Named
#SessionScoped
public class Farma implements Serializable {
#Inject private User user;
#PostConstruct
public void initialize(){
user.setName("MyName");
}
// Getters and Setters
}
#Named
#SessionScoped
public class Pata implements Serializable {
#Inject private User user;
public String getFuzzyName() {
// Here I want to use the object "user" with the name "MyName" to do some logic
}
// Getters and Setters
}
public class User implements Serializable {
private String name;
// Getters and Setters
Just scoping a User object won't allow you to initialize it.
Use "producer method" to control bean's creation.
Try this:
#SessionScoped
public class Pata implements Serializable {
#Inject
#SessionUser // inject here using the producer method
private User user;
public String getFuzzyName() {
return user.getName();
}
}
#SessionScoped
public class Farma implements Serializable {
#Produces
#SessionUser // qualifier to tie injection points to this method
#SessionScoped // to ensure it will be called once per session for any number of injection points
public User produceUser() {
System.out.println("Creating user");
User u = new User();
u.setName("User");
return u;
}
}
////// that's your custom qualifier, it's in a separate file
#Qualifier
#Retention(RetentionPolicy.RUNTIME)
#Target({METHOD, FIELD, PARAMETER, TYPE})
public #interface SessionUser {}
// no scopes here, it is defined by the producer method
public class User implements Serializable {
private String name;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
You need to understand scoping of CDI beans. The default scope, if none is specified, is the #Dependent scope, which means that an object exists to serve exactly one client (bean) and has the same lifecycle as that client (bean).
In this case it means that the user in Farma only exists for the Farma class and lives for the life of the Farma class.
The user in Pata is a different instance, and its lifecycle matches that of Pata.
You need to properly scope the User object.
As axiopisty said, adding #Named #SessionScoped is the correct way.
I tried and it works great.
#Named
#SessionScoped
public class Pata implements Serializable {
#Inject
private User user;
public String getFuzzyName() {
System.out.println(user.getName());
return user.getName();
}
public User getUser() {
return user;
}
public void setUser(final User user) {
this.user = user;
}
}
#Named
#SessionScoped
public class Farma implements Serializable {
#Inject
private User user;
#PostConstruct
public void initialize() {
user.setName("MyName");
}
// Getters and Setters
public User getUser() {
return user;
}
public void setUser(final User user) {
this.user = user;
}
}
#Named
#SessionScoped
public class User implements Serializable {
private String name = "Default";
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
<h:outputText value="#{farma}"></h:outputText><br />
<h:outputText value="#{pata}"></h:outputText><br />
<h:outputText value="#{pata.fuzzyName}"></h:outputText>

JSF2 facelets and mvc

I'm trying to use mvc in my JSF2 facelets webapplication.
This is my logincontroller:
#ManagedBean
#ApplicationScoped
public class LoginControllerImpl implements LoginController{
#ManagedProperty(value = "#{applicationBean}")
private ApplicationBean applicationBean;
#Override
public boolean checkLogin(String username, String password) {
Store store = applicationBean.getStore(); //my model and my data are in this object
try {
store.checkLogin(username, password);
return true;
} catch (LoginException ex) {
return false;
}
}
}
This is my loginBean:
#ManagedBean
#SessionScoped
public class LoginBean implements Serializable{
#ManagedProperty(value="#{loginController}")
private LoginController loginController;
private String username;
private String password;
public void checkLogin(){
loginController.checkLogin(username, password);
}
}
Now I want to redirect the user to a welcome page when checklogin is true. Any ideas/tips how i should do that?
You can use implicit navigation, just return the page to which you want to access (relative to the current URL)
#ManagedBean
#SessionScoped
public class LoginBean implements Serializable{
#ManagedProperty(value="#{loginController}")
private LoginController loginController;
private String username;
private String password;
public String checkLogin(){
if (loginController.checkLogin(username, password)) {
return "welcome.xhtml";
}
return null; // won't change page
}
}

Resources