JSF Bean attribute from other bean - jsf

I try to bring the property of one ManagedBean (SessionScoped) (loginBean) to another (RequestScoped) ManagedBean (newsBean):
<c:set value="#{loginBean.user.nickname}" target="#{newsBean}" property="author" />
<h3>News verfassen:</h3>
<h:form>
<p:inputText label="Titel" value="#{newsBean.title}"></p:inputText>
<p:inputTextarea label="Inhalt" value="#{newsBean.description}"></p:inputTextarea>
<p:commandLink type="button" value="Absenden" action="#{newsBean.writeMsg}"></p:commandLink>
</h:form>
I thought that I can use the c:set tag like in the case I want to set a attribute "staticly".. :)
Maybe someone can help me?
Domii
----- AFTER ANSWER ------
LoginBean:
#ManagedBean
#SessionScoped
public class LoginBean {
public LoginBean() {
email = "";
pwd = "";
device = "";
user = null;
}
private String email;
private String pwd;
private User user;
private String device;
/**
* #return the user
*/
public User getUser() {
return user;
}
/**
* #param user the user to set
*/
public void setUser(User user) {
this.user = user;
}
And NewsBean:
public class NewsBean {
#ManagedProperty("#{loginBean.user.nickname}")
private String nickname;
private String title;
private String description;
/**
* Creates a new instance of NewsBean
*/
public NewsBean() {
}
And yes i also declare the getter /setter for nickname in user!

Just use #ManagedProperty.
#ManagedBean
#ViewScoped
public class NewsBean {
#ManagedProperty("#{loginBean.user.nickname}")
private String author;
// ...
}

Related

Search by specific cloumn name in Seam

I am working in seam with jsf1.2.
Everything working fine for me, except the search operation. Can anyone please suggest me to go in a right way?
Here, how I am having my form:
<h:form class="input-list" id="searchUser" style="width:100%;"
name="searchUser">
<div class="edit-label">FIRST NAME :</div>
<h:inputText tabindex="1" id="firstName" type="text" class="miniusername clp"
value="#{userListAction.firstName}" required="true">
<f:validateLength minimum="3" maximum="20" />
</h:inputText>
<h:commandButton value="Search" tabindex="2" style="margin-left: 5px"
action="#{userListAction.retrieveName}" class="usersearch">
</h:commandButton>
</h:form>
My interface:
#Local
public interface UserListAction extends Serializable {
public List<User> retrieveCustomers();
public List<User> retrieveEmployees();
public List<User> getUsersList();
public CLRPUser getLoginUser();
public List<User> retrieveName();
#WebRemote
public String deleteById(Integer userId);
#WebRemote
public CLRPUser getUserById(Integer userId);
public UserTypeEnum getUserType();
public void setUserType(UserTypeEnum userType);
public void setFirstName(String firstName);
public String getFirstName();
public CLRPUser getCurrentUser();
public void setCurrentUser(CLRPUser currentUser);
}
Action class which implements the interface:
#Name("userListAction")
#Stateless
#AutoCreate
public class UserListActionImpl implements UserListAction {
#In
protected UserService userService;
#Out(value = "userType", scope = ScopeType.CONVERSATION, required = false)
private UserTypeEnum userType;
#In
private LoggedInUser loggedInUser;
#Out(value = "currentUser", scope = ScopeType.CONVERSATION, required = false)
#In(value = "currentUser", scope = ScopeType.CONVERSATION, required = false)
private CLRPUser currentUser;
#In(value = "firstName", scope = ScopeType.CONVERSATION, required = false)
private String firstName;
/**
*
*/
private static final long serialVersionUID = 8649412602585430272L;
/*
* (non-Javadoc)
*
* #see com.ermms.clrp.user.UserAction#getUsersList()
*/
public List<User> retrieveName() {
System.out.print("FirstName is :" + firstName);
return userService.getAllUsers(firstName);
}
public UserTypeEnum getUserType() {
return this.userType;
}
public void setUserType(UserTypeEnum userType) {
this.userType = userType;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
#Override
public CLRPUser getCurrentUser() {
// TODO Auto-generated method stub
return null;
}
#Override
public void setCurrentUser(CLRPUser currentUser) {
// TODO Auto-generated method stub
}
}
Console says the First name is : null.
I tried more times, but lost my mind in this. Please suggest me.
Why do you inject the firstName in the userListAction-component? Where should this come from?
If there is nothing more, I guess it works as follows:
user enters first name and clicks the command button
the form gets submitted and the entered first name is set into the model using the setter-method
when executing the command button-action Seam-bijection takes place and injects the value for the firstName stored in "some" context. Since it is not defined anywhere, null is injected.
So if you need the injection (for any case), you should put the correct value in the contest at any place. If not, just remove the #In annotation.

JSF Datatable does not show all List fields(columns)

I want to display a table in JSF:DataTAble. I successfully retrived table from database to List of users type where "users" is my pojo class. Now I am having problem with displaying it on data table some of the columns like FName, LName, Pwd, displayed correctly but when i add other coulmns like "Note" "Email" it gives me this error
javax.servlet.ServletException: /dt.xhtml: Property 'Email' not found on type in.ali.pojo.users
javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
root cause
javax.el.ELException: /dt.xhtml: Property 'Email' not found on type in.ali.pojo.users
com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:88)
com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:82)
com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:302)
com.sun.faces.renderkit.html_basic.TableRenderer.renderRow(TableRenderer.java:385)
com.sun.faces.renderkit.html_basic.TableRenderer.encodeChildren(TableRenderer.java:162)
javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:894)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1856)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
javax.faces.component.UIComponent.encodeAll(UIComponent.java:1859)
com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:443)
com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
here is my xhtml page
<?xml version='1.0' encoding='UTF-8' ?>
<!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>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:dataTable value="#{pretechDataTableBean.user}" var="users">
<h:column>
<f:facet name="header">Name</f:facet>
#{users.FName}
</h:column>
<h:column>
<f:facet name="header">Email</f:facet>
#{users.Email}
</h:column>
<h:column>
<f:facet name="header">Password</f:facet>
#{users.pwd}
</h:column>
</h:dataTable>
</h:body>
</html>
here is my PretechDataTableBean which i used for retrieving data from DB
package com.pretech;
import in.ali.pojo.users;
import in.ali.util.HibernateUtil;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* #author vinod
*/
#ManagedBean
#RequestScoped
public class PretechDataTableBean {
public PretechDataTableBean() {
}
public List<users> getUser() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
List<users> users =null;
try
{
transaction = session.beginTransaction();
users = session.createQuery("from users").list();
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
session.close();
}
return users;
}
}
This is my users pojo
package in.ali.pojo;
// Generated Sep 28, 2013 3:55:01 PM by Hibernate Tools 4.0.0
/**
* users generated by hbm2java
*/
public class users implements java.io.Serializable {
private long UserId;
private String FName;
private String LName;
private long UserTypeId;
private String UserName;
private String Email;
private String Pwd;
private String Note;
private boolean IsActive;
public users() {
}
public users(long UserId) {
this.UserId = UserId;
}
public users(long UserId, String FName, String LName, long UserTypeId,
String UserName, String Email, String Pwd, String Note,
boolean IsActive) {
this.UserId = UserId;
this.FName = FName;
this.LName = LName;
this.UserTypeId = UserTypeId;
this.UserName = UserName;
this.Email = Email;
this.Pwd = Pwd;
this.Note = Note;
this.IsActive = IsActive;
}
public long getUserId() {
return this.UserId;
}
public void setUserId(long UserId) {
this.UserId = UserId;
}
public String getFName() {
return this.FName;
}
public void setFName(String FName) {
this.FName = FName;
}
public String getLName() {
return this.LName;
}
public void setLName(String LName) {
this.LName = LName;
}
public long getUserTypeId() {
return this.UserTypeId;
}
public void setUserTypeId(long UserTypeId) {
this.UserTypeId = UserTypeId;
}
public String getUserName() {
return this.UserName;
}
public void setUserName(String UserName) {
this.UserName = UserName;
}
public String getEmail() {
return this.Email;
}
public void setEmail(String Email) {
this.Email = Email;
}
public String getPwd() {
return this.Pwd;
}
public void setPwd(String Pwd) {
this.Pwd = Pwd;
}
public String getNote() {
return this.Note;
}
public void setNote(String Note) {
this.Note = Note;
}
public boolean isIsActive() {
return this.IsActive;
}
public void setIsActive(boolean IsActive) {
this.IsActive = IsActive;
}
}
The fields must be likeThis instead of LikeThis. Just change your JSF code to
<h:dataTable value="#{pretechDataTableBean.user}" var="user">
<h:column>
<f:facet name="header">Name</f:facet>
#{user.fName}
</h:column>
<h:column>
<f:facet name="header">Email</f:facet>
#{user.email}
</h:column>
<h:column>
<f:facet name="header">Password</f:facet>
#{user.pwd}
</h:column>
</h:dataTable>
And update the field names in your User class to follow the proper Java Bean naming convention.
public class users implements java.io.Serializable {
private long userId;
private String fName;
private String lName;
private long userTypeId;
private String userName;
private String email;
private String pwd;
private String note;
private boolean isActive;
//constructor, getters and setters
}
Apart from this, there are other bugs in your current design:
You must not have business logic in the getters of your managed bean, instead take advantage of the #PostConstruct method to initialize the necessary data to be used.
Since this bean looks that should stay alive while the user stays in the same view, it will be better to decorate it as #ViewScoped instead of #RequestScoped.
Use proper names for your classes and fields. For example, if you have a List<Something> field, name your variable somethingList or similar in order that the code is self-explanatory.
From these, you can change your managed bean to:
#ManagedBean
#ViewScoped
public class PretechDataTableBean {
private List<users> userList;
public PretechDataTableBean() {
}
#PostConstruct
public void init() {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
List<users> users =null;
try
{
transaction = session.beginTransaction();
users = session.createQuery("from users").list();
}
catch(Exception e)
{
e.printStackTrace();
}
finally{
session.close();
}
return users;
}
public List<users> getUserList() {
return this.user;
}
}
Since the field changed its name in the managed bean, you should edit it accordingly in the respective view:
<h:dataTable value="#{pretechDataTableBean.userList}" var="user">
Related info:
Why JSF calls getters multiple times
Communication in JSF 2: Managed bean scopes
JavaBeans API Specification , more specifically, Section 7: Properties.

