Storing a http session attribute in database

不问归期 提交于 2019-12-25 05:52:10

问题


How can I pass an injected http session attribute (see below), along with other values (informe by the user) and save them using JPA?

The session attribute is correctly displayed and injected, but I need to pass it using the selected to be stored in the database (actually, it passess null).

The JSF:

<p:outputLabel value="UserID (the sessionAttribute):" for="userID" />
<p:inputText id="userID" value="#{userBean.myUser.xChave}" title="userID" />

<p:outputLabel value="Type the Reason:" for="reason" />
<p:inputText id="reason" value="#{viagensController.selected.reason}" />
<!-- updated (just the call to the action method: -->
<p:commandButton actionListener="#{viagensController.saveNew}" value="#{viagensBundle.Save}" update="display,:ViagensListForm:datalist,:growl" oncomplete="handleSubmit(xhr,status,args,ViagensCreateDialog);" />

The bean:

import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;

@Named(value = "userBean")
@SessionScoped
public class UserBean implements Serializable {

private bean_login myUser;

public bean_login getMyUser() {
    return myUser;
}

public void setMyUser(bean_login myUser) {
    this.myUser = myUser;
}

@PostConstruct
public void init() {
    String uid = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("xChave").toString();
    myUser = new bean_login();
    myUser.setxChave(uid);
    System.out.print("from init:" + myUser.toString());
}
}

The AbstractFacade:

public abstract class AbstractFacade<T> {

private Class<T> entityClass;

public AbstractFacade(Class<T> entityClass) {
    this.entityClass = entityClass;
}

protected abstract EntityManager getEntityManager();

public void create(T entity) {
    getEntityManager().persist(entity);
}

public void edit(T entity) {
    getEntityManager().merge(entity);
}

public void remove(T entity) {
    getEntityManager().remove(getEntityManager().merge(entity));
}

public T find(Object id) {{ /*impl. ommited*/ }
public List<T> findAll() {{ /*impl. ommited*/ }
public List<T> findRange(int[] range) { /*impl. ommited*/ }
public int count() { /*impl. ommited*/ }
}

The AbstractController (for the selected in JSF above and other methods):

public abstract class AbstractController<T> {

@Inject
private AbstractFacade<T> ejbFacade;
private Class<T> itemClass;
private T selected;
private Collection<T> items;

private enum PersistAction {
    CREATE,
    DELETE,
    UPDATE
}

public AbstractController() {
}

public AbstractController(Class<T> itemClass) {
    this.itemClass = itemClass;
}

public T getSelected() {
    return selected;
}

// Pass in the currently selected item
public void setSelected(T selected) {
    this.selected = selected;
}

protected void setEmbeddableKeys() {
}

protected void initializeEmbeddableKey() {
}

public Collection<T> getItems() {
    if (items == null) {
        items = this.ejbFacade.findAll();
    }
    return items;
}

// Pass in collection of items
public void setItems(Collection<T> items) {
    this.items = items;
}

// Apply changes to an existing item to the data layer.
public void save(ActionEvent event) {
    String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Updated");
    persist(PersistAction.UPDATE, msg);
}

// Store a new item in the data layer.
public void saveNew(ActionEvent event) {
    String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Created");
    persist(PersistAction.CREATE, msg);
    if (!isValidationFailed()) {
        items = null; // Invalidate list of items to trigger re-query.
    }
}

public void delete(ActionEvent event) {/*implementations ommited*/ }

private void persist(PersistAction persistAction, String successMessage) {
    if (selected != null) {
        this.setEmbeddableKeys();
        try {
            if (persistAction != PersistAction.DELETE) {
                this.ejbFacade.edit(selected);
            } else {
                this.ejbFacade.remove(selected);
            }
            JsfUtil.addSuccessMessage(successMessage);
        } catch (EJBException ex) {
            String msg = "";
            Throwable cause = JsfUtil.getRootCause(ex.getCause());
            if (cause != null) {
                if (cause instanceof ConstraintViolationException) {
                    ConstraintViolationException excp = (ConstraintViolationException) cause;
                    for (ConstraintViolation s : excp.getConstraintViolations()) {
                        JsfUtil.addErrorMessage(s.getMessage());
                    }
                } else {
                    msg = cause.getLocalizedMessage();
                    if (msg.length() > 0) {
                        JsfUtil.addErrorMessage(msg);
                    } else {
                        JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
                    }
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
            JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/viagensBundle").getString("PersistenceErrorOccured"));
        }
    }
}

// Creates a new instance of an underlying entity and assigns it to Selected property.
public T prepareCreate(ActionEvent event) {
    T newItem;
    try {
        newItem = itemClass.newInstance();
        this.selected = newItem;
        initializeEmbeddableKey();
        return newItem;
    } catch (InstantiationException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

// Inform the user interface whether any validation error exist on a page.
public boolean isValidationFailed() {
    return JsfUtil.isValidationFailed();
}

// Retrieve all messages as a String to be displayed on the page.
public String getComponentMessages(String clientComponent, String defaultMessage) {
    return JsfUtil.getComponentMessages(clientComponent, defaultMessage);
}
}

Thanks in advance.

updated:

The ViagensController:

@Named(value = "viagensController")
@ViewScoped
public class ViagensController extends AbstractController<Viagens> implements Serializable {
//generics:passing JPA Entity class, where the 'reason' in JSF is defined
    public ViagensController() {
        super(Viagens.class);
    }
}

回答1:


Need to override the save method passing the injected http session value :

@ManagedBean(name = "riscosController")
@ViewScoped
public class RiscosController extends AbstractController<Riscos> {

    @EJB
    private RiscosFacade ejbFacade;

    @Inject
    @SessionChave
    private String iSessionChave;

    private String sessionChave;
    private UorPosController matriculaController;
    private UorPosController informanteController;

    public String getSessionChave(String chave) {
        if (sessionChave.isEmpty()) {
            sessionChave = iSessionChave;
        }
        return sessionChave;
    }

    public void setSessionChave(String sessionChave) {
        this.sessionChave = sessionChave;
    }

    @PostConstruct
    @Override
    public void init() {
        super.setFacade(ejbFacade);
        FacesContext context = FacesContext.getCurrentInstance();
        matriculaController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
        informanteController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
        sessionChave = "";
    }

    @Override
    public void saveNew(ActionEvent event) {
        this.getSelected().setObs(this.getSessionChave(sessionChave));
        super.saveNew(event);
    }

}


来源:https://stackoverflow.com/questions/23509029/storing-a-http-session-attribute-in-database

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!