Combobox created dynamically from database (JSF) - mysql

I wanted to create in JSF a combobox (selectOneMenu). I want to fill this combobox with all logins from one column from Database (SELECT logins FROM database).
Will be much gratefull from any help.

In your backing bean (YourBean in the example) you should have an array of Strings (or of objects with a getter method that returns the String you want). For instance lets assume you have the following code in your backing bean:
private ArrayList<String> logins; // read from DB
private String selectedLogin; // this will hold the selected value
// this method will be called by the JSF framework to get the list
public ArrayList<String> getLogins()
{
return logins;
}
public String getSelectedLogin()
{
return selectedLogin;
}
public String setSelectedLogin(String sl)
{
selectedLogin = sl;
}
In you Facelets page, assuming you are on JSF 2.x:
<h:selectOneMenu value="#{YourBean.selectedLogin}">
<f:selectItems value="#{YourBean.logins}" itemLabel="#{l}" itemValue="#{l}" var="l"/>
</h:selectOneMenu>
This will create a select menu with all the options in the array. Once the form is submitted the value will be set in the String value of your backing bean.

Related

PropertyNotFoundException for p:column filterValue attribute

we are trying to migrate our application from tomcat/websphere to was liberty profile.
Additionally we are upgrading the myfaces-version, we are using 2.1, to myfaces-2.2.
To save the current state of a table (filtering) we store the filtered value in a map and read it when loading the table (filterValue attribute of p:column).
When initially loading the table the correct method will be used (in our case its getFilterValue in the DataModel). But if we start filtering a column, the method wont be found anymore and the following exception occurs:
javax.el.PropertyNotFoundException: Die Eigenschaft 'getFilterValue' wurde nicht im Typ package.LazyModel gefunden.
javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:245)
javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:222)
javax.el.BeanELResolver.property(BeanELResolver.java:332)
javax.el.BeanELResolver.getType(BeanELResolver.java:83)
javax.el.CompositeELResolver.getType(CompositeELResolver.java:99)
org.apache.myfaces.el.unified.resolver.FacesCompositeELResolver.getType(FacesCompositeELResolver.java:150)
org.apache.el.parser.AstValue.setValue(AstValue.java:199)
org.apache.el.ValueExpressionImpl.setValue(ValueExpressionImpl.java:257)
org.jboss.weld.el.WeldValueExpression.setValue(WeldValueExpression.java:64)
org.apache.myfaces.view.facelets.el.ContextAwareTagValueExpression.setValue(ContextAwareTagValueExpression.java:153)
org.primefaces.component.datatable.DataTable.processUpdates(DataTable.java:746)
org.apache.myfaces.context.servlet.PartialViewContextImpl$PhaseAwareVisitCallback.visit(PartialViewContextImpl.java:787)
org.apache.myfaces.component.visit.PartialVisitContext.invokeVisitCallback(PartialVisitContext.java:213)
org.primefaces.component.api.UIData.visitTree(UIData.java:822)
The table:
<p:dataTable id="table" var="group"
value="#{bean.lazyModel}"
selection="#{bean.selectedMulti}"
rows="#{bean.lazyModel.rows}" paginator="true"
currentPageReportTemplate="#{msg['data.table.pagereport']}"
paginatorTemplate="#{msg['data.table.paginator']}"
rowsPerPageTemplate="#{msg['data.table.rows']}"
resizableColumns="true" rowKey="#{group.pkId}" lazy="true"
filterDelay="1000" emptyMessage="#{msg['data.table.empty']}"
style="font-size: 8pt;"
tableStyle="font-size: 8pt; table-layout:auto;"
first="#{bean.lazyModel.first_m}"> >
<p:column headerText="Name"
sortBy="#{group.name}" filterBy="#{group.name}"
filterValue="#{bean.lazyModel.getFilterValue('name')}"
filterStyleClass="column_filter" styleClass="wrap">
<h:outputText value="#{group.name}" />
</p:column>
...
The lazymodel:
#Named
#Scope(value = "prototype")
public class LazyModel extends AbstractLazyModel<Brand> {
private static final long serialVersionUID = 2247660292777600670L;
/**
* Konstruktor
*/
public LazyModel() {
super();
}
public Object getFilterValue(final String keyForColumn) {
return this.filterManager.getFilterField(this.getKeyForPage(), keyForColumn);
}
I think this should be the most important things to know.
So, i dont understand what changed between these versions that trigger the exception.
Every help would be great. TIA!
I don't know why this has worked before (it should not have (properly)), but the error you are currently getting is sort of expected. The filterValue attribute should be bound to a property with read and write access. You could bind each column filter value to an individual property, but it is more convenient to use a Map<String,Object> for your filter values.
Bean (lazy model in your case):
private Map<String,Object> filterValues = new HashMap<>();
// ... add getter and setter for filterValues
XHTML:
filterValue="#{bean.lazyModel.filterValues['name']}"

how to get mapping id dynamically from data base

i am developing an application in which i have put menus which are rendered from mysql database i have inserted menus names and mappingIds into db table.
now i am getting problem how do i rendered list (list of menus) into xhtml(jsf html tags) currently i am using this
i have saved all menus in subMenuBeanList and stored this list into Session
and then iterate(ui:repeat) subMenuBeanList into xhtml file where i want to get menus names(show menus names to the user) like this: h:commandLink value="#{subMenuBeanList.subMenuNameBean}" and mappingId action="#{subMenuBeanList.subMenuLinkBean}" see clear code below :
<ui:repeat value="#{session.getAttribute('subMenuBeanList')}" var="subMenuBeanList">
<h:commandLink value="#{subMenuBeanList.subMenuNameBean}" action="#{subMenuBeanList.subMenuLinkBean}" />
// i want this <h:commandLink value="menu One Name" action="pretty:menuonemappingid" />
//<h:commandLink value="menu Two Name" action="pretty:menutwomappingid" />
// so on depending upon records in table
// closing tags
here when i click on h:commandLink i get this Exception
javax.el.MethodNotFoundException: /template/templateslider.xhtml #56,123 action="#{subMenuBeanList.subMenuLinkBean}": Method not found: com.hesco.repository.common.generalinformation.managed.bean.SubMenuBean#1a0974ce.subMenuLinkBean()
i know this subMenuLinkBean is not a method its a variable in action(.java) class but here i put it into action="#{subMenuBeanList.subMenuLinkBean}" thats why i am getting this exception..
my question is that how do i do this ? i want to get mappingId from Db not hard coded in any file
this is managed bean class
#ManagedBean(name="subMenuBean")
#ViewScoped
public class SubMenuBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer subMenuIdBean;
private Integer menuIdBean;
private String subMenuNameBean;
private String subMenuLinkBean;
private String isActive;
//jsf will not create nasted object, so that i create it like this.
private MenuBean menuBean = new MenuBean();
//private Set<Assigneduserrole> assigneduserroles = new HashSet<Assigneduserrole>(0);
private ArrayList<SubMenuBean> subMenuBeanList = null;
///setter and getter
this is an other class from where i am setting beans value
query is fatched db records..
for (Iterator it = query.iterator(); it.hasNext();) {
Object[] obj = (Object[]) it.next();
log.info("assigning role by iterator");
// adding Section Beans into ArrayList
SubMenuBean subMenuBean = new SubMenuBean();
subMenuBean.setSubMenuIdBean(((Submenu) obj[2]).getSubMenuId());
subMenuBean.setSubMenuNameBean(((Submenu) obj[2]).getSubMenuName());
subMenuBean.setSubMenuLinkBean(((Submenu) obj[2]).getSubMenuLink());
subMenuBean.setMenuIdBean(((Submenu) obj[2]).getMenu().getMenuId());
subMenuBean.setIsActive(((Submenu) obj[2]).getIsActive());
this.subMenuBeanList.add(subMenuBean);
log.info("Sub Menu List: " + this.subMenuBeanList.size());
} // ending of Object iterator

Reset input fields of a form after successful submit

I have a form which creates a new Employee. My backing bean is #SessionScoped. When I create the first employee, everything went well. However, when I'm about to create the second employee, the form still displays the properties of the first employee in the input fields.
How do I reset them without changing the scope of the bean? The scope is mandatory for other purposes.
i use a managed Bean ( controller) where i have "Create employe"
public String createEmploye()
{
employe = new Employe();
employe.setId(this.id);
employe.setNom(this.nom);
employe.setPrenom(this.prenom);
employe.setNum_telephone(this.num_telephone);
employe.setAdresse(this.adresse);
employe.setNum_poste(this.num_poste);
employeBean.addEmploye(employe);
employe.setNom("");
return "ListEmployes.xhtml?faces-redirect=true";
// return ("ListEmployes.xhtml");
}
Recreate the Employee instance after saving it in the DB.
public void save() {
service.save(employee);
employee = new Employee(); // <--- Just add this line.
}
Unrelated to the concrete problem, I however strongly recommend to reconsider your bean design. Shouldn't it rather be split into two beans? One request/view scoped for the form itself and another session scoped one for the real session scoped data which get injected in the request/view scoped one. This way you can after the save just perform a redirect to the same view in order to start with a clean form (and have the additional benefit that the very same employee doesn't get duplicated in the DB when you refresh the page after submit).
See also:
How to choose the right bean scope?
Update as per the update, it seems that you're duplicating/flattening all properties of Employee in the backing bean instead of letting the form refer them directly. I strongly recommend to not duplicate/flatten the model properties into the controller.
#ManagedBean
#SessionScoped
public class Manager {
private Employee employee = new Employee();
#EJB
private EmployeeService service;
public void createEmployee() {
service.create(employee);
employee = new Employee();
}
public Employee getEmployee() {
return employee;
}
}
with
<h:inputText value="#{manager.employee.firstname}" />
<h:inputText value="#{manager.employee.lastname}" />
<h:inputText value="#{manager.employee.telephone}" />
<h:inputText value="#{manager.employee.street}" />
...
I could solve this problem by creating a method that makes me void the object and calling it inside the form on page jsf.
public void clear_objet() {
this.producto = null;
}
<h:form id="form">
#{bean.limpiar_objeto()}
</h:form>

