How to manipulate Java List with jsf RequestScope - jsf

I'm using JSF 2.2 with RequestScoped managebean. I'd like to update a Java List inside of Customers entity. When submitting, only info in Java List (List<'Phone >) is gone. I don't want to use SessionScoped. Could anyone share some tips or solve this issue?
My codes are shown here.
Customers Entity:
{ ..
#Column(name = "FIRSTNAME")
private String firstname;
#Column(name = "LASTNAME")
private String lastname;
...
#ElementCollection
#CollectionTable(name = "CUSTOMERS_Phone",
joinColumns = #JoinColumn(name = "CUSTOMERS_ID"))
#AttributeOverride(name = "teleNumbers",
column = #Column(name = "PHONE_NUMBER",length=30))
private List<Phone> phone;
..}
JSF Managebean:
#Named(value = "editCustomersBeanService")
#RequestScoped
public class EditCustomersBeanService implements Serializable {
/**
* Creates a new instance of EditCustomersBeanService
*/
#PostConstruct
public void init() {
ctx = FacesContext.getCurrentInstance();
customers =new Customers();
phones = new ArrayList<>();
customers.setPhone(phones);
}
public EditCustomersBeanService() {
}
#Inject
private BusinessSessionCustomers businessSSCustomers;
private int customerId;
private List<Phone> phones;
private Customers customers;
//setter, getter ...
//update to DB
public String updatedCustomers() {
System.out.println("customer Name: " + customers.getFirstname());
System.out.println("customer LastName: " + customers.getLastname());
System.out.print("List of Phones in updatedCustomers: ");
for (Phone ph : customers.getPhone()) {
System.out.print(ph.getPhoneType() + ", " + ph.getTeleNumbers());
}
businessSSCustomers.mergeToDB(customers);
return "customers";
}
..
}
CustomersEdit.xhtml:
<h:form>
...
<label for="Last Name">Last Name</label>
<h:inputText id="lastName" p:placeholder="Last Name"
value="#{editCustomersBeanService.customers.lastname}"/>
<ui:repeat var="phone" value="#{editCustomersBeanService.customers.phone}" varStatus="status">
<label for="phones">Phone: [#{status.index}]</label>
<h:selectOneMenu value="#{phone.phoneType}">
<f:selectItems value="#{editCustomersBeanService.phoneTypeList}"
itemLabel="#{editCustomersBeanService.phoneType}"
itemValue="#{editCustomersBeanService.phoneType}"/>
</h:selectOneMenu>
<h:inputText class=" form-control" value="#{phone.teleNumbers}" />
</ui:repeat>
<h:commandLink value="Save" action="#{editCustomersBeanService.updatedCustomers()}" />
…
</h:form>
Phone.java:
#Embeddable
public class Phone {
public enum PhoneType {
Home, Mobile, Work
}
#Enumerated(EnumType.STRING)
#Column(name = "PHONE_TYPE", length = 10)
private PhoneType phoneType;
#Column(name = "PHONE_NUM", length = 30)
private String teleNumbers;
//setter, getter
..
}

Related

Set a default input value that can be editable

I would like to create a JSF application
Where a user must provide their age. This will default to 18 and be editable (If the user wants to provide a different value).
How to achieve this functionality?
The input value provided by the user or the default value ie which is 18 would be saved in the Database
<h:form>
<p:panel id="panel" header="New User">
<h:panelGrid columns="3" cellpadding="5">
<p:outputLabel for="age" value="Age:" />
<p:inputText id="age" value="#{managedBean.entityBean.age}" required="true" label="Age">
</p:inputText>
</h:panelGrid>
<p:commandButton value="Save" update="panel" action="#{managedBean.save}" />
</p:panel>
</h:form>
Entity.java
public class Entity implements Serializable {
#Column(name = "AGE")
private Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
managedBean.java
#ManagedBean(name = "managedBeanJava")
#ViewScoped
public class managedBeanJava implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(managedBeanJava.class);
private Entity entityBean;
public Entity getEntityBean() {
return entityBean;
}
public void setEntityBean(Entity entityBean) {
this.entityBean = entityBean;
}
private Integer age = 50;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
#PostConstruct
public void init() {
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, String> params = externalContext.getRequestParameterMap();
}
public void save(AjaxBehaviorEvent event) {
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
entityBean.setAge(this.entityBean.getAge());
}
}
You could define default value of <h:inputText> in your managed bean directly.
private Integer age = 18;

JSF SelectOneRadio PrimeFaces javax.el.PropertyNotFoundException: Target Unreachable

When I insert this into my xhtml I'll get the javax.el.PropertyNotFoundException: Target Unreachable, identifier 'telefonbuch' resolved to null
<h3>Auswahl</h3>
<h1:panelGrid columns="2" style="margin-bottom:10px" cellpadding="5">
<p:outputLabel for="geschaeftsstelle" value="Geschäftsstelle:" />
<p:selectOneRadio id="geschaeftsstelle" value="#{telefonbuch.geschaeftsstelle}" layout="grid" columns="3">
<f:selectItems value="#{telefonbuch.geschaeftsstellen}" var="c" itemLabel="#{geschaeftsstelle}" itemValue="#{geschaeftsstelle}"/>
</p:selectOneRadio>
</h1:panelGrid>
My model class looks like this:
#Data
#Entity
public class Telefonbuch {
#PostConstruct
public void init() {
geschaeftsstellen = new ArrayList<String>();
geschaeftsstellen.add("Dortmund");
geschaeftsstellen.add("Essen");
geschaeftsstellen.add("Stralsund");
geschaeftsstellen.add("Stuttgart");
geschaeftsstellen.add("Zürich");
geschaeftsstellen.add("Istanbul");
geschaeftsstellen.add("Köln");
geschaeftsstellen.add("Aachen");
geschaeftsstellen.add("Berlin");
}
public String getGeschaeftsstelle() {
return geschaeftsstelle;
}
public void setGeschaeftsstelle(String geschaeftsstelle) {
this.geschaeftsstelle = geschaeftsstelle;
}
public List<String> getGeschaeftsstellen() {
return geschaeftsstellen;
}
public void setGeschaeftsstellen(List<String> geschaeftsstellen) {
this.geschaeftsstellen = geschaeftsstellen;
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column
private String vorname;
#Column
private String nachname;
#Column
private String telefonnummer;
#Column
private String handynummer;
#Column
private String geschaeftsstelle;
#Column
#ElementCollection
private List<String> geschaeftsstellen;
protected Telefonbuch() {
}
public Telefonbuch(String vorname, String nachname, String telefonnummer, String handynummer) {
this.vorname = vorname;
this.nachname = nachname;
this.telefonnummer = telefonnummer;
this.handynummer = handynummer;
}
I don't know what the problem is. The buttons won't be shown. Just the heading is there. No choices.
Just clean your project and it should work fine.
I don't know is it your case, but whenever i have similar problem, cleaning project and reloading server solved it for me.
EDIT:
I will assume that #Data and #Entity are valid identifiers in this case (because i am always using #ManagedBean, and store it in some DTO class later.
Also i think that this line:
<f:selectItems value="#{telefonbuch.geschaeftsstellen}" var="c" itemLabel="#{geschaeftsstelle}" itemValue="#{geschaeftsstelle}"/>
should look like this:
<f:selectItems value="#{telefonbuch.geschaeftsstellen}" var="c" itemLabel="#{c.geschaeftsstelle}" itemValue="#{c.geschaeftsstelle}"/>

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.

Adding a Customer object to a database from a SelectOneMenu

I am trying to create a new order by selecting a customer name from a SelectOneMenu. I am getting a Conversion error setting value for 'null Converter'.
Order.java
#Entity
#Table(name = "order")
public class Order
{
#Id
#Column(name = "ORDER_ID", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private long orderId;
#JoinColumn(name = "PRODUCT_ID", referencedColumnName = "PRODUCT_ID")
private Product product;
#Column(name = "QUANTITY")
private int quantity;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "ORDER_DATE")
private Date orderDate;
#ManyToOne(optional = false)
#JoinColumn(name = "CUSTOMER_ID", referencedColumnName = "CUSTOMER_ID")
private Customer customer;
// Getters & Setters
}
newOrder.xhtml
<h:outputLabel value="Customer: "/>
<h:selectOneMenu id="customer" value="#{solController.order.customer}" >
<f:selectItem itemLabel="" itemDisabled="true"/>
<f:selectItems value="#{solController.customerList}" var="customer" id="customerID" itemLabel="#{customer.customerName}" itemValue="#{customer.customerId}" />
</h:selectOneMenu>
SolController.java
#ManagedBean(name = "solController")
#SessionScoped
public class SolController implements Serializable
{
#EJB
private SolEJB solEJB;
private Order order = new Order();
private List<Order> orderList = new ArrayList<Order>();
public String doCreateOrder()
{
order = solEJB.createOrder(order);
orderList = solEJB.findOrders();
return "listOrders.xhtml";
}
// Getters & Setters
}
SolEJB.java
#Stateless
public class SolEJB
{
#PersistenceContext(unitName = "myPU")
private EntityManager em;
public Order createOrder(Order order)
{
em.persist(order);
return order;
}
}

Passing parameters between managedbeans primefaces

I have a problem with my managedbeans. I cannot manage to pass parameters between them. Here is an XHTML snippet. It is basically a form for login. It just sends the parameters to back bean.
<h:outputLabel for="username" value="Kullanıcı Adı: *" />
<p:inputText id="username" value="#{loginBean.username}" required="true" requiredMessage="Kullanıcı adı giriniz.">
<f:validateLength minimum="2" />
</p:inputText>
<p:message for="username" display="icon"/>
<h:outputLabel for="password" value="Şifre: *" />
<p:inputText id="password" value="#{loginBean.password}" required="true" requiredMessage="Şifreyi giriniz!" type="password">
<f:validateLength minimum="2" />
</p:inputText>
<p:message for="password" id="msgPass" display="icon"/>
<f:facet name="footer">
<center>
<p:commandButton id="submit" value="Giriş" icon="ui-icon-check" action="#{loginBean.check}" style="margin:0" update="grid"/>
</center>
</f:facet>
In my backing bean, I am checking whether the user input matches with the database record. If so then I let him enter the system. At the same time, I am taking his full name.
My backbean:
#ManagedBean
#RequestScoped
public class LoginBean {
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMgs() {
return mgs;
}
public void setMgs(String mgs) {
this.mgs = mgs;
}
public String getFullname() {
return fullname;
}
public void setFullname(String fullname) {
this.fullname = fullname;
}
public String getOriginalURL() {
return originalURL;
}
public void setOriginalURL(String originalURL) {
this.originalURL = originalURL;
}
private String username;
private String password;
private String mgs;
private String fullname;
private String originalURL;
private static Logger log = Logger.getLogger(LoginBean.class.getName());
public String check() throws Exception {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/projetakip", "root", "");
Statement stmt = con.createStatement();
String md5Pass = md5(password);
String SQL = "select * from users where username='" + username + "' and password='" + md5Pass + "'";
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
if (username.matches(rs.getString("username")) && md5Pass.matches(rs.getString("password"))) {
this.fullname = rs.getString("ad") + " " + rs.getString("soyad");
return "panel?faces-redirect=true";
} else {
FacesMessage msg = new FacesMessage("Yanlış kullanıcı adı/şifre.");
FacesContext.getCurrentInstance().addMessage(null, msg);
return "index?faces-redirect=true";
}
}
return "index?faces-redirect=true";
}
public void getProductSetupData(ActionEvent event) {
FacesContext context = FacesContext.getCurrentInstance();
Data data = context.getApplication().evaluateExpressionGet(context, "#{data}", Data.class);
}
What I want is to pass fullName to other beans (or pages). How can I pass this variable between my beans?
Thanks in advance.
BalusC wrote a whole blog post about communication in JSF 2.0, it is truly worthy of your time. Reading it, you will discover that there are more than one way of doing it, one of them being injecting the property itself, in your other beans:
#ManagedProperty("#{loginBean.fullName}")
private String fullName;
And another, perhaps more appropriate, could be to inject the bean itself:
#ManagedProperty("#{loginBean}")
private LoginBean loginBean;

Resources