Shopping Cart does not display updated info - jsf-2

I'm using WildFly 9.0 and IntelliJ 14 Ultimate
I can add items to the cart- and they can be viewed using a PrimeFaces data table on ViewCart.xhtml
There is a button to delete each cart item- which works.
Faces-config has been edited to return back to the ViewCart.xhtml page when the button is clicked; which seems to be the case.
The PROBEM: Cart is still showing the original list, before the item was deleted.
If I go to the product catalogue and return back to ViewCart.xhtml, the executed changes are reflected in the cart. Please can someone help?
Here is the ViewCart.xhtml page
<body>
<h:outputText value="Cart List"
style="font-family: Verdana, Helvetica, sans-serif;font-size: 18px; font-weight: 900;" />
<h:form name="ViewProductsManagedBean">
<p:dataTable id="cartTable" var="cartList"
value="#{ViewProductsManagedBean.cart}" <p:column>
<f:facet name="header">
<h:outputText value="Delete Cart Item "
style="font-family: Verdana, Helvetica, sans-serif;font-size: 16px;" />
</f:facet>
<h:commandButton action="#{ViewProductsManagedBean.removeItemFromCart(cartList.itemcode)}"> </h:commandButton>
</p:column>
</f:facet>
</p:dataTable>
</h:form>
</body>
</html>
now the managed bean:
#ManagedBean(name="ViewProductsManagedBean")
#RequestScoped
public class ViewProductsManagedBean {
public String removeItemFromCart(String itemCode){
return cartFunctions.removeItemFromCart(itemCode);
}
}
The facade that "talks" to the business logic
#Stateful
#SessionScoped
public class CartFacade {
public String removeItemFromCart(String itemCode){
return cartBean.removeItemFromCart(itemCode);
}
}
The cart been looks like follows:
#Stateful
#Local(ShoppingCartLocal.class)
#Remote(ShoppingCart.class)
#SessionScoped
public class ShoppingCartBean implements ShoppingCartLocal, ShoppingCart {
public String removeItemFromCart(String itemCode){
for(Orderitem ord:cartItems){
if(itemCode.equals(ord.getItemcode())){
cartItems.remove(ord);
System.out.println("Item removed " + itemCode);
}
}
return "ViewCart";
}
here is the full cart bean
package com.shop.cart;
/**
* Created by LalinPethiyagoda on 30/07/2015.
*/
#Stateful
#Local(ShoppingCartLocal.class)
#Remote(ShoppingCart.class)
#SessionScoped
public class ShoppingCartBean implements ShoppingCartLocal, ShoppingCart {
#PersistenceContext(unitName ="Shop")
private EntityManager cartEntityManager;
private CustomerManager customerManagerBean;
private CopyOnWriteArrayList<Orderitem> cartItems = new CopyOnWriteArrayList<>();
private List<Orderitem> cartItemsReturn = new ArrayList<>();
public void setCartItems(CopyOnWriteArrayList<Orderitem> cartItems) {
this.cartItems = cartItems;
}
private CustomerEntity customer;
public ShoppingCartBean(){}
#Override
public List<Orderitem> getCartItemsReturn() {
return cartItemsReturn;
}
public void setCartItemsReturn(List<Orderitem> cartItemsReturn) {
this.cartItemsReturn = cartItemsReturn;
}
#Override
public boolean addCartItem(ProductEntity product, int quantityPurchased){
com.shop.entity.Orderitem basketItem=new Orderitem();
Locale currentLocale = new Locale("en", "GB");
double subTotal;
// check for duplicate entry.
for (Orderitem itemsIntheCart : cartItems) {
if (itemsIntheCart.getItemcode().equals(product.getItemcode())) {
return false;
}
}
basketItem.setItemcode(product.getItemcode());
basketItem.setItemdescription(product.getItemdescription());
basketItem.setUnitprice(product.getUnitprice());
basketItem.setQuantitypurchased(quantityPurchased);
subTotal = quantityPurchased * basketItem.getUnitprice();
Double currencyAmount = new Double(subTotal);
NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(currentLocale);
currencyFormatter.format(currencyAmount);
basketItem.setSubtotal(currencyAmount);
cartItems.add(basketItem);
return true;
}
public String removeItemFromCart(String itemCode){
for(Orderitem ord:cartItems){
if(itemCode.equals(ord.getItemcode())){
cartItems.remove(ord);
System.out.println("Item removed " + itemCode);
}
}
return "ViewCart";
}
#Override
public CopyOnWriteArrayList<Orderitem> viewCartItems(){
return this.cartItems;
}
#Override
public CopyOnWriteArrayList<Orderitem> getCartItems(){
CopyOnWriteArrayList<Orderitem> cartItemList = this.cartItems;
for(Orderitem x:cartItemList){
System.out.println(x.getItemdescription());
}
return cartItemList;
}
public CustomerEntity getCustomer() {
return customer;
}
public void setCustomer(CustomerEntity customer) {
this.customer = customer;
}
public void removeCartItem(int itemCode){
System.out.println("hello");
}
#Override
public double getTotal(){
double total=0;
for(Orderitem bItem:getCartItems()){
total = total + bItem.getSubtotal();
}
return total;
}
#PreDestroy
public void exit(){
persistCartItems();
stopSession();
}
#Override
public void persistCartItems() {
// TODO Auto-generated method stub
}
#Remove
public void stopSession(){
System.out.println("saved- all done - object detached from object pool");
}
public void assignCartToCustomer(){
customer = customerManagerBean.getVerifiedCustomer();
}
public CustomerEntity getCustomerAssociatedWithTheCart(){
return this.customer;
}
#Remove
public void remove() {
cartItems = null;
}
#Override
public void incrementQuantity() {
}
#Override
public void decrementQuantity() {
}
}

Related

struts2 jquery grid data not loaded when implements model driven

My web application not loading data when I implements model driven in action class. It works fine when remove modeldriven.
action class :
package action;
import action.UserBean;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import service.OrganisationBo;
import model.AtDivision;
import model.AtOrganisation;
public class OraganisationAction extends ActionSupport implements ModelDriven<UserBean> {
private String uname;
private String passwd;
private String sidx;
// Search Field
private String searchField;
// The Search String
private String searchString;
// he Search Operation ['eq','ne','lt','le','gt','ge','bw','bn','in','ni','ew','en','cn','nc']
private String searchOper;
// Your Total Pages
private Integer total = 0;
//Your result List
private List<UserBean> gridModel;
//get how many rows we want to have into the grid - rowNum attribute in the grid
private Integer rows = 0;
//Get the requested page. By default grid sets this to 1.
private Integer page = 0;
// sorting order - asc or desc
private String sord;
private boolean loadonce = false;
// All Record
private Integer records = 0;
private String includepage;
private List<UserBean> myList;
private String oper;
private String id;
private String contact;
private String country;
UserBean ubs = new UserBean();
private AtOrganisation org = new AtOrganisation();
private AtDivision div = new AtDivision();
private List<AtOrganisation> orglist = new ArrayList<AtOrganisation>();
OrganisationBo orgBo;
private String aoId;
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getSidx() {
return sidx;
}
public void setSidx(String sidx) {
this.sidx = sidx;
}
public String getSearchField() {
return searchField;
}
public void setSearchField(String searchField) {
this.searchField = searchField;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getSearchOper() {
return searchOper;
}
public void setSearchOper(String searchOper) {
this.searchOper = searchOper;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
public List<UserBean> getGridModel() {
return gridModel;
}
public void setGridModel(List<UserBean> gridModel) {
this.gridModel = gridModel;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public String getSord() {
return sord;
}
public void setSord(String sord) {
this.sord = sord;
}
public boolean isLoadonce() {
return loadonce;
}
public void setLoadonce(boolean loadonce) {
this.loadonce = loadonce;
}
public Integer getRecords() {
return records;
}
public void setRecords(Integer records) {
this.records = records;
}
public String getIncludepage() {
return includepage;
}
public void setIncludepage(String includepage) {
this.includepage = includepage;
}
public List<UserBean> getMyList() {
return myList;
}
public void setMyList(List<UserBean> myList) {
this.myList = myList;
}
public String getOper() {
return oper;
}
public void setOper(String oper) {
this.oper = oper;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public List<AtOrganisation> getOrglist() {
return orglist;
}
public void setOrglist(List<AtOrganisation> orglist) {
this.orglist = orglist;
}
public String getAoId() {
return aoId;
}
public void setAoId(String aoId) {
this.aoId = aoId;
}
public void setOrgBo(OrganisationBo orgBo) {
this.orgBo = orgBo;
}
public AtDivision getDiv() {
return div;
}
public void setDiv(AtDivision div) {
this.div = div;
}
public AtOrganisation getOrg() {
return org;
}
public void setOrg(AtOrganisation org) {
this.org = org;
}
public String execute() throws Exception {
myList = DAO.buildList();
setRecords(DAO.count());
int to = (getRows() * getPage());
int from = to - getRows();
if (to > getRecords()) {
to = getRecords();
}
if (loadonce) {
setGridModel(myList);
} else {
if (searchString != null && searchOper != null && !searchString.equals("") && !searchOper.equals("")) {
System.out.println("Searching within Database");
if (searchOper.equalsIgnoreCase("cn")) {
// setGridModel(DAO.findbyName(searchString));
}
} else {
System.out.println("Not Searching Anywhere");
//setGridModel(DAO.find(from, to));
System.out.println("dili 4444");
setGridModel(myList);
}
}
total = (int) Math.ceil((double) getRecords() / (double) getRows());
System.out.println("tot " + total);
System.out.println(gridModel.size());
return SUCCESS;
}
#Override
public UserBean getModel() {
return ubs;
}
}
Struts.xml :
<package name="default" extends="struts-default,json-default">
<action name="gridaction" class="action.OraganisationAction" >
<result name="success" type="json"/>
</action>
</package>
</struts>
index.jsp :
<%--
Document : index
Created on : 15 Nov, 2011, 11:45:45 PM
Author : XCoder
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags" %>
<%#taglib prefix="sj" uri="/struts-jquery-tags" %>
<%#taglib prefix="sjg" uri="/struts-jquery-grid-tags" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<sj:head jquerytheme="start" jqueryui="true"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<s:url id="remoteurl" action="gridaction"/>
<sjg:grid
id="sjgrid"
caption="Grid Model"
dataType="json"
href="%{remoteurl}"
pager="true"
rowList="10,20,100"
rowNum="5"
navigator="true"
width="999"
navigatorSearchOptions="{sopt:['eq','ne','lt','gt']}"
navigatorAddOptions="{height:280,reloadAfterSubmit:true}"
navigatorEditOptions="{height:280,reloadAfterSubmit:false}"
navigatorEdit="false"
navigatorView="false"
navigatorDelete="true"
navigatorDeleteOptions="{height:280,reloadAfterSubmit:true}"
gridModel="gridModel"
editurl="%{editurl}"
editinline="true"
onSelectRowTopics="rowselect"
>
<sjg:gridColumn name="iduser" formatter="integer" title="iduser" key="true" hidden="true"/>
<sjg:gridColumn name="uname" title="Username" editable="true" align="center"
editrules="{required:true}"
/>
<sjg:gridColumn name="passwd" title="Password" editable="true" align="center"
editrules="{required:true}"
/>
<sjg:gridColumn name="country" title="Country" editable="true" align="center"
edittype="select"
editoptions="{dataUrl:'%{selecturl}'}"
/>
<sjg:gridColumn name="contact" title="Contact No" editable="true" align="center"
editrules="{required:true,number:true,integer:true}"
/>
</sjg:grid>
</body>
</html>
cant we implement model driven with jqgrid or my code is wrong?
EDIT:
Just figure out that modeldriven work fine with old lib set
struts2-convention-plugin-2.1.8,
struts2-core-2.1.8.1,
struts2-jquery-grid-plugin-2.5.0,
struts2-jquery-plugin-2.5.0,
struts2-json-plugin-2.1.8,
xwork-core-2.1.6.
But when I update project into new version of struts grid is not fill with data. New lib set is as follows :
struts2-convention-plugin-2.3.16,
struts2-core-2.3.16,
struts2-jquery-grid-plugin-3.7.1,
struts2-jquery-plugin-3.7.0 ,
struts2-json-plugin-2.3.16.3
xwork-core-2.3.16.
Anyone knows what happening here?

How to get the objects in the targetList of a rich:pickList?

I filled my rightList of the PickList with Objects from a web service, but when i select some elements, i want to get these elements in myManagedBean, because i'll affect them to an Object.
JSF :
<h:form>
<rich:panel>
<h:panelGrid columns="2" styleClass="criteresSaisie"
rowClasses="critereLigne" columnClasses="titreColonne,">
<h:outputLabel for="libelleCoplement" value=" "
size="20" />
<rich:pickList d="libelleCoplement" sourceCaption="Compléments"
targetCaption="Compléments sélectionnés"
value="#{listeCmpltDispoModel.listeCmpltSelect}" size="15"
addText=">" addAllText=">>" removeText="<"
removeAllText="<<" listWidth="270px" listHeight="110px"
orderable="true">
<f:converter converterId="cmpltsTitresConcerter" />
<f:selectItems value="#{listeCmpltDispoModel.listeCmpltDispo}"
var="liste" itemLabel="#{liste.libelleComplement}"
itemValue="#{liste.cdComplement}"/>
</rich:pickList>
</h:panelGrid>
<h:panelGroup>
<div align="right">
<h:panelGrid columns="8">
<h:commandButton value="Valider"
action="#{saisieCmpltsTitreCtrl.valider}" />
</h:panelGrid>
</div>
</h:panelGroup>
</rich:panel>
</h:form>
The bean :
#ManagedBean(name = "listeCmpltDispoModel")
#SessionScoped
public class ListeCmpltDispoModel implements Serializable {
private static final long serialVersionUID = 1L;
private Long cdComplement;
private String libelleComplement;
private int nbCompl;
private List<ComplementsDispoSortieDTO> listeCmpltDispo ;
private List<ComplementsDispoSortieDTO> listeCmpltSelect ;
public ListeCmpltDispoModel() {
}
public Long getCodeComplement() {
return cdComplement;
}
public void setCodeComplement(Long cdComplement) {
this.cdComplement = cdComplement;
}
public String getLibelleComplement1() {
return libelleComplement;
}
public void setLibelleComplement1(String libelleCoplement) {
this.libelleComplement = libelleCoplement;
}
public Long getCdComplement() {
return cdComplement;
}
public void setCdComplement(Long cdComplement) {
this.cdComplement = cdComplement;
}
public String getLibelleComplement() {
return libelleComplement;
}
public void setLibelleComplement(String libelleComplement) {
this.libelleComplement = libelleComplement;
}
public List<ComplementsDispoSortieDTO> getListeCmpltDispo() {
return listeCmpltDispo;
}
public void setListeCmpltDispo(List<ComplementsDispoSortieDTO> listeCmpltDispo) {
this.listeCmpltDispo = listeCmpltDispo;
}
public int getNbCompl() {
return nbCompl;
}
public void setNbCompl(int nbCompl) {
this.nbCompl = nbCompl;
}
public List<ComplementsDispoSortieDTO> getListeCmpltSelect() {
return listeCmpltSelect;
}
public void setListeCmpltSelect(List<ComplementsDispoSortieDTO> listeCmpltSelect) {
this.listeCmpltSelect = listeCmpltSelect;
}
}
Converter :
#FacesConverter(value="cmpltsTitresConcerter")
public class CmpltsTitresConcerter implements Converter {
#SuppressWarnings("null")
public Object getAsObject(FacesContext context, UIComponent component,
String value){
ComplementsDispoSortieDTO cmpltSelect = null;
cmpltSelect.setCdComplement(Long.parseLong(value));
return cmpltSelect;
}
public String getAsString(FacesContext arg0, UIComponent arg1, Object obj) {
return String.valueOf(((ComplementsDispoSortieDTO) obj).getCdComplement());
}
}
Any help is greatly apprectiated!
Roughtly you need 3 things :
Custom converter for your object (Object to String, String to Object)
Getter/Setter with the List of your Objects choices
Getter/Setter with the List of your Objects selected
Everything is perfectly described here : RichFaces Showcase - pickList
EDIT :
Adding this should fix your problem :
<rich:pickList ...>
<f:converter converterId="cmpltsTitresConcerter" />
</rich:pickList>
also the converter property in <f:selectItems /> is not valid : f:selectItems
EDIT :
You should modify your converter like that to remove converting exceptions :
#FacesConverter(value="cmpltsTitresConcerter")
public class CmpltsTitresConcerter implements Converter
{
public Object getAsObject(FacesContext context, UIComponent component, String value)
{
ComplementsDispoSortieDTO cmpltSelect = null;
if(value != null)
{
cmpltSelect = new ComplementsDispoSortieDTO();
cmpltSelect.setCdComplement(Long.parseLong(value));
}
return cmpltSelect;
}
public String getAsString(FacesContext arg0, UIComponent arg1, Object obj)
{
String result = null;
if(obj != null)
{
result = String.valueOf(((ComplementsDispoSortieDTO) obj).getCdComplement());
}
return result;
}
}
Your selected objects are bound to the value attribute which must have a getter and setter.

Can't get all values from web page

I am working with JSF 2 and Hibernate. I have XHTML page where bean is get from database and inserted into page. When I change the values of bean and submit for savign I am getting only the last value. What I making wrong?
Here is my XHTML page form code:
<h:form id="edit-slide-form">
<h:panelGrid columns="2">
<h:outputText value="#{msgs.slideTitle}" styleClass="label"/>
<h:inputText id="title" value="#{sliderAction.newSlide.title}" name="#{sliderAction.slide.title}" required="true"/>
<p></p><h:message for="title" errorClass="error"/>
<h:outputText value="#{msgs.description}" styleClass="label"/>
<h:inputTextarea id="description" value="#{sliderAction.newSlide.description}" name="#{sliderAction.slide.description}" required="true"/>
<p></p><h:message for="description" errorClass="error"/>
<p></p>
<h:commandButton value="#{msgs.save}" action="#{sliderAction.saveChanges}" styleClass="button"/>
<h:message for="edit-slide-form"/>
</h:panelGrid>
</h:form>
When I submit this form I can get only last value (e.g id="description").
SliderAction.class
#Named
#SessionScoped
public class SliderAction implements Serializable {
private static final long serialVersionUID = 1L;
private EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("iaau");
private EntityManager entityManager;
private int id;
private Integer coordinates[] = new Integer[4];
private Image image = new Image();
private Slide slide = new Slide();
private Slide newSlide = new Slide();
private List<Slide> slides = new ArrayList<Slide>();
private UploadedFile uploadedFile;
private boolean uploaded;
public String uploadSlideImage() {
ImageAction imageAction = new ImageAction();
if( uploaded ) {
imageAction.delete( image.getUniqueName(), image.getThumb() );
for( int i = 0; i < coordinates.length; i++ ) {
coordinates[i] = null;
}
}
imageAction.upload(uploadedFile, false);
setImage( imageAction.getImage() );
uploaded = true;
return null;
}
public String cropAndSave(){
ImageAction imageAction = new ImageAction();
imageAction.cropSlide( image, coordinates, 928, 318 );
newSlide = new Slide();
newSlide.setImage( image );
startTransaction();
entityManager.persist(image);
entityManager.persist(newSlide);
endTransaction();
closeTransaction();
uploaded = false;
setId(newSlide.getId());
return "edit";
}
public String saveChanges() {
startTransaction();
entityManager.merge(newSlide);
endTransaction();
closeTransaction();
return "list";
}
public void deleteSlide() {
startTransaction();
slide = (Slide)entityManager.find(Slide.class, id);
entityManager.remove(slide);
endTransaction();
closeTransaction();
ImageAction imageAtion = new ImageAction();
imageAtion.delete(slide.getImage().getUniqueName(), slide.getImage().getThumb());
}
public Slide getSlide() {
startTransaction();
slide = entityManager.find(Slide.class, id);
endTransaction();
closeTransaction();
return slide;
}
public void setSlide(Slide slide) {
this.slide = slide;
}
public Slide getNewSlide() {
startTransaction();
newSlide = entityManager.find(Slide.class, id);
endTransaction();
closeTransaction();
return newSlide;
}
public void setNewSlide(Slide newSlide) {
this.newSlide = newSlide;
}
#SuppressWarnings("unchecked")
public List<Slide> getSlides() {
startTransaction();
slides = entityManager.createQuery("from Slide").getResultList();
endTransaction();
closeTransaction();
return slides;
}
/*Declaration of EntityManager and other getter and setter methods*/
}
Slide.class
#Entity
public class Slide extends AbstractEntity<Integer>{
private static final long serialVersionUID = 1L;
private String title;
private String description;
private Image image;
private String link;
private Page page;
private boolean showOnFeed;
private boolean approved;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#OneToOne
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
#OneToOne
public Page getPage() {
return page;
}
public void setPage(Page page) {
this.page = page;
}
#Column(name="show_on_feed")
public boolean isShowOnFeed() {
return showOnFeed;
}
public void setShowOnFeed(boolean showOnFeed) {
this.showOnFeed = showOnFeed;
}
public boolean isApproved() {
return approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
}
Also I have notices this warning message:
[org.hibernate.ejb.internal.EntityManagerFactoryRegistry] (http-localhost-127.0.0.1-8080-1) HHH000436: Entity manager factory name (iaau) is already registered. If entity manager will be clustered or passivated, specify a unique value for property 'hibernate.ejb.entitymanager_factory_name'
can this cause such problems

Struts 2 jquery grid component with jquery grid column type list which takes list of objects

The problem I have is that I am trying to have a multi select data grid column which will have a List objects (productsEntitled).
I've got the products to display properly by providing a buildSelect custom function to populate my Edit Dialog Box when a user click edit on a record.
When I have the column with the multi select <sjg:gridColumn name="productsEntitledListModel on my grid, the save functionality does not work and does not save. I don't see any errors on the browser console nor on the java console.
Any help will be appreciated as I am unable to find out what the problem is, I de-compiled the entire show case jar and nothing that helps with this issue.
My model look like this:
#Entity
#Table ( name = "USERS")
public class User {
private Long id;
private String name;
private String username;
private String password;
private String sourceIp;
private Device device;
private List<Product> productsEntitled;
This is my grid on a jsp page:
<s:url id="remoteurl" action="loadUsersJson"/>
<s:url id="editurl" action="editGridUserEntry"/>
<s:url id="selectproductsurl" action="loadProductsJson"/>
<sjg:grid gridModel="users"
id="gridUsers"
dataType="json"
width="1150"
href="%{remoteurl}"
draggable="true"
pager="true"
resizable="true"
navigatorAddOptions="{height:525, width:425, readAfterSubmit:true, draggable:true, resizable:true}"
navigatorEditOptions="{height:525, width:425, reloadAfterSubmit:true, draggable:true, resizable:true}"
navigatorDeleteOptions="{height:200, width:200, reloadAfterSubmit:true, draggable:true, resizable:true}"
editurl="%{editurl}"
navigator="true"
navigatorEdit="true"
navigatorAdd="true"
navigatorView="true"
navigatorDelete="true"
rowList="10,15,20"
rowNum="15"
multiselect="false"
onSelectRowTopics="rowselect">
<sjg:gridColumn name="id" editable="true" index="id" hidden="true" key="true" title="ID"/>
<sjg:gridColumn name="name" index="name" editable="true" edittype="text" title="NAME"/>
<sjg:gridColumn name="sourceIp" index="sourceIp" editable="true" edittype="text" title="SOURCE IP"/>
<sjg:gridColumn name="username" index="username" editable="true" edittype="text" title="USERNAME"/>
<sjg:gridColumn name="password" index="password" editable="true" edittype="password" title="PASSWORD"/>
<sjg:gridColumn name="role" index="role" editable="true" edittype="select" editoptions="{value:'Admin:Admin;User:User;'}" title="ROLE"/>
<sjg:gridColumn name="deviceId" jsonmap="device.id" key="true" hidden="true" editable="text" title="DEVICE ID"/>
<sjg:gridColumn name="deviceIp" jsonmap="device.ip" editable="true" edittype="text" title="DEVICE IP"/>
<sjg:gridColumn name="productsEntitledListModel"
width="300"
editable="true"
edittype="select"
editoptions="{dataUrl: '%{selectproductsurl}', multiple:true, buildSelect:customBuildSelect}"
title="PRODUCTS"/>
</sjg:grid>
These are my action classes:
Show the grid:
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class AdminAction extends ActionSupport implements ServletRequestAware {
private static final long serialVersionUID = -1090720652366248768L;
private static final Log logger = LogFactory.getLog(AdminAction.class);
private HttpServletRequest request;
private AuthenticationTicket ticket;
private AdminService adminService;
private List<User> users;
private List<Product> products;
//private List<String>productsAllList;
private String userId;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public AuthenticationTicket getTicket() {
return ticket;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
public void setTicket(AuthenticationTicket ticket) {
this.ticket = ticket;
}
#Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
public String redirectUsersTab() {
return "users";
}
public String redirectProductsTab() {
return "products";
}
private void initAdminService () {
logger.debug("initAdminService()...");
if (adminService == null) {
adminService = (AdminService)ServiceFinder.getContext(request).getBean("adminService");
}
}
public String loadUsersJson() {
initAdminService();
this.users = adminService.getUsersAll();
return "success";
}
public String loadProductsJson() {
initAdminService();
this.products = adminService.getProductsAll();
return "success";
}
//TODO: clean up
public String getAllProductsList() {
logger.debug("testParam, userId: " + this.userId);
initAdminService();
List<Product> temp = adminService.getProductsAll();
if (userId != null) {
User userTemp = new User();
userTemp.setId(new Long(userId));
List<Product> prodEntitled = adminService.getProductsByUser(userTemp);
logger.debug("Products entitled: " + prodEntitled);
}
//TODO: merge prod and prod entitled to Model to populate the grid
products = temp;
/*
if (temp != null && temp.size() > 0) {
this.productsAllList = new ArrayList<String>();
for (Product p : temp) {
this.productsAllList.add(p.getName());
}
}
*/
//logger.debug("this.productsAllList: " + this.productsAllList);
return "success";
}
}
Class to edit the grid:
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class EditUsersGridAction extends ActionSupport implements ServletRequestAware {
private static final Log logger = LogFactory.getLog(EditUsersGridAction.class);
private static final long serialVersionUID = -5485382508029951644L;
private HttpServletRequest request;
private AdminService adminService;
private String oper = "";
private Long id;
private String name;
private String sourceIp;
private String password;
private String username;
private Long deviceId;
private String deviceIp;
private String devicePortDescription;
private String devicePortLayer;
private String deviceType;
private List<Product>productsEntitled;
private List<GridColumnListModel> productsEntitledListModel;
private List<Product>productsAvailable;
public List<GridColumnListModel> getProductsEntitledListModel() {
try {
if (productsEntitled != null && productsEntitled.size() > 0) {
productsEntitledListModel = new ArrayList<EditUsersGridAction.GridColumnListModel>();
for (Product p : productsEntitled) {
GridColumnListModel tmp = new GridColumnListModel();
tmp.setName(p.getName());
tmp.setValue(p);
productsEntitledListModel.add(tmp);
}
return this.productsEntitledListModel;
}else {
return null;
}
} catch (Exception ex) {
logger.error("Exception in getProductsEntitledString", ex);
return null;
}
}
public void setProductsEntitledListModel(List<GridColumnListModel> productsEntitledListModel) {
this.productsEntitledListModel = productsEntitledListModel;
}
public Long getDeviceId() {
return deviceId;
}
public void setDeviceId(Long deviceId) {
this.deviceId = deviceId;
}
public String getDeviceIp() {
return deviceIp;
}
public void setDeviceIp(String deviceIp) {
this.deviceIp = deviceIp;
}
public String getDevicePortDescription() {
return devicePortDescription;
}
public void setDevicePortDescription(String devicePortDescription) {
this.devicePortDescription = devicePortDescription;
}
public String getDevicePortLayer() {
return devicePortLayer;
}
public void setDevicePortLayer(String devicePortLayer) {
this.devicePortLayer = devicePortLayer;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getOper() {
return oper;
}
public void setOper(String oper) {
this.oper = oper;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSourceIp() {
return sourceIp;
}
public void setSourceIp(String sourceIp) {
this.sourceIp = sourceIp;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<Product> getProductsEntitled() {
return productsEntitled;
}
public void setProductsEntitled(List<Product> productsEntitled) {
this.productsEntitled = productsEntitled;
}
public List<Product> getProductsAvailable() {
return productsAvailable;
}
public void setProductsAvailable(List<Product> productsAvailable) {
this.productsAvailable = productsAvailable;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
#Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
private void initAdminService () {
logger.debug("initAdminService()...");
if (adminService == null) {
adminService = (AdminService)ServiceFinder.getContext(request).getBean("adminService");
}
}
public String execute() throws Exception {
logger.debug("#### IN EditGridUsersAction ###");
initAdminService();
productsAvailable = adminService.getProductsAll();
User user = new User();
user.setName(name);
user.setPassword(password);
user.setUsername(username);
user.setSourceIp(sourceIp);
Device device = new Device();
device.setId(deviceId);
device.setIp(deviceIp);
device.setPortDescription(devicePortDescription);
device.setType(deviceType);
user.setDevice(device);
if (id != null) {
user.setId(id);
}
if (oper.equalsIgnoreCase("add")) {
logger.debug("products selected");
//user.setProductsEntitled(adminService.getProductsAll());
adminService.addUser(user);
} else if ( oper.equalsIgnoreCase("edit")) {
//TODO: convert model to products and add to user
logger.debug("now in edit");
List<Product> tempProd = new ArrayList<Product>();
for (GridColumnListModel gridColModel : productsEntitledListModel) {
tempProd.add(gridColModel.getValue());
}
user.setProductsEntitled(tempProd);
adminService.updateUser(user);
//return "input";
}else if (oper.equalsIgnoreCase("del")) {
logger.debug("in delete");
adminService.deleteUser(user);
}
return "success";
}
public class GridColumnListModel {
private String name;
private Product value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Product getValue() {
return value;
}
public void setValue(Product value) {
this.value = value;
}
}
}

Display edit Employee's profile using jsf

Using jsf I want to edit a employee profile, when user will click on any particular datatable row,then
I am able to get all that deatils of selected patient in an
arraylist. Now I want to set all the attritbutes in arraylist to
page1.xhtml backingbean , so When user will select a particular row,
he will navigate to page1.xhtml where he will get all these fields in
the form set already by arraylist attributes.
I am trying in this way.
> page1.xhtml
<h:outputLabel value="Name" />
<p:inputText id="name1" value="#{employeeBB.emp.name}" >
</p:inputText>
<h:outputLabel value="age" />
<p:inputText id="ag" value="#{employeeBB.emp.age}" >
</p:inputText>
<h:outputLabel value="code" />
<p:inputText id="code1" value="#{employeeBB.emp.code}" >
</p:inputText>
#ManagedBean(name = "employee")
#ViewScoped
public class emp {
private String name;
private String age;
private String code;
public String getName()
{ return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
#SessionScoped
#ManagedBean
public class EmployeeBB implements serializable{
private Employe emp;
public Employee getEmp() {
return emp;
}
public void setEmp(Employee emp) {
this.emp = emp;
}
}
#SessionScoped
#ManagedBean
public class AddEmployeeBB{
private ArrayList<Employee>empList;
private ArrayList<Employee>empList;
public ArrayList<Employee> getEmpList() {
if(empList==null){
empList=new ArrayList<Employee>();
}
return empList;
}
public void setEmpList(ArrayList<Employee> empList) {
this.empList = empList;
}
public void method() throws IOException{
String code='123';
EmployeeDAO obj=new EmployeeDAO(); // DAO class
empList=obj.getAllEmplInfo(code); // will get all needed information about employee of this code in this arrayist
for(int i=0;i<empList.size();i++){
String name=empList.get(i).getName();
String age=empList.get(i).getAge();
String code=empList.get(i).getCode();
Employee e=new Employee();
e.setName(name);
e.setAge(age);
e.setCode(code);
EmployeeBB obj1=new EmployeeBB();
obj1.setEmp(e); // now according to my logic object e will set to emp object of Employee, and
// that means all these values name ,agem and code will be set to my page1.xhtml and I will be able to see it.
}
}
But I am unable to get pag1.xhtml with filled values.
Show me the way.
The reason for it not being shown is that you are setting values in a object which you are creating
EmployeeBB obj1=new EmployeeBB();
obj1.setEmp(e);
JSF lifecycle doens't know about this object and everytime you are seeing blank.
In AddEmployeeBB add this
#ManagedProperty(value="employeeBB")
private EmployeeBB employeeBB = null; // create getter setter for this
then instead of this :
EmployeeBB obj1=new EmployeeBB();
obj1.setEmp(e);
Use this:
this.employeeBB.setEmp(e);

Resources