Bean doesn't dispatch to another page - jsf

I've a problem with a bean that doesn't dispatch the response to another page.
This is the code:
#ManagedBean(name = "ssoServiceBean")
public class SSOServiceBean {
#ManagedProperty(value="#{param.samlRequest}")
private String samlRequest;
#ManagedProperty(value="#{param.relayState}")
private String relayState;
#PostConstruct
public void submit() {
System.out.println("1) PostConstruct method called");
//samlRequest = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("samlRequest");
//relayState = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("relayState");
processResponse();
}
//getters and setters omitted for succinctness
private void processResponse(){
System.out.println("2) Processing response");
String uri;
if(samlRequest != null && !samlRequest.equals("") && relayState != null && !relayState.equals("")) {
System.out.println("SAMLRequest: "+samlRequest);
System.out.println("RelayState: "+relayState);
uri = "challenge.xhtml";
System.out.println("3) Sending challenge...");
} else {
uri = "dashboard.xhtml";
System.out.println("3) Sending dashboard...");
}
try {
FacesContext.getCurrentInstance().getExternalContext().dispatch(uri);
System.out.println("4) Done.");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The problem is that the dispatch() method doesn't work properly, and seems to be ignored.
Infact the system responses with an error of the related bean's page ssoservice.xhtml
I've used the Postconstruct annotation because with this bean I've to intercept POST parameters that come from a third-party page.
Once I've received the post parameters, I've to render the challenge.xhtml page, WITHOUT using a redirect directive.
Nextly, the user will submit challenge.xhtml to the related bean ChallengeBean.java .
So, what is the problem? Why dispatch doesn't work?

Related

My sessionscoped bean does not have values stored on every refresh

I have a SessionScoped Bean which consists of a list and a flag. The list populates a datatable in the xhtml view.
On first load, the list is populated. Every other load should not repopulate the list but it does despite the check. This behaviour also holds for postbacks on commandLinks clicks.
#ManagedBean(name = "customerSegmentInfo")
#SessionScoped
public class CustomerSegmentInfo extends BasePage implements Serializable {
private boolean isNBACalled = false;
private List<NextBestActionDTO> nextBestActionList = null;
public List<NextBestActionDTO> getNextBestActionList() {
log.debug("----- nbaCalled: " + isNBACalled);
if(nextBestActionList == null && !isNBACalled){
log.debug("-------- getNextBestAction");
try {
nextBestActionList = this.getNbaService().getNextBestAction(this.getCustomerInfo().getCountryCode(), this.getCustomerInfo().getCustomerNo());
log.debug("---- " + nextBestActionList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
log.debug("------ error calling nba service bean " + e);
}
isNBACalled = true;
log.debug("----- nbaCalled: " + isNBACalled);
}
return nextBestActionList;
}
public void setNextBestActionList(List<NextBestActionDTO> nextBestActionList) {
this.nextBestActionList = nextBestActionList;
}
}
As the list is not null from last page load and flag also set to true, the call getNextBestAction shouldnt be made, but in logs the flag is false and apparently the list is null too.
the behaviour is irregular
On certain loads it behaves as expected on others not.
I Tried setting the javax.faces.STATE_SAVING_METHOD context parameter in the web.xml to both server and client, nothing changed.
Thank you in advance

How to specify command attribute in h:inputText?

I have a function that I derclare beans in my manager and I want to return the value in inputText but when I put the name of my function in the value attribute of inputText tag like this:
<p: inputText value = "#{ticketBean.getLastIndexTache} "/>
this error appear:
Etat HTTP 500 - /pages/test.xhtml #13,106 value="#{ticketBean.getLastIndexTache}": Property 'getLastIndexTache' not found on type com.bean.TicketBean
here is the java code
#ManagedBean(name="ticketBean")
public class TicketBean {
public int getLastIndexTache() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
int index = 0;
try {
session.beginTransaction();
String sql = "select MAX(t.IDTICKET) from ticket t ";
Query query = session.createSQLQuery(sql);
if( query.uniqueResult()==null){
index=0;
}else{
index=(int) query.uniqueResult();
index=index+1;
}
} catch (HibernateException e) {
// TODO: handle exception
session.getTransaction().rollback();
e.printStackTrace();
}
return index;
}
}
You should use the bean property in value like
<p:inputText value="#{ticketBean.lastIndexTache}"/>
as JSF by itself adds "get" to the property name. Currently it will look for the method getGetLastIndexTache().
Besides its very bad practice to have logic in any getter as they are called multiple times by JSF. Instead you should make an property like
private Integer lastIndexTache; // +getter/setter
and set the value in a #PostConstruct method:
#PostConstruct
public void init() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
// etc....
lastIndexTache = index;
}
The getter would then simply be
public Integer getLastIndexTache() {
return lastIndexTache;
}
and don't forget a setter:
public void setLastIndexTache(Integer newValue) {
lastIndexTache = newValue;
}
Also you should probably put a scope on the bean (for example #ViewScoped).

How to destroy a session after data is presented in a jsf page

I have this problem: I´m making this wonderfull tutorial The NetBeans E-commerce Tutorial . But instead of make it in JSP as is presented, i´m making a JSF version. Just to undertands the logic in construction an application like that.
In certain part the ControllerServlet.java, has this code:
int orderId = orderManager.placeOrder(name, email, phone, address, cityRegion, ccNumber, cart);
// if order processed successfully send user to confirmation page
if (orderId != 0) {
// dissociate shopping cart from session
cart = null;
// end session
session.invalidate();
// get order details
Map orderMap = orderManager.getOrderDetails(orderId);
// place order details in request scope
request.setAttribute("customer", orderMap.get("customer"));
request.setAttribute("products", orderMap.get("products"));
request.setAttribute("orderRecord", orderMap.get("orderRecord"));
request.setAttribute("orderedProducts", orderMap.get("orderedProducts"));
userPath = "/confirmation";
// otherwise, send back to checkout page and display error
As you can see, the author invalidates the session, in order to permit another purchase order. I made an Managed Bean with session scope in order to mantain the data avalaible throught the whole session. But when I try to clean up the session, as in the tutorial the author does, I can´t receive the data for confirmation.
Then, I made a different managed bean in order to have one to process the order (CartManagerBean), and another one to present the confirmation (ConfirmationMBean). I just injected the confirmatioBean into the cartBean to pass the orderId, necessary to present the data. In the confirmationBean, I made a cleanUp() method that invalidates the session.
But always, the data is not presented. So if any one can tell me what to do, I´ll appreciate.
Here is the part of my cartBean's code that pass the data to the confirmation bean:
...
#ManagedProperty(value ="#{confirmationBean}")
private ConfirmationMBean confirmationBean;
...
public String makeConfirmation() {
FacesContext fc = FacesContext.getCurrentInstance();
if (!cartMap.isEmpty()) {
int orderId = orderManager.placeOrder(name, email, phone, address, credicard, cartMap);
// if order processed successfully send user to confirmation page
if (orderId != 0) {
// get order details
confirmationBean.setOrderId(orderId);
// dissociate shopping cart from session
cartMap.clear();
// end session
//fc.getExternalContext().invalidateSession();
}
}
return "confirmation";
}
As you can see, I commented the part that invalidates the session. Here is the code that I implemented for the ConfirmationMBean:
#ManagedBean(name = "confirmationBean")
#SessionScoped
public class ConfirmationMBean implements Serializable{
private Customer customer;
private List<OrderedProduct> orderedProducts;
private CustomerOrder orderRecord;
private List<Product> products;
private int orderId;
#EJB
private OrderManager orderManager;
public void cleanUp(){
FacesContext fc = FacesContext.getCurrentInstance();
fc.getExternalContext().invalidateSession();
}
private void init(){
Map<String, Object> orderMap = orderManager.getOrderDetails(orderId);
customer = (Customer) orderMap.get("customer");
orderRecord = (CustomerOrder) orderMap.get("orderRecord");
orderedProducts = (List<OrderedProduct>) orderMap.get("orderedProducts");
products = (List<Product>) orderMap.get("products");
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public List<OrderedProduct> getOrderedProducts() {
return orderedProducts;
}
public void setOrderedProducts(List<OrderedProduct> orderedProducts) {
this.orderedProducts = orderedProducts;
}
public CustomerOrder getOrderRecord() {
return orderRecord;
}
public void setOrderRecord(CustomerOrder orderRecord) {
this.orderRecord = orderRecord;
}
public List<Product> getProducts() {
return products;
}
public void setProducts(List<Product> products) {
this.products = products;
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
init();
cleanUp();
}
}
As you can see, when the orderId is setted by the preceding bean, the data is requested from the database, and populates the variables to present in the facelet. ¿Where or how I have to use the cleanUp method in order to obtain the same result that the tutorial?
Thanks in advance.
Put the bean where you're invoking the action in the request scope instead of session scope and get hold of the desired session scoped bean as a (managed) property.
#ManagedBean
#RequestScoped
public class SubmitConfirmationBean {
#ManagedProperty("#{cartBean}")
private CartBean cartBean;
// ...
}
And reference it by #{submitConfirmationBean.cartBean...} instead of #{cartBean...}.
Alternatively, explicitly put the desired session scoped bean in the request scope in the same action method as where you're invalidating the session:
externalContext.getRequestMap().put("cartBean", cartBean);
This way the #{cartBean...} will refer the request scoped one instead of the session scoped one which is newly recreated at that point because you destroyed the session. The request scoped one is lost by next request anyway.

ExternalContext#dispatch() doesn't work

I have server-side coundown counter. When it == 0, method should execute ExternalContext#dispatch(), but it didn't do it. Method ExternalContext#redirect() works correctly on this place.
....
}else{
try {
FacesContext.getCurrentInstance().getExternalContext().dispatch("result.xhtml");
} catch (IOException e) {
e.printStackTrace();
}
}
....
I tried a few ways of the spelling url(result,result.xhtml,\result.xhtml etc.) with the same result.
This is not the right way to let JSF navigate to a different view.
If you're inside an action method, you should be returning it as string instead.
public String submit() {
// ...
return "result.xhtml";
}
Or if you're not inside an action method and couldn't change it to a fullworthy action method for some unclear reason, then use NavigationHandler#handleNavigation() instead.
FacesContext context = FacesContext.getCurrentInstance();
context.getApplication().getNavigationHandler().handleNavigation(context, null, "result.xhtml");

new CDI conversation

While inside a not trasient conversation, I need to start a new conversation for the bean.
The case is the following: I have a jsf page with a cdi bean to handle creation and altering of an order. On the menu of the page there is an item which is "new Order". So, when altering an Order, I need to click on "new Order" and the page must be refreshed with the new CID, and a new conversation scope. But if I try to do this, the conversation.getConverstaionId() always return the same value, even if I call conversation.end() and conversation.begin() first.
EDIT:
I have a page to edit an order. When clicking on a new button (of the menu), I want it to refresh and start a new conversation, to add a new order. So this button calls the method redirectToNewOrderPage(). But it has the problem described on the code and before.
#Named
#ConversationScoped
public class OrderEditBean implements Serializable {
private static final long serialVersionUID = 1L;
#Inject
private Conversation conversation;
[...]
public void redirectToNewOrderPage() {
String cid = createNewConversationId();
setOrder(null);
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("/OrdersManager/restricted/orders/edit.xhtml?cid=" + cid);
} catch (IOException e) {
e.printStackTrace();
}
}
private String createNewConversationId() {
String oldConversationId = null;
String newConversationId = null;
oldConversationId = conversation.getId();
if (!conversation.isTransient() && conversation.getId() != null) {
conversation.end();
}
conversation.begin();
newConversationId = conversation.getId();
// **************
// at this point newConversationId is equal to
// oldConversationId if the conversation was NOT transient.
// **************
return newConversationId;
}
}
What you are trying to do, does not work. The conversation scope in CDI is not as power as the one from Seam 2 (if that's where you're coming from).

Resources