2010-07-30 3 views
0

Проблема: поиск более подходящего дизайна.<h:dataTable> и SessionScoped beans

Цель: я хочу иметь таблицу с информацией о пользователе и с кнопкой «сменить пароль» в столбце для каждого пользователя, после нажатия кнопки «сменить пароль» исчезла (rendered = «false») и появилось поле inputSecreat - пользователь вводит пароль и отправляет его (нажав какую-то дополнительную кнопку или горячую клавишу). после отправки - кнопка «сменить пароль», как и раньше.

мой боб

import javax.annotation.PostConstruct; 
import javax.ejb.EJB; 
import javax.faces.bean.SessionScoped; 
import javax.faces.context.ExternalContext; 
import javax.faces.context.FacesContext; 
import javax.inject.Inject; 
import javax.inject.Named; 
import javax.servlet.http.HttpServletRequest; 
import java.io.Serializable; 
import java.util.HashMap; 

/** 
* <p>Type: UserSession 
* <p>User: kislo_metal 
* <p>Date: Jun 21, 2010 
* <p>Time: 4:41:57 PM 
*/ 
@Named 
@SessionScoped 
public class UserSession implements Serializable { 

    private String name; 
    private String role; 

    @Inject 
    private org.slf4j.Logger log; 

    @EJB 
    private PersistenceService pservice; 

    @Inject 
    private RulesBean rules; 

    private HashMap<Long, Boolean> boolHashmap; 


    public UserSession() { 
    } 


    @PostConstruct 
    public void postConstruct() { 

     log.info("session init "); 

    } 

    public String getName() { 
     if (name == null) getUserData(); 
     return name == null ? "" : name; 
    } 

    public String getRole() { 
     return role == null ? "" : role; 
    } 

    public void setRole(String newValue) { 
     role = newValue; 
    } 

    public boolean isInRole() { 
     ExternalContext context 
       = FacesContext.getCurrentInstance().getExternalContext(); 
     Object requestObject = context.getRequest(); 
     if (!(requestObject instanceof HttpServletRequest)) { 
      log.info("request object has type " + requestObject.getClass()); 
      return false; 
     } 
     HttpServletRequest request = (HttpServletRequest) requestObject; 
     return request.isUserInRole(role); 
    } 


    private void getUserData() { 
     ExternalContext context 
       = FacesContext.getCurrentInstance().getExternalContext(); 
     Object requestObject = context.getRequest(); 
     if (!(requestObject instanceof HttpServletRequest)) { 
      log.info("request object has type " + requestObject.getClass()); 
      return; 
     } 
     HttpServletRequest request = (HttpServletRequest) requestObject; 
     name = request.getRemoteUser(); 
    } 

    public HashMap getBoolHashmap() { 
     if (boolHashmap == null) 
      initBolHashMap(); 
     return boolHashmap; 
    } 

    public void setBoolHashmap(HashMap<Long, Boolean> boolHashmap) { 
     this.boolHashmap = boolHashmap; 
    } 

    public void initBolHashMap() { 

     this.boolHashmap = new HashMap<Long, Boolean>(); 
     System.out.println(""); 
     log.info("init map.."); 
     log.info("loding list"); 
     log.warn("user name = " + rules.getUserPrincipalName()); 
     for (OasysUserEntity user : pservice.getUsersList(pservice.getUserByLogin(rules.getUserPrincipalName()).getPartnerid())) { 
      boolHashmap.put(user.getId(), false); 
      log.info("map =" + boolHashmap); 
     } 
     log.info("loaded list"); 
    } 


    public boolean getPWRender(long id) { 
     if (boolHashmap == null) 
      initBolHashMap(); 
     //TODO if it null - exception will be thrown 
     try { 
      log.info("getting id =" + id); 
      log.info("map is =" + boolHashmap); 
      log.info("getting result = =" + boolHashmap.get(id)); 
      log.info("getting result = =" + boolHashmap.get(Long.valueOf(id))); 

      return boolHashmap.get(Long.valueOf(id)); 
     } catch (NullPointerException e) { 
      e.printStackTrace(); 
      return false; 
     } 
    } 

    public void setPWrenerTrue(long id) { 
     if (boolHashmap == null) 
      initBolHashMap(); 
     log.info("setPWrenerTrue id =" + id); 
     boolHashmap.put(id, true); 
     log.info("setPWrenerTrue map is =" + boolHashmap); 

    } 
} 

и страница:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml" 
     xmlns:ui="http://java.sun.com/jsf/facelets" 
     xmlns:h="http://java.sun.com/jsf/html" 
     xmlns:f="http://java.sun.com/jsf/core" 
     xmlns:cc="http://java.sun.com/jsf/composite" 
     xmlns:p="http://primefaces.prime.com.tr/ui" 
     > 
<body> 
<cc:interface> 

