обновление значений бина из контроллера, несколько вставок по нажатию кнопки - PullRequest
0 голосов
/ 20 января 2012

Я новичок в jsf jpa rest. Мне было интересно, как установить значения в bean-компонентах из bean-компонентов контроллера.

Скажем, предположим, что как только пользователь зарегистрируется, я хочу вставить значения в БД вместе с датой, котораяЯ генерирую в контроллере. Теперь, как мне установить это в POJO

register.xhtml

<h:form id="registerForm">
            <table>
                <tr>
                    <td colspan="3" id="register">
                        <h2 style="border-bottom: 1px solid #CCCCCC;">Customer
                            Information</h2>
                        <tr>
                            <td class="label">
                                <h:outputLabel for="name" value="Name:"></h:outputLabel>
                            </td>
                            <td class="field">
                                <h:inputText id="name" size="20" required="true" requiredMessage="Please enter your name" value="#{registerController.selected.contactName}">
                                    <f:validateLength maximum="50"></f:validateLength>
                                </h:inputText>
                            </td>
                        </tr>
                        <tr>
                            <td class="label">
                                <h:outputLabel for="company" value="Company:"></h:outputLabel>
                            </td>
                            <td class="field">
                                <h:inputText id="company" size="20" required="true" requiredMessage="Please enter your company" value="#{registerController.selected.company}">
                                    <f:validateLength maximum="50"></f:validateLength>
                                </h:inputText>
                            </td>
                        </tr>
                        <tr>
                            <td class="label">
                                <h:outputLabel for="designation" value="Designation:"></h:outputLabel>
                            </td>
                            <td class="field">
                                <h:inputText id="designation"  size="20" required="true" requiredMessage="Please enter your designation" value="#{registerController.selected.designation}">
                                    <f:validateLength maximum="50"></f:validateLength>
                                </h:inputText>

                            </td>
                        </tr>
                        <tr>
                            <td class="label">
                                <h:outputLabel for="email" value="Email Id:"></h:outputLabel>
                            </td>
                            <td class="field">
                                <h:inputText id="email"  size="20" required="true" requiredMessage="Please enter your email,eg:yourid@domain.com" value="#{registerController.selected.primaryEmailId}" title="eg:www.domain.com OR http://127.0.0.1/domain">
                                    <f:validateLength maximum="70"></f:validateLength>
                                </h:inputText>
                            </td>
                        </tr>
                        <tr>
                            <td class="label">
                                <h:outputLabel for="phone" value="Contact No:"></h:outputLabel>
                            </td>
                            <td class="field">
                                <h:inputText id="phone" size="20" required="true" requiredMessage="Please enter your contact number" value="#{registerController.selected.contactNo}" title="eg:+919999999999">
                                    <f:validateLength minimum="13" maximum="25"></f:validateLength>
                                </h:inputText>
                            </td>
                        </tr>

                    </td>

                </tr>
                <tr>
                    <td colspan="4" id="loginInfo">
                        <h2 style="border-bottom: 1px solid #CCCCCC;">Login Information</h2>
                        <tr>
                            <td class="label"> 
                                <h:outputLabel for="email" value="Login Email:"></h:outputLabel>
                            </td>
                            <td class="field">
                                <h:inputText id="email"  size="20" maxlength="70" required="true" requiredMessage="Please enter your login email id,eg:yourid@domain.com" value="#{loginController.selected.clientId}">
                                    <f:validateLength maximum="70"></f:validateLength>
                                </h:inputText>

                            </td>
                        </tr>
                        <tr>
                            <td class="label">
                                <h:outputLabel for="password" value="Password:"></h:outputLabel>
                            </td>
                            <td class="field">
                                <h:inputSecret id="password"  size="20" maxlength="70" required="true" requiredMessage="Please enter your desired password(minimun 6 characters)" value="#{loginController.selected.password}">
                                    <f:validateLength minimum="6" maximum="50"></f:validateLength>
                                </h:inputSecret>

                            </td>
                        </tr>
                        <tr>
                            <td class="label">
                                <h:outputLabel for="confirm_password" value="Confirm Password:"></h:outputLabel>
                            </td>
                            <td class="field">
                                <h:inputSecret id="confirm_password" size="20" required="true" requiredMessage="Please confirm your password">
                                    <f:validateLength minimum="6" maximum="50"></f:validateLength>
                                </h:inputSecret>
                            </td>
                        </tr>
                    </td>
                    <tr>
                        <td>
                            <h:commandButton value="Sign Up" action="">
                            </h:commandButton>
                        </td>
                    </tr>
                </tr>
                </table>