Adding content from a database into a dropdownlist in struts2

I am doing my project in struts2 framework. but i cant find a way to specify a dropdown list from a database.. is there a way.. pls help
If you are talking about a drop down list in your JSP page than there is already a select Tag for that
<s:select name="mydrop_down" list="%{sports}" />
where list is a Iterable source to populate from. If the list is a Map (key, value), the Map key will become the option 'value' parameter and the Map value will become the option body.
All you need to create a List/Map/Array in you action class and provide its getter and setter how the list will be picked form the ActionClass in jsp will be handled by the framewrok itself
Action Class
public class MyAction extends ActionSuport{
private List<String> sports; //can be array or map etc
getters and setters for sports
public String execute() throws Exception{
sports = init the List and fill it
// can fill the list from database
return SUCCESS;
}
}

Struts 2 - pattern/strategy for multiple objects on the same page

I'm looking for a good design pattern/strategy for how to using the Struts 2 framework for editing multiple objects of the same type on an HTML page. Struts is really good for editing a single object, like Address. If you provider accessor methods for address1, city, state, etc, struts calls those and the standard struts UI tags will populate the form fields accordingly.
How to do this when editing multiple of the same type of object on the same page. I have a web based contest, parting of the contest is a set of rating scale objects for each contest. Each rating scale has a value and a label. If I name the input fields value_0, value_1... and label_0, label_1... then I either have to code a bunch of accessor methods (UGLY) or use the raw parameters to get the values I need. It is difficult, but not impossible, to use the struts validation methods to send error messages back to the correct form field.
If I name all the fields "Value" and "label", struts is kind enough to call a method that sets a List of input values, but I have no way of sending validation errors back to the correct output field.
I need something that doesn't require a huge number of accessor methods, allows easy access to the inputs to validate, return validation messages to the correct form field.
The strategy here is to use a Map<Integer, Address>.
Example Bean Class
Let's assume the following example Address class.
public class Address {
private String line1;
private String line2;
private String city;
private String state;
private String zipCode;
// getters and setters here
}
Example Action
public class ExampleAction extends ActionSupport {
/**
* A map of ID -> Address.
*/
private Map<Integer, Address> addresses = Maps.newLinkedHashMap();
// ... action method(s) and validate here
public Map<Integer, Address> getAddresses() {
return addresses;
}
}
In your JSP layer, you can iterate over the map (each iteration is a Map.Entry) and output the fields (line1, line2, city, etc.) for each. The field names should be:
addresses[0].line1
addresses[0].line2
addresses[0].city
addresses[0].state
addresses[0].zipCode
...
addresses[5].line1
addresses[5].line2
addresses[5].city
addresses[5].state
addresses[5].zipCode
To perform validation, just iterate over the map and check each field appropriately. When editing addresses, you can use the primary key of the address from your database. For adding new addresses, you can just increment starting from zero. The index can be any number, so long as its unique within the map.
I typically map out everything I need to use in a form and group them into related classes, Person, Address, Misc for example. I will then create a wrapper class and use delegate accessor methods to provide a single interface to access the individual objects. Most often I work with JPA entites so these classes are already set up for me, I just need the wrapper and maybe some utility methods for CRUD functions. For example:
public class ContactWrapper implements Serializable{
private Person person;
private Address address;
private Misc misc;
// Getters / Setters for primary objects - person, address, misc
...
// Delegate accessors
public String getName(){
return person.getName();
}
public String setName(String name){
return person.setName(name);
}
...
}
Now you have one object to work with in your action class and jsp's which can be references however you choose.
In your action class:
public class ContactAction extends ActionSupport{
private ContactWrapper contact;
....
}
In your JSP:
<s:textfield name="contact.name" />
Struts handles all the object instantiation auto-magically, even in objects contained inside other objects.