在数据库中存储http会话属性

时间:2014-05-07 04:56:39

标签: jsf jpa ejb cdi

如何传递注入的http会话属性(见下文)以及其他值(用户的信息)并使用JPA保存它们?

会话属性已正确显示并注入,但我需要使用选择的传递它以存储在数据库中(实际上,它传递为null)。

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);" />

豆子:

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());
}
}

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*/ }
}

AbstractController(用于JSF上面的选中和其他方法):

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);
}
}

提前致谢。

更新

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 个答案:

答案 0 :(得分:0)

需要覆盖通过注入的http会话值传递的save方法:

@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);
    }

}