I am using a p:schedule but it won't show up at the first time I entered the page
I have to refresh the page once and then it comes out.
<?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">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:form id="form">
<h:outputScript library="js" name="primefaces-locale-zh.js" />
<div class="top-extra-title">
<h:outputText value="#{menu.miMeetingScheduleView}" />
</div>
<p:schedule id="schedule" value="#{meetingScheduleView.meetingSchedule}"
widgetVar="meetingSchedule" timeZone="GMT+8" draggable="false"
locale="zh" >
<p:ajax partialSubmit="true" event="eventSelect" listener="#{meetingScheduleView.onEventSelect}"
update="mform :content" />
</p:schedule>
</h:form>
</ui:composition>
#ManagedBean(name = "meetingScheduleView")
#ViewScoped
public class MeetingScheduleView implements Serializable {
private static final long serialVersionUID = 1L;
SessionUser sessionUser;
private String accountOrgId;
private static final String msgFile = "cyberstar.module.meeting.meeting";
private List<Meeting> meetingList;
private ScheduleModel meetingSchedule;
private ScheduleEvent event;
#ManagedProperty(value = "#{sysAdminPage}")
private SysAdminPage sysAdminPage;
#PostConstruct
public void init() {
sessionUser = JSFUtil.getSessionUser();
if(sessionUser==null){
MsgUtil.showErrorMsg(msgFile, "infSessionUserFail", "infSessionUserFailDetail");
sessionUser.logoff();
}
accountOrgId = sessionUser.getOperator().getOrgId();
meetingList = new ArrayList<Meeting>();
meetingSchedule = new DefaultScheduleModel();
event = new DefaultScheduleEvent();
initialize();
}
public void sendMeetingUnid(){
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
String issueUnid = context.getRequestParameterMap().get("meetingUnid");
LinkedHashMap<String , String> hm = new LinkedHashMap<String , String>();
if (sessionUser.getSendDataMap().get("meetingView") == null) {
hm.put("meetingUnid", issueUnid);
sessionUser.getSendDataMap().put("meetingView", hm);
} else {
hm = sessionUser.getSendDataMap().get("meetingView");
hm.put("meetingUnid", issueUnid);
}
}
public void initialize(){
try {
if (sessionUser.isCyberStar()) {
meetingList = MeetingDAO.getAllMeeting();
} else {
meetingList = MeetingDAO.getMeetingByOrgId(accountOrgId);
}
for (int i = 0; i < meetingList.size(); i++) {
Meeting m = meetingList.get(i);
if (m.getStatus().equals(MeetingStatus.sketch)) {
continue;
}
DefaultScheduleEvent dsEvent = new DefaultScheduleEvent(m.getTitle(), m.getStartTime(), m.getEndTime(),m.getUnid());
if(m.getStatus().equals(MeetingStatus.cancel)){
dsEvent.setStyleClass("redEvent");
}
meetingSchedule.addEvent(dsEvent);
}
} catch (SQLException e) {
MsgUtil.showErrorMsg(msgFile, "infUpdateFail",
"infUpdateFailSQLExceptionDetail");
e.printStackTrace();
}
}
public void onEventSelect(SelectEvent selectEvent) {
event = (ScheduleEvent) selectEvent.getObject();
String issueUnid = String.valueOf(event.getData());
LinkedHashMap<String , String> hm = new LinkedHashMap<String , String>();
if (sessionUser.getSendDataMap().get("meetingView") == null) {
hm.put("meetingUnid", issueUnid);
sessionUser.getSendDataMap().put("meetingView", hm);
} else {
hm = sessionUser.getSendDataMap().get("meetingView");
hm.put("meetingUnid", issueUnid);
}
try {
sysAdminPage.openView("meetingForm");
} catch (IOException e) {
MsgUtil.showErrorMsg(msgFile, "infUpdateFail", "infUpdateFailExceptionDetail");
e.printStackTrace();
}
}
these are the codes of button which direct to the page
<p:menuitem value="#{menu.miMeetingScheduleView}" styleClass="meetingScheduleView"
onclick="highlightme('meetingScheduleView')" action="#{sysAdminPage.menuSelected}"
update="mform :content">
<f:param name="viewname" value="meetingScheduleView" />
</p:menuitem>
my goal is to show the p:schedule just when I enter the page
Related
my pb is that when I select an item to display items in the second selectOneMenu () the submit button does not work.
at the second click the button tries to submit the form but (this action emptie the second SOM) as the second SelectOneMenu becomes empty its trigger a validation error.
primefaces 6.1
jsf2.2
tomcat8.5
<h:form id="create_intervention_form">
<h:messages id="errorMessages" style="color:red;margin:8px;" />
<h:panelGroup id="addProjet2" rendered="true">
<table>
<tr>
<td><h:outputLabel value="Structure à visiter:" for="Client2">
</h:outputLabel></td>
<td><p:selectOneMenu id="Client2"
value="#{creerintervention.selected_client}" effect="fade"
style="width:100px" filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{creerintervention.list_client}" var="cl"
itemValue="#{cl}" itemLabel="#{cl.nom_client}" />
<f:converter converterId="ClientConverter" />
<p:ajax update="create_intervention_form:station1_client"
listener="#{creerintervention.getStructureByClient}"
process="Client2" />
</p:selectOneMenu> <p:selectOneMenu id="station1_client"
value="#{creerintervention.selectedStation}" style="width:100px"
filter="true" filterMatchMode="startsWith">
<f:selectItems value="#{creerintervention.list_Station}"
var="entry1" itemValue="#{entry1}" itemLabel="#{entry1.nom_stat}" />
<f:converter converterId="StationConverter" />
<p:ajax partialSubmit="false" />
</p:selectOneMenu></td>
</tr>
<tr>
<p:commandButton value="Valider" pdate="create_intervention_form"
id="valide" actionListener="#{creerintervention.addOdm}"
styleClass="ui-priority-primary" />
</tr>
</table>
</h:panelGroup>
</h:form>
ManagedBean
#RequestScoped
#Management(name = "creerintervention")
public class CreerIntervention {
private String matricule;
private agentService agentservice = new agentServiceImpl();
private usersService usersService = new usersServiceImpl();
private clientService clientService = new clientServiceImpl();
private List<client> list_client;
private List<station> list_Station;
private List<SelectItem> clientList;
//private Map<String, String> clientList;
//private Map<String, String> StationList;
private List<SelectItem> StationList;
private station selectedStation;
private client Selected_client;
{
//*** initialiser la liste des client dans le SelectOnMenu
list_client = clientService.findAll();
}
public void getStructureByClient()
{
// ######## Préparer la liste des nom des clients ######## //
list_Station=stationService.findByRefClient(getSelected_client().getRef());
log.info("La refernce du client est ---"+ Selected_client.getRef());
log.info("LES STIONS SONT D UN NBR DE ---"+ list_Station.size());
}
public void addOdm(ActionEvent e)
{
log.info("Matricule:" + matricule) ;
log.info("destination:" +destination);
log.info("client:"+Selected_client.getNom_client()) ;
log.info("station:"+ selectedStation.getNom_stat());
log.info("objet mission:"+ obj_mission );
log.info("date depart:"+ date_dep );
log.info("date ret:"+ date_retour );
log.info("moyen transp:"+ moyen_transport) ;
log.info("imma:"+ immatriculation) ;
log.info("prise en charge :"+ prise_en_charge) ;
log.info("struct:"+ structure) ;
}
.....
Setters and Getters...
I have get the solution ; the problem was in the Scope the right one is #ViewScoped.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Insert title here</title>
</h:head>
<h:body>
<h:form id="create_intervention_form">
<h:messages id="errorMessages" style="color:red;margin:8px;" />
<table>
<tr>
<td><p:outputLabel value="Matricule:" for="Matricule" /></td>
<td><p:inputText id="Matricule"
value="#{teststation.matricule}" size="5" /></td>
</tr>
<tr>
<td><h:outputLabel value="Structure à visiter:" for="Client2"></h:outputLabel> </td>
<td>
<p:panel id="st">
<p:selectOneMenu id="Client2" value="#{teststation.selected_client}">
<f:selectItems value="#{teststation.list_client}" var="cl" itemValue="#{cl}" itemLabel="#{cl.nom_client}" />
<f:converter converterId="ClientConverter" />
<p:ajax update="station1_client" listener ="#{teststation.getStructureByClient}" />
</p:selectOneMenu>
<p:selectOneMenu id="station1_client" value="#{teststation.selectedStation}" >
<f:attribute name="selected_station" value="#{teststation.selectedStation}" />
<f:selectItems value="#{teststation.list_Station}" var="entry1" itemValue="#{entry1}" itemLabel="#{entry1.nom_stat}" />
<f:converter converterId="StationConverter" />
</p:selectOneMenu>
</p:panel>
</td>
</tr>
<tr>
<td><h:outputLabel value="Immatriculation:" for="imma"></h:outputLabel> </td>
<td><p:inputText size="20" value="#{teststation.immatriculation}" id="imma"></p:inputText></td>
</tr>
<tr>
<p:growl id="growl" life="2000" />
<td></td>
<td><p:commandButton value="Valider" id="valide" update="errorMessages" actionListener="#{teststation.addOdm}" styleClass="ui-priority-primary" />
</td>
</tr>
</table>
</h:form>
</h:body>
</html>
the ManagedBean
#ViewScoped
#ManagedBean(name = "teststation")
public class TestStation {
private String matricule;
private stationService stationService = new stationServiceImpl();
private clientService clientService = new clientServiceImpl();
public static Logger log = LogManager.getLogger(CreerIntervention.class.getName());
private String nom;
private String client_name;
private List<client> list_client;
private List<station> list_Station;
private List<SelectItem> clientList;
//private Map<String, String> clientList;
//private Map<String, String> stationList;
private List<SelectItem> stationList;
private String immatriculation;
private String ref_Selected_client;
private String Nom_Selected_client;
private String ref_Selected_station;
private String Nom_Selected_station;
private List<station> station;
private station selectedStation;
private client Selected_client;
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
Map<String, String> selectedStationParam= fc.getExternalContext().getRequestParameterMap();
#PostConstruct
public void initMyBean()
{
log.info("ici PosteConstract"+this.getClass().hashCode());
}
public TestStation()
{
super();
log.info("ici Constract "+this.getClass().hashCode());
}
{
list_client = clientService.findAll();
}
public void updateSelectedStation()
{
log.info("LES updateSelectedStatio ---"+ list_Station.get(0).getNom_stat());
}
public void getStructureByClient()
{
log.info("La refernce du client selectioné est --- "+ Selected_client.getRef());
list_Station=stationService.findByRefClient(getSelected_client().getRef());
stationList= new ArrayList<>();
for (station o : list_Station)
{
stationList.add(new SelectItem(o.getNom_stat(),o.getRef_stat()));
}
log.info("LES STIONS SONT D UN NBR DE ---"+ list_Station.get(0).getNom_stat());
}
public void addOdm()
{ Nom_Selected_station=selectedStation.getNom_stat();
//log.info("num_odm :" + num_odm) ;
log.info("Matricule:" + matricule) ;
log.info("client:"+Selected_client.getNom_client()) ;
log.info("station:"+ Nom_Selected_station);
log.info("imma:"+ immatriculation) ;
}
public void addMessage(String summary) {
FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary, null);
FacesContext.getCurrentInstance().addMessage(null, message);
}
public void cancelAction(ActionEvent e)
{
log.info("etat valeur ShowForm555 = ");
}
public String getMatricule() {
return matricule;
}
public void setMatricule(String matricule) {
this.matricule = matricule;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getNom_Selected_client() {
return Nom_Selected_client;
}
public void setNom_Selected_client(String nom_Selected_client) {
Nom_Selected_client = nom_Selected_client;
}
public String getRef_Selected_client() {
return ref_Selected_client;
}
public void setRef_Selected_client(String Ref_Selected_client) {
this.ref_Selected_client = Ref_Selected_client;
}
public String getClient_name() {
return client_name;
}
public void setClient_name(String client_name) {
this.client_name = client_name;
}
/*public Map<String, String> getClientList() {
return clientList;
}
public void setClientList(Map<String, String> clientList) {
this.clientList = clientList;
}
public List<client> getList_client() {
return list_client;
}
public void setList_client(List<client> list_client) {
this.list_client = list_client;
}*/
public String getImmatriculation() {
return immatriculation;
}
public void setImmatriculation(String immatriculation) {
this.immatriculation = immatriculation;
}
public List<station> getStation() {
return station;
}
public void setStation(List<station> station) {
this.station = station;
}
/*public List<station> getList_Station() {
return list_Station;
}
public void setList_Station(List<station> list_Station) {
this.list_Station = list_Station;
}*/
/*public Map<String, String> getStationList() {
return stationList;
}
public void setStationList(Map<String, String> stationList) {
stationList = stationList;
}*/
public void setClientList(List<SelectItem> clientList) {
this.clientList = clientList;
}
public List<SelectItem> getStationList() {
return stationList;
}
public void setStationList(List<SelectItem> stationList) {
this.stationList = stationList;
}
public List<SelectItem> getClientList() {
return clientList;
}
public station getSelectedStation() {
return selectedStation;
}
public void setSelectedStation(station selectedStation) {
this.selectedStation = selectedStation;
}
public client getSelected_client() {
return Selected_client;
}
public void setSelected_client(client selected_client) {
Selected_client = selected_client;
}
public List<client> getList_client() {
return list_client;
}
public void setList_client(List<client> list_client) {
this.list_client = list_client;
}
public List<station> getList_Station() {
return list_Station;
}
public void setList_Station(List<station> list_Station) {
this.list_Station = list_Station;
}
public String getRef_Selected_station() {
return ref_Selected_station;
}
public void setRef_Selected_station(String ref_Selected_station) {
this.ref_Selected_station = ref_Selected_station;
}
public String getNom_Selected_station() {
return Nom_Selected_station;
}
public void setNom_Selected_station(String nom_Selected_station) {
Nom_Selected_station = nom_Selected_station;
}
}
the StationConverter
#FacesConverter("StationConverter")
public class StationConverter implements Converter {
public static Logger log = LogManager.getLogger(StationConverter.class.getName());
stationService statServ = new stationServiceImpl();
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
log.info("4- submitted value for Station Converter ********** "+submittedValue);
log.info("5- returned Object for Station Converter ********** "+statServ.findByRef(submittedValue).getNom_stat());
return statServ.findByRef(submittedValue);
} catch (NumberFormatException exception) {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Client ID"));
}}
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
log.info(modelValue.getClass());
if (modelValue instanceof station ) {
log.info( "6- la valeur en String Converter Station est ****** "+String.valueOf(((station) modelValue).getNom_stat()));
return String.valueOf(((station) modelValue).getRef_stat());
} else {
throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Station instance"));
}
}
}
I'm trying to write some simple login page in JSF and I don't really understand the converter class. I have this error when I try to login:
JSF - java.lang.NumberFormatException: For input string: ""
My controller class:
#ManagedBean(name="main")
#SessionScoped
#PersistenceContext(name = "persistence/LogicalName", unitName = "ProjectPU")
public class MainController {
private EntityManager em;
#Resource
private javax.transaction.UserTransaction utx;
#PersistenceUnit(unitName="ProjectPU")
private EntityManagerFactory emf;
/**
* Creates a new instance of MainController
*/
Users user = new Users();
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
private EntityManager getEntityManager()
{
return emf.createEntityManager();
}
public MainController() {
}
public String signin()
{
EntityManager em = getEntityManager();
TypedQuery<Users> query = em.createNamedQuery("Users.findByLogin", Users.class);
query.setParameter("login", user.getLogin());
Users result = null;
try{
result = query.getSingleResult();
} catch(javax.persistence.NoResultException a){
}
if (result != null) {
if(result.getPassword().equals(user.getPassword())){
Util.getSession().setAttribute("login", user.getLogin());
return "index.xhtml";
}
} else {
return "signin.xhtml";
}
return "index.xhtml";
}
public Object findUser(Integer id) {
EntityManager em = getEntityManager();
try {
Users u = (Users) em.find(Users.class, id);
return u;
} finally {
em.close();
}
}
}
My converter class:
#FacesConverter("Converters.UsersConverter")
public class UsersConverter implements Converter
{
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
if (!value.equals("null"))
{
Integer id = new Integer(value);
MainController controller = (MainController) context.getApplication().getELResolver().getValue(
context.getELContext(), null, "main");
return controller.findUser(id);
}
else
{
return null;
}
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value)
{
if (value == null) {
return null;
}
if(value instanceof Users)
{
Users u = (Users) value;
return "" + u.getId();
}
else
{
throw new IllegalArgumentException("object:" + value + " of type:" + value.getClass().getName() + "; expected type: Users");
}
}
}
and my view(Index 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:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<table>
<h:inputHidden value="#{main.user}" immediate="true"/>
<tr><td>Login:</td><td><h:inputText id="login" value="# {main.user.login}"/></td></tr>
<tr><td>Password:</td><td><h:inputSecret id="password" value="#{main.user.password}"/></td></tr>
</table>
<h:commandButton id="submit" value="Signin" action="#{main.signin()}"/>
</h:form>
</h:body>
</html>
I created database I have there a table User and I added one user and I cant login. On debugger I can see null values in my converter in both methods(getasobject and getasstring).
I am very new to JSF and was trying to implement a pagination using <ui:repeat>. I am using the #ViewScoped but currently my state is not saved. Every time the backing bean resets the page information and the next page is not displayed. Attaching the source code for reference.
WorkItemList.xhtml
<?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">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jsp/jstl/core"
template="/WEB-INF/template/default.xhtml">
<ui:define name="content">
<h:form id="form">
<ui:repeat value="#{repeatPaginator.model}" var="listItem">
<div>
<h:outputText value="#{listItem}"/>
</div>
</ui:repeat>
<h:commandButton value="< prev" action="#{repeatPaginator.prev}"/>
<h:outputText value="#{repeatPaginator.pageIndex} / #{repeatPaginator.pages}"/>
<h:commandButton value="next >" action="#{repeatPaginator.next}"/>
<h:inputHidden value="#{repeatPaginator.pageIndex}"/>
</h:form>
</ui:define>
</ui:composition>
Backing Bean - RepeatPaginator.java
package test;
#ManagedBean
#ViewScoped
public class RepeatPaginator implements Serializable{
private static final long serialVersionUID = 1L;
private static final int DEFAULT_RECORDS_NUMBER = 2;
private static final int DEFAULT_PAGE_INDEX = 1;
private TestDelegate delegate;
private int records;
private int recordsTotal;
private int pageIndex;
private int pages;
private List<String> model;
public RepeatPaginator() {
delegate = new TestDelegate();
this.records = DEFAULT_RECORDS_NUMBER;
this.pageIndex = DEFAULT_PAGE_INDEX;
// Get Model
this.model = delegate.fetchCurrentList(getFirst(), getFirst()+records);
this.recordsTotal = delegate.getListSize();
if (records > 0) {
pages = records <= 0 ? 1 : recordsTotal / records;
if (recordsTotal % records > 0) {
pages++;
}
if (pages == 0) {
pages = 1;
}
} else {
records = 1;
pages = 1;
}
updateModel();
}
public void updateModel() {
int fromIndex = getFirst();
int toIndex = getFirst() + records;
if(toIndex > this.recordsTotal) {
toIndex = this.recordsTotal;
}
setModel(delegate.fetchCurrentList(fromIndex, toIndex));
}
public void next() {
if(this.pageIndex < pages) {
this.pageIndex++;
}
updateModel();
}
public void prev() {
if(this.pageIndex > 1) {
this.pageIndex--;
}
updateModel();
}
public int getRecords() {
return records;
}
public int getRecordsTotal() {
return recordsTotal;
}
public int getPageIndex() {
return pageIndex;
}
public int getPages() {
return pages;
}
public int getFirst() {
return (pageIndex * records) - records;
}
public List<String> getModel() {
if(model==null)
updateModel();
return model;
}
public void setModel(List<String> model) {
this.model = model;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
}
Delegate - TestDelegate.java
#ViewScoped
public class TestDelegate {
private List<String> list = new ArrayList<String>();
public TestDelegate()
{
this.list.add("Item 1");
this.list.add("Item 2");
this.list.add("Item 3");
this.list.add("Item 4");
this.list.add("Item 5");
this.list.add("Item 6");
this.list.add("Item 7");
this.list.add("Item 8");
this.list.add("Item 9");
this.list.add("Item 10");
this.list.add("Item 11");
}
public List<String> fetchCurrentList(int from, int to)
{
return list.subList(from, to);
}
public int getListSize()
{
return this.list.size();
}
}
The #ViewScoped bean is not "magically present all the time". At the end of the request, it's values will be serialized and the bean is destructed.
This causes a Re-Construct of the bean at the beginning of the next request (click on next). Your Container will take care to deserialize the stored values again, in order to return the actual State of the bean. BUT: This happens after Bean-Construction, meaning when you try to use the values within the Constructor of the bean, nothing is restored.
Move your logic into a method that you annotate with #PostConstruct - then all values will be loaded and you can fetch the correct result. The container will call the method annotated with #PostConstruct once it restored the prior state of the bean.
This becomes important when you start to use ManagedProperties or CDI-Injections.
public RepeatPaginator() {
//no serialized data available here, Good location to initialize some stuff
//that is independent.
delegate = new TestDelegate();
this.records = DEFAULT_RECORDS_NUMBER;
this.pageIndex = DEFAULT_PAGE_INDEX;
}
#PostConstruct
public void init() {
//Here the ViewScoped values are restored. We can start to use them.
// Get Model
this.model = delegate.fetchCurrentList(getFirst(), getFirst()+records);
this.recordsTotal = delegate.getListSize();
if (records > 0) {
pages = records <= 0 ? 1 : recordsTotal / records;
if (recordsTotal % records > 0) {
pages++;
}
if (pages == 0) {
pages = 1;
}
} else {
records = 1;
pages = 1;
}
updateModel();
}
I am new for prime face. I had a checkbox and textbox value on dataTable.And dataTable will load data from database. Please see my code below
text.xhtml
<?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:c="http://java.sun.com/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<ui:composition template="../templates/layout.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:event type="preRenderView" listener="#{kooBean.initEdit}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h:form prependId="false" id="growlForm">
<p:growl id="growl" showDetail="#{applicationBean.isShowDetailMessage()}" />
</h:form>
<h:form id="form">
<p:dataTable id="list" value="#{kooBean.model}" lazy="true" var="kooTable"
rendered="#{kooBean.dataVisible}" paginatorTemplate=" {CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="5,10,25,50" rows="10" sortBy="#{kooTable.id}" selection="#{kooBean.selectedCars}"
rowKey=" #{kooTable.id}">
<f:facet name="header">
Checkbox Based Selection
</f:facet>
<p:column selectionMode="multiple" style="width:10%;text-align:center" />
<p:column headerText="Description" >
#{kooTable.description}
<p:inputText value=" #{kooTable.param_str}" />
</p:column>
<f:facet name="footer">
<p:commandButton id="multiViewButton" value="View" icon="ui-icon-search"
update=":form:displayMulti" oncomplete="multiCarDialog.show()"/>
</f:facet>
</p:dataTable>
</h:form>
</ui:define>
</ui:composition>
</html>
bean.java
package my.com.mesiniaga.sphere.web;
import static my.com.mesiniaga.sphere.domain.KooPredicate.nameLike;
import my.com.mesiniaga.sphere.domain.KooTable;
import java.util.Date;
import java.util.List;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.primefaces.model.LazyDataModel;
import org.springframework.roo.addon.jsf.managedbean.RooJsfManagedBean;
import org.springframework.roo.addon.serializable.RooSerializable;
import my.com.mesiniaga.sphere.service.KooService;
import my.com.mesiniaga.sphere.service.QueryDslSupport;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.Date;
import com.mysema.query.types.Predicate;
#RooSerializable
#RooJsfManagedBean(entity = KooTable.class, beanName = "kooBean")
public class KooBean {
private KooTable kooTable = new KooTable();
private String attribute;
private List<String> cols;
public String userId;
public String emailNotification;
private boolean addGroup = false;
private boolean editGroup = false;
private boolean addGroupUser = false;
private KooTable selectedCar;
private KooTable[] selectedCars;
private final LazyDataModel<KooTable> model = new AbstractQueryDslJpaLazyDataModel<KooTable>() {
#Override
public Predicate getPredicate(){
// LOG.info(getKooTable().getName());
return nameLike(getKooTable().getDescription());
}
//
#Override
public QueryDslSupport<KooTable> getQueryDslSupport(){
return kooService;
}
};
public LazyDataModel<KooTable> getModel() {
return model;
}
public String getUserId() {
return userId;
}
//
// public void setUserId(String userId) {
// this.userId = userId;
// }
public String getEmailNotification() {
return emailNotification;
}
//
// public void setEmailNotification(String emailNotification) {
// this.emailNotification = emailNotification;
// }
public List<String> getCols() {
return cols;
}
public void setCols(List<String> cols) {
this.cols = cols;
}
public String getAttribute() {
return attribute;
}
public void setAttribute(String attribute) {
this.attribute = attribute;
}
public boolean isAddGroup() {
return addGroup;
}
public void setAddGroup(boolean addGroup) {
this.addGroup = addGroup;
}
public boolean isEditGroup() {
return editGroup;
}
public void setEditGroup(boolean editGroup) {
this.editGroup = editGroup;
}
public boolean isAddGroupUser() {
return addGroupUser;
}
public void setAddGroupUser(boolean addGroupUser) {
this.addGroupUser = addGroupUser;
}
public void initCreatePage() {
//Initialize user group listing page
cols = new ArrayList<String>();
cols.add("id");
cols.add("description");
// displayGroupsList();
if (!FacesContext.getCurrentInstance().isPostback()) {
// if (FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("edit") != null) {
// LOG.info("EDIT....");
// attribute = FacesContext.getCurrentInstance().getExternalContext().getRequestHeaderMap().get("referer");
// initEdit();
// editGroup = true;
// } else if (FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("create") != null) {
// LOG.info("CREATE....");
// addGroup = true;
// }
}
}
//
// public String displayGroupsList() {
// findAllGroupses();
// return LIST_NAVIGATION_PAGE;
// }
//
// public String cancelCreateGroup(){
// return LIST_NAVIGATION_PAGE;
// }
//
// public String createGroup() {
// String message = "";
// try {
//
// if (groups.getId() != null) {
// //submit response inquiry
//
// groupsService.responseInquiry(groups);
// message = "message_successfully_updated";
// } else {
// groups.setDescription("none");
// groups.setUpdatedby(1L);
// groups.setUpdatedon(new Date());
// groupsService.create(groups);
// message = "message_successfully_created";
// }
// } catch (NestedRuntimeException e) {
// LOG.error(e.getMostSpecificCause().getMessage(), e);
// message = "Failed to update";
// FacesMessage facesMessage = new FacesMessage(message);
// facesMessage.setDetail(e.getMostSpecificCause()
// .getLocalizedMessage());
// FacesContext.getCurrentInstance().addMessage(null, facesMessage);
// return null;
// }
// FacesMessage facesMessage = MessageFactory.getMessage(message,
// "groups");
// FacesContext.getCurrentInstance().addMessage(null, facesMessage);
// // FacesContext.getCurrentInstance().getExternalContext().getFlash().setKeepMessages(true);
//// reset();
// return LIST_NAVIGATION_PAGE;
// }
public void initEdit() {
System.out.println("init edit !");
// String groupId = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("groupId");
// if (groupId != null) {
// addGroupUser = true;
// groupsWithTask = groupsService.findGroupsWithTask(Long.valueOf(groupId));
// groups = groupsWithTask.getGroups();
// if (groupsWithTask.getTask() != null) {
// LOG.info("task name = " + groupsWithTask.getTask().getName());
// }
// }
}
public boolean isDataVisible() {
return true;
}
// public Car[] getSelectedCars() {
// return selectedCars;
// }
// public void setSelectedCars(Car[] selectedCars) {
// this.selectedCars = selectedCars;
// }
public KooTable[] getSelectedCars() {
return selectedCars;
}
public void setSelectedCars(KooTable[] selectedCars) {
this.selectedCars = selectedCars;
}
public KooTable getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(KooTable selectedCar) {
this.selectedCar = selectedCar;
}
}
Here is my question.When I click view button, I need to get every row of value including checkbox value whether checkbox is checked or nt then update to database. Is it possible?
I'm still on the road of learning JSF. I have an IceFaces tree with an IceFaces commandLink to try to download a file. So far this is my xhtml and my backing bean. When I click the commandLink it just prints the two messages and then it does nothing and it does not show any warning any error at all... How to know what's happening? What am I missing?
Cheers
XHTML
<?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:ice="http://www.icesoft.com/icefaces/component">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<ice:tree id="tree"
value="#{treeBean.model}"
var="item"
hideNavigation="false"
hideRootNode="false"
imageDir="./images/">
<ice:treeNode>
<f:facet name="icon">
<ice:panelGroup style="display: inline">
<h:graphicImage value="#{item.userObject.icon}"/>
</ice:panelGroup>
</f:facet>
<f:facet name="content">
<ice:panelGroup style="display: inline">
<ice:commandLink action="#{treeBean.doDownload(item.userObject.fileAbsolutePath)}">
<ice:outputText value="#{item.userObject.text}"/>
</ice:commandLink>
</ice:panelGroup>
</f:facet>
</ice:treeNode>
</ice:tree>
</h:form>
</h:body>
</html>
BEAN
#ManagedBean
#ViewScoped
public class TreeBean implements Serializable {
private final DefaultTreeModel model;
/** Creates a new instance of TreeBean */
public TreeBean() {
// create root node with its children expanded
DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
IceUserObject rootObject = new IceUserObject(rootTreeNode);
rootObject.setText("Root Node");
rootObject.setExpanded(true);
rootObject.setBranchContractedIcon("./images/tree_folder_close.gif");
rootObject.setBranchExpandedIcon("./images/tree_folder_open.gif");
rootObject.setLeafIcon("./images/tree_document.gif");
rootTreeNode.setUserObject(rootObject);
// model is accessed by by the ice:tree component via a getter method
model = new DefaultTreeModel(rootTreeNode);
// add some child nodes
for (int i = 0; i < 3; i++) {
DefaultMutableTreeNode branchNode = new DefaultMutableTreeNode();
FileSourceUserObject branchObject = new FileSourceUserObject(branchNode);
branchObject.setText("SteveJobs.jpg");
branchObject.setFileAbsolutePath("/Users/BRabbit/Downloads/SteveJobs.jpg");
branchObject.setBranchContractedIcon("./images/tree_folder_close.gif");
branchObject.setBranchExpandedIcon("./images/tree_folder_open.gif");
branchObject.setLeafIcon("./images/tree_document.gif");
branchObject.setLeaf(true);
branchNode.setUserObject(branchObject);
rootTreeNode.add(branchNode);
}
}
public DefaultTreeModel getModel() {
return model;
}
public void doDownload(String fileAbsolutePath) {
System.out.println(fileAbsolutePath);
File file = new File(fileAbsolutePath);
if(file.exists())
System.out.println("Yes"); //It exists !
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
externalContext.setResponseHeader("Content-Type", externalContext.getMimeType(file.getName()));
externalContext.setResponseHeader("Content-Length", String.valueOf(file.length()));
externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"" + file.getName() + "\"");
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(file);
output = externalContext.getResponseOutputStream();
IOUtils.copy(input, output);
} catch (FileNotFoundException ex) {
Logger.getLogger(TreeBean.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(TreeBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
}
facesContext.responseComplete();
}
}
Bean's object
public class FileSourceUserObject extends IceUserObject{
String fileAbsolutePath;
public FileSourceUserObject(DefaultMutableTreeNode wrapper) {
super(wrapper);
}
public String getFileAbsolutePath(){
return fileAbsolutePath;
}
public void setFileAbsolutePath(String fileAbsolutePath){
this.fileAbsolutePath = fileAbsolutePath;
}
}
Finally I did it!
Here's some code that allows the user to see a tree (of Files) and download them.
XHTML
<ice:tree id="tree"
value="#{treeBean.model}"
var="item"
hideNavigation="false"
hideRootNode="false"
imageDir="./images/">
<ice:treeNode>
<f:facet name="icon">
<ice:panelGroup style="display: inline">
<h:graphicImage value="#{item.userObject.icon}"/>
</ice:panelGroup>
</f:facet>
<f:facet name="content">
<ice:panelGroup style="display: inline-block">
<ice:outputResource resource="#{item.userObject.resource}"
fileName="#{item.userObject.text}"
shared="false"/>
</ice:panelGroup>
</f:facet>
</ice:treeNode>
</ice:tree>
BACKING BEAN
#ManagedBean
#ViewScoped
public class TreeBean implements Serializable {
private final DefaultTreeModel model;
public TreeBean() {
DefaultMutableTreeNode rootTreeNode = new DefaultMutableTreeNode();
FileSourceUserObject rootObject = new FileSourceUserObject(rootTreeNode);
rootObject.setText("Root Node");
rootObject.setExpanded(true);
rootObject.setBranchContractedIcon("./images/tree_folder_close.gif");
rootObject.setBranchExpandedIcon("./images/tree_folder_open.gif");
rootTreeNode.setUserObject(rootObject);
// model is accessed by by the ice:tree component via a getter method
model = new DefaultTreeModel(rootTreeNode);
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
// add some child nodes
for (int i = 0; i < 3; i++) {
DefaultMutableTreeNode branchNode = new DefaultMutableTreeNode();
FileSourceUserObject branchObject = new FileSourceUserObject(branchNode);
branchObject.setText("Test.jpg");
branchObject.setResource(new SRCResource("/<filePath>/Test.jpg"));
branchObject.setBranchContractedIcon("./images/tree_folder_close.gif");
branchObject.setBranchExpandedIcon("./images/tree_folder_open.gif");
branchObject.setLeafIcon("./images/tree_document.gif");
branchObject.setLeaf(true);
branchNode.setUserObject(branchObject);
rootTreeNode.add(branchNode);
}
}
public DefaultTreeModel getModel() {
return model;
}
}
SRCResource
public class SRCResource implements Resource {
private String fileAbsolutePath;
private final Date lastModified;
public SRCResource(String fileAbsolutePath) {
this.fileAbsolutePath = fileAbsolutePath;
this.lastModified = new Date();
}
#Override
public String calculateDigest() {
return "No lo calcularé jamás !!";
}
#Override
public InputStream open() throws IOException {
return (InputStream)(new FileInputStream(fileAbsolutePath));
}
#Override
public Date lastModified() {
return lastModified;
}
#Override
public void withOptions(Options optns) throws IOException {
}
public String getFileAbsolutePath() {
return fileAbsolutePath;
}
public void setFileAbsolutePath(String fileAbsolutePath) {
this.fileAbsolutePath = fileAbsolutePath;
}
}
Web.xml
Add the following
<servlet>
<servlet-name>Resource Servlet</servlet-name>
<servlet-class>com.icesoft.faces.webapp.CompatResourceServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Resource Servlet</servlet-name>
<url-pattern>/xmlhttp/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/icefaces/*</url-pattern>
</servlet-mapping>
And that's it ! Simply adapt the code to your needs !
Cheers !
More info on http://wiki.icefaces.org/display/ICE/Adding+ICEfaces+to+Your+Application