在SQLIntegrityConstraintViolationException上显示错误消息Jsf中的异常

时间:2012-02-24 12:25:43

标签: java sql jsf-2 error-handling

我想通过<h:messages/>

在我的jsf页面中通知SQLException用户

我有以下功能

 public String createAccount() throws RollbackFailureException,SQLIntegrityConstraintViolationException,Exception{
    String status = "failure";
    EntityManager em = null;
    try {
        logger.log(Level.INFO,"Registering the user");
        utx.begin();
        em = getEntityManager();

        em.persist();
        status = "success";
        utx.commit();

    } catch (Exception ex) {
        try {
            utx.rollback();
        } catch (Exception re) {
            throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
        }
        if (findDetails(details.getId()) != null) {

          throw new SQLIntegrityConstraintViolationException("Your Account cannot be setup as the Login Id already exists.Kindly choose a different Login ID", ex);
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }

如何使用jsf ??

显示错误消息

感谢:)

1 个答案:

答案 0 :(得分:2)

在支持bean中使用以下内容添加消息:

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
...
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);

严重性可以是SEVERITY_WARNSEVERITY_INFO。您可以将clientId作为addMessage的第一个参数。如果是null,则该消息是全局消息,并显示在h:messages