Reset values of a Session Bean in JSF

1

Good afternoon, I wanted to know if please someone could help me with the following, as I search and I can not find a solution.

I have a form called "formuPrestamo", which collects values from a Session-managed managedBean called "frances" in an inputText (which initially has all 0) performs some operations and redirects to another page.

The problem is that when I re-open the form "formuPrestamo" the managedBean values remain in the inputText and I need those values to be 0 again.

Thank you very much.

Greetings.

view

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      

                        </h:panelGrid>
                    </p:fieldset>


                    <p:fieldset legend="Datos de Préstamo" toggleable="true" toggleSpeed="500">
                        <p:ajax event="toggle"  listener="#{vistaFieldSet.handleToggle(event)}" update="msgs"/>
                        <h:panelGrid columns="2" cellpadding="5">

                            <p:outputLabel value="Monto Prestado:" for="montoprestado" />
                            <p:inputText id="montoprestado"  value="#{frances.montoSolicitado}" title="Montoprestado" 
                                         readonly="true" />
                            <p:outputLabel value="Fecha de Solicitud:" for="fechaSolicitud" />
                            <p:inputText id="fechaSolicitud"  value="#{frances.fechaSolicitud}" title="FechaSolicitud" 
                                         readonly="true"
                                         >
                                <f:convertDateTime pattern="MM/dd/yyyy" />
                            </p:inputText>
                            <p:outputLabel value="Cuotas:" for="cantidadCuotas" />
                            <p:inputText id="cantidadCuotas" value="#{frances.plazo}" title="CantidadCuotas" 
                                         readonly="true"
                                         />
                            <p:outputLabel value="TNA %:" for="tna" />
                            <p:inputText id="tna" value="#{frances.tasa}" title="Tna"
                                         readonly="true"/>
                            <p:outputLabel value="Gastos Adm:" for="gastosAdm" />
                            <p:inputText id="gastosAdm" value="#{frances.go}"  title="GastosAdm"
                                         readonly="true"/>
                            <p:outputLabel value="Seg. de Vida:" for="seguroVida" />
                            <p:inputText id="seguroVida" value="#{frances.sv}"  title="SeguroVida"/>
                            <p:outputLabel value="IVA %:" for="iva" />
                            <p:inputText id="iva" value="#{frances.iv}"  title="IVA" 
                                         readonly="true"/>
                            <p:outputLabel value="Observación:" for="observacion" />
                            <p:inputTextarea id="observacion" value="#{prestamoController.prestamo.observacion}" title="Observacion" />
                            <p:outputLabel for="somDoc" value="Estado "/>
                            <p:selectOneMenu id="somDoc" value="#{prestamoController.estadoPrestamo.idestadoprestamo}" 
                                             converter="javax.faces.Integer"
                                             required="true"
                                             requiredMessage="Debe seleccionar el estado del préstamo">
                                <f:selectItem itemLabel="Seleccionar" itemValue=""/>
                                <!--<f:selectItem itemLabel="Activo" itemValue="1"/>
                                <f:selectItem itemLabel="Cancelado" itemValue="2"/>-->
                                <f:selectItem itemLabel="Pendiente de Pago" itemValue="3"/>
                            </p:selectOneMenu>


                        </h:panelGrid>
                    </p:fieldset>

                    <p:commandButton id="btnBoton" 
                                     icon="ui-icon-check" value="#{app['boton.grant']}" 
                                     action="#{prestamoController.otorgarPrestamo()}"
                                     update="msgs"
                                     ajax="false"/>

                    <p:commandButton id="btnBotn" 
                                     icon="ui-icon-print" value="#{app['boton.print']}"  
                                     action="#{prestamoController.exportarPDF()}"
                                     ajax="false"/>

                </h:form>

Method to grant a loan

FacesContext context = FacesContext.getCurrentInstance();
        context.getExternalContext().getFlash().setKeepMessages(true);
        JSFUtil.addSuccessMessage(rf.getMensajeArb("info.save"));
        //remover:
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("Frances");

        return "/faces/pages/prestamo/simulaPrestamo.xhtml?faces­redirect=true";
    
asked by francisco castillo 08.06.2017 в 20:05
source

2 answers

1

First, if it is necessary for your MB to have a Session scope, you will have to clean its values once they are not used, in your case if you return to that view and the values were not reset, evidently being a session bean. they stay alive.

For this you can use preRenderView, what it will do is:  Before rendering the view, it will execute some validation or, in your case, clean the objects and properties that you indicate. facelets

A minimal example:

<?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"
      >

    <f:event listener="#{bean.limpiar}" type="preRenderView" />

    <h:body>

        <h1>Todos los componentes se limpiaran antes de hacer render</h1>

    </h:body>

</html>

In the MB you add the method that will be invoked, inside this put everything you want to clean at the time the view is painted.

import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ComponentSystemEvent;

@ManagedBean(name="bean")
@SessionScoped
public class UserBean{

  public void limpiar(ComponentSystemEvent event){

    //Antes de  hacer  render se llama a este metodo
    //Limpiara los objetos o propiedades
    texto1 = "";
    cantidad1 = 0;
    obj = null

  }
}

If you can change the scope of your bea, you can do it viewScope or request, so you can add an annotated method with @PostConstrut

@PostConstruct
   public void limpiar() {
       texto1 = "";
        cantidad1 = 0;
        obj = new Object();

   }

Take a spin on the following links:

preRender View / view Action Vs PostConstruct

The code of the answer does not test it, but it should work without problem.

    
answered by 08.06.2017 / 20:38
source
1

What version of JSF are you using?

With version 2.0, @ConversationScoped() was added, which allows defining a start and end of the life cycle of your managedBean . This scope already existed in frameworks CDI as SeamFramework and then became part of the JSF 2.0 standard

The Conversation scope is better suited to your problem, since maintaining information through several redirect does not necessarily imply that it is throughout the entire session.

Example:

import java.io.Serializable;

import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Inject;
import javax.inject.Named;

@Named()
@ConversationScoped()
public class ManagedBean implements Serializable {
    private static final long serialVersionUID = 1L;
    private String value;
    private Integer otherValue;
    @Inject
    private Conversation conversation;

    public String onSomeClick() {
         conversation.begin();
        return "nextpage?faces-redirect=true";
    }

 public String onFinish() {
    conversation.end();
    cleanData();
    return "index?faces-redirect=true";
}

private void cleanData(){
 value = null;
 otherValue = null;

}

// getters and setters ...
    
answered by 08.06.2017 в 21:49