</cc:interface> 
<cc:implementation> 
    #{i18n.user_managment_title} 
    <h:form> 
     <!--<f:ajax render="@form" execute="@form">--> 
     <h:dataTable id="userTable" var="puser" value="#{userTable.uList}" border="1"> 
      <h:column> 
       <f:facet name="header"> 
        <h:outputText value="Login"/> 
       </f:facet> 
       #{puser.login} 
      </h:column> 
      <h:column> 
       <f:facet name="header"> 
        <h:outputText value="password"/> 
       </f:facet> 
       <h:panelGroup> 
        <!--#{puser.password}     --> 
        <h:commandButton id="chps" value="#{i18n.chpsqd_button}" rendered="#{!userSession.getPWRender(puser.id)}" 
          action="#{userSession.setPWrenerTrue(puser.id)}"> 
          <f:ajax render="pswd chps"/> 
        </h:commandButton> 


        <h:inputSecret id="pswd" rendered="#{userSession.getPWRender(puser.id)}" value="some"/> 

        <!--<h:inputSecret id="chpaswd" value="#{managePUser.password}">--> 
         <!--<f:ajax event="click" render="chpaswd"/>--> 
        <!--</h:inputSecret>--> 

        <!--<h:commandButton value="#{i18n.submit_button}">--> 
        <!--</h:commandButton>--> 
       </h:panelGroup> 

      </h:column> 
      <h:column> 
       <f:facet name="header"> 
        <h:outputText value="pId"/> 
       </f:facet> 
       #{puser.partnerid} 
      </h:column> 
      <h:column> 
       <f:facet name="header"> 
        <h:outputText value="groupName"/> 
       </f:facet> 
       #{puser.groupName} 
      </h:column> 
      <h:column> 
       <f:facet name="header"> 
        <h:outputText value="isActive"/> 
       </f:facet> 
       #{puser.userStatusid==2} 
      </h:column> 

      <h:column> 
       <h:commandButton value="#{i18n.delete_button}" action="#{managePUser.removeEntity(puser)}" 
           disabled="#{puser.groupName.equals('admin')}"> 
        <f:ajax render="@form"/> 
       </h:commandButton> 
      </h:column> 
      <!--<h:column>--> 
      <!----> 
      <!--<h:commandButton value="#{i18n.edit_button}" action="#{managePUser.removeEntity(puser)}"/>--> 
      <!--</h:column>--> 

      <f:facet name="footer"> 
       <!--<f:ajax render="footeradd userTable">--> 
       <h:panelGroup id="footeradd"> 

        <h:panelGroup layout="block" rendered="#{!managePUser.padd}"> 
         <h:commandButton value="#{i18n.user_manager_add_user}" 
             action="#{managePUser.setEnablepadd}"> 
          <f:ajax render="footeradd"/> 
         </h:commandButton> 
        </h:panelGroup> 

        <h:panelGroup id="adduser" rendered="#{managePUser.padd}" layout="block"> 

         <h:panelGrid columns="2"> 

          <h:outputText value="#{i18n.username}"/> 
          <h:inputText id="username" value="#{managePUser.login}"/> 

          <h:outputText value="#{i18n.password}"/> 
          <h:inputSecret id="passowrd" value="#{managePUser.password}"/> 

          <h:commandButton value="#{i18n.cancel_button}" 
              action="#{managePUser.setDisblepadd}"> 
           <f:ajax render="footeradd"/> 
          </h:commandButton> 
          <h:commandButton value="#{i18n.submit_button}" action="#{managePUser.submit}"> 
           <f:ajax render="footeradd userTable" execute="@this username passowrd"/> 
          </h:commandButton> 

         </h:panelGrid> 
        </h:panelGroup> 
       </h:panelGroup> 
       <!--</f:ajax>--> 
      </f:facet> 
     </h:dataTable> 
     <!--</f:ajax>--> 
    </h:form> 
</cc:implementation> 
</body> 
</html> 

поэтому я использую мой боб в колонку:

    <h:commandButton id="chps" value="#{i18n.chpsqd_button}" rendered="#{!userSession.getPWRender(puser.id)}" 
          action="#{userSession.setPWrenerTrue(puser.id)}"> 
          <f:ajax render="pswd chps"/> 
        </h:commandButton> 

Вопрос 2: что может быть лучше дизайн для этого ситуация?

Вопрос 3: Возможно ли прослушать некоторые события (onclick, ondbclick внутри тега компонента) для некоторого компонента (inputSecret в моей ситуации), если он отключен = «true»?

Спасибо!

+0

Что такое событие часов? :) – BalusC

+0

было на клике) –

ответ

0

Измените область видимости на ViewScope, нет необходимости сохранять класс UserSession в SessionScope.

+1

Я использую CDI bean, а не @ManagedBean. Существует всего несколько реализованных рук @ViewScoped для CDI-компонентов, и, насколько я понимаю, области @ManagedBean не имеют места с CDI-компонентами. –