在数据库中存储http会话属性 [英] Storing a http session attribute in database

查看:113
本文介绍了在数据库中存储http会话属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

正确显示并注入了session属性,但我需要使用 selected 传递它,以将其存储在数据库中(实际上,它传递了null).

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).

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:

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

AbstractController(对于上述JSF中的 selected 和其他方法):

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

谢谢.

已更新:

The ViagensController:

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

推荐答案

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

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

}

这篇关于在数据库中存储http会话属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