Теперь мой бин Register и login содержит геттеры и сеттеры

loginbean

       public String getLoginEmail() {
        return loginEMail;
    }

    public void setLoginEmail(String loginEMail) {
        this.loginEMail = loginEMail;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

Register bean

    public String getContactName() {
        return contactName;
    }

    public void setContactName(String ContactName) {
        this.contactName = contactName;
    }

    public String getCompany() {
        System.out.println("get....." + company);
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
        System.out.println("set....." + company);
    }

    public String getDesignation() {
        System.out.println("get....." + designation);
        return designation;
    }

    public void setDesignation(String designation) {
        this.designation = designation;
        System.out.println("set....." + primaryDesignation);
    }

    public String getContactNo() {
        return contactNo;
    }

    public void setContactNo(String contactNo) {
        this.contactNo = contactNo;;
    }

    public String getEmailId() {
        return emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    public String getActiveFlag() {
        return activeFlag;
    }

    public void setActiveFlag(String activeFlag) {
        this.activeFlag = activeFlag;
    }

    public String getCreatedBy() {
        System.out.println("get create name....." + createdBy);
        createdBy=getPrimaryContactName();
        return createdBy;
    }

    public void setCreatedBy(String primaryContactName) {
        this.createdBy = primaryContactName;
    }

    public Date getCreatedOn() {
        return createdOn;
    }

    public void setCreatedOn(Date createdOn) {
        this.createdOn = createdOn;
        System.out.println("set....." + createdOn);
    }
    public String getLastUpdatedBy() {
        return lastUpdatedBy;
    }

    public void setLastUpdatedBy(String primaryContactName) {
        this.lastUpdatedBy = primaryContactName;
    }
    public Date getLastUpdatedOn() {
        return lastUpdatedOn;
    }

   public void setLastUpdatedOn(Date lastUpdatedOn) {
       this.lastUpdatedOn = lastUpdatedOn;
    }

У меня есть два контроллера registerController и loginController, где у меня есть бизнес-логика.

@ManagedBean(name = "registerController")
@SessionScoped
    public String prepareCreate() {
    System.out.println("Inside create");
    current = new Register();
    System.out.println("Inside create current");
    selectedItemIndex = -1;
    return "Signup Success";
}

public String create() {
    try {
        System.out.println("I am inside create");
        getFacade().create(current);
        JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("RegisterCreated"));
        return prepareCreate();
    } catch (Exception e) {
        System.out.println("I am here inside create exception");
        e.printStackTrace();
        JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        return null;
    }
}

public Date generateCurrentTime()
{
    // get current system time yyyy/MMM/dd HH:mm:ss
    Calendar currentDate = Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    String dateNow = formatter.format(currentDate.getTime());
            Date convertedDate=null;
            try
            {
            convertedDate=formatter.parse(dateNow);
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            System.out.println("date now is:"+dateNow);
            return convertedDate;
}

Аналогично loginController также содержит то же самоекод.Как установить атрибут convertDate для полей созданныхOnOn и LastUpdatedOn в pojo ??

Я использовал @ManagedBeanProperty, но он не задал значение ...

@ManagedBeanProperty(value=#{registerController.getgenerateCurrentTime})
  @Column(name = "created_on")
   @Temporal(TemporalType.DATE)
   private Date createdOn;


  @ManagedBeanProperty(value=#{registerController.getgenerateCurrentTime})
  @Column(name = "created_on")
   @Temporal(TemporalType.DATE)
   private Date lastUpdatedOn;

Пожалуйста, укажите, где яЯ ошибаюсь. Я использовал @sessionscoped

Также, как вы можете видеть, у меня есть две таблицы в форме, и они зависят друг от друга. Как мне вставить их в базу данных, когда пользователь нажимает кнопку регистрации .... Должен ли я сначала передать управление по нажатию кнопки контроллеру, скажем, setupController, а затем зарегистрировать регистр и войти в систему контроллера

Спасибо:)

Ответы [ 2 ]

0 голосов
/ 21 января 2012

, как говорили другие друзья, вам нужно вызвать действие для установки значений на компоненте поддержки ... вы можете создать метод, который вызывается действием вашей кнопки, и внутри этого метода вы можете вызывать вашу службу для сохранения вашегоданные в БД.веселит

0 голосов
/ 20 января 2012
<h:commandButton value="Sign Up" action="">

выполняет отправку формы, которая приводит к сохранению значений полей в бине (если ajax не используется)

и предоставление действия в командной кнопке, например action="#{setupController.create}", приведет к вызову этого метода create при отправке формы после назначения полей компоненту.

также вы можете указать это в форме

см. Как определить действие формы в JSF?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...