Managed property between SessionScoped ManagedBeans

I have the following problem!
On one of my sites i have a button:
<h:commandButton value="IDA Analyzer Results" action="#{SelectionBean.monitoringLog()}"/>
The method it calls with some part of the bean:
#ManagedBean(name = "SelectionBean")
#SessionScoped
public class TableSelectionBean {
private List<String> analyzerLog = new ArrayList<String>();
public String monitoringLog() throws FileNotFoundException, IOException{
String fileName = "/opt/IDA2/Linux/bin/"+"filtered_"+selectionMonitoringData.get(0).getMonitoringName()+"_result.txt";
if(selectionMonitoringData.get(0).getIsExecuted())
{
BufferedReader br = new BufferedReader(new FileReader(fileName));
try {
String line;
while ((line=br.readLine()) != null) {
getAnalyzerLog().add(line);
}
} finally {
br.close();
System.out.println(getAnalyzerLog());
}
}
return "analyzerresult.xhtml";
}
After i click this button as you can see it navigates me to an other page:
<h:body>
<h:form>
<h:commandButton value="hi" action="#{AnalyzerBean.myMethod()}"></h:commandButton>
</h:form>
</h:body>
Here is the Bean:
#ManagedBean(name = "AnalyzerBean")
#SessionScoped
public class AnalyzerResultBean {
#ManagedProperty(value="#{SelectionBean.analyzerLog}")
private List<String> analyzerLog;
public void myMethod(){
System.out.print(analyzerLog);
}
/**
* #return the analyzerLog
*/
public List<String> getAnalyzerLog() {
return analyzerLog;
}
/**
* #param analyzerLog the analyzerLog to set
*/
public void setAnalyzerLog(List<String> analyzerLog) {
this.analyzerLog = analyzerLog;
}
So when I'm trying to use this Managed property it says:
The scope of the object referenced by expression #{SelectionBean.analyzerLog}, view, is shorter than the referring managed beans (AnalyzerBean) scope of session but as you can see both of the is Session Scoped. What could be the problem?
If you use JSF 2.x and you want to navigate analyzerresult.xhtml page return analyzerresult
public String monitoringLog() throws FileNotFoundException, IOException{
return "analyzerresult";
}
.xhtml extension is not needed.

JSF display username when the user login

How can I display the username from the userindex page once the user successfully login. Should I be pass it to the constructor and use it? or is there any better solution for this?
Create a session-scoped bean that stores either the user's ID (so you can lookup the user per request) or the actual user object itself.
#Named // or #ManagedBean
#SessionScoped
public class SessionGlobals {
private Integer userId;
public boolean isLoggedIn() {
return userId != null;
}
public Integer getUserId() {
return userId;
}
public void login(int userId) {
this.userId = userId;
}
public void logout() {
this.userId = null;
}
Inject this bean wherever it is required. When you login and logout, call the appropriate methods above.
For example:
#Named // or #ManagedBean
#RequestScoped
public class RequestGlobals {
public User getUser() {
return sessionGlobals.isLoggedIn()
? userDao.findById(sessionGlobals.getUserId())
: null;
}
#Inject
private UserDao userDao;
#Inject
private SessionGlobals sessionGlobals;
}
and in your page or template:
<h:outputText value="Welcome, #{requestGlobals.user.firstName}"
rendered="#{sessionGlobals.loggedIn}"/>

JSF: Conversion Error setting value '<some string>' for 'null Converter'

I am getting the null Converter error for what I thought was a very simple scenario:
<!-- My View -->
<ui:composition template="/template/template_v1.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<!-- Simplified for clarity -->
<h:form>
<div class="block-panel customer-data">
<h:outputLabel for="txtUsername">Username:</h:outputLabel>
<h:inputText id="txtUsername" name="Username"
value="#{userBean.user.id}"
styleClass="text" />
<rich:message id="errorUsername" for="txtUsername"/>
</div>
<!-- Other fields omitted for clarity -->
</h:form>
/* The User Bean - simplified */
#ManagedBean
#ViewScoped
public class UserBean implements Serializable {
private User user;
public User getUser() {
// Contains logic for reading a user from the database or creating a new
// user object
return user;
}
public void setUser(User user) {
this.user = user;
}
}
/* The user Entity - Simplified */
#Entity
#Table(name = "user")
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name = "user_type", discriminatorType = DiscriminatorType.STRING)
public class User implements IEntity<String>, Serializable {
private static final long serialVersionUID = 1L;
private String id;
#Id
#Column(name = "username", length = 50)
#NotNull(message = "{userIdMandatory}")
#Size(max = 50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
}
/* The IEntity interface */
public interface IEntity<ID extends Serializable> {
ID getId();
void setId(final ID pId);
}
So essentially I'm trying to bind a string property of my user entity to a inputText field. As far as I'm concerned there should be no need for a conversion so I shouldn't be getting the error I'm seeing.
Interestingly, if I add the following getter and setter to my entity:
public String getTmpId() {
return this.id;
}
public void setTmpId(String id) {
this.id = id;
}
And then make the necessary changes to my view to bind to tmpId rather than id, everything works as expected.
This seems like a bug to me either to do with the fact that I am binding to a getter/setter defined in an interface, defined in a generic interface or because the getter is marked with the Id attribute. I would appreciate someone else's ideas however.
As an aside, I have inherited this design and don't particularly like it so I may just end up refactoring it to introduce a new username property rather than trying to use the Id.
To the best of my knowledge I believe this is caused by an obscure bug in BeanELResolver which is used to get the type of the property being bound to - rather than returning String it is returning Serializable, for which there is no converter and hence the error I am seeing.
It's not particularly elegant, but I have worked around this by adding a userId property to my userBean and then binding to that in my view instead of the Id property on the user entity. I then use that value to set the Id manually on the entity when I save it:
<!-- My New View -->
<ui:composition template="/template/template_v1.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
<!-- Simplified for clarity -->
<h:form>
<div class="block-panel customer-data">
<h:outputLabel for="txtUsername">Username:</h:outputLabel>
<h:inputText id="txtUsername" name="Username"
value="#{userBean.userId}"
styleClass="text" />
<rich:message id="errorUsername" for="txtUsername"/>
</div>
<!-- Other fields omitted for clarity -->
/* The New User Bean - simplified */
#ManagedBean
#ViewScoped
public class UserBean implements Serializable {
private string userId;
private User user;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public User getUser() {
// Contains logic for reading a user from the database or creating a new
// user object
return user;
}
public void setUser(User user) {
this.user = user;
}
public void saveUser() {
if (user.getId() == null) {
user.setId(userId);
}
// Actual saving omitted for brevity
}
}

Resources