0

基本上,我正在尝试使用 primefaces 的自动完成来搜索我的社交网络项目中的用户。我面临的问题是,每当有新用户注册时,自动完成功能有时会在建议中显示新用户,有时不会显示。通常在用户第一次注册时,自动完成功能会在建议中显示用户的姓名,但第二次当另一个用户注册时,他的姓名不会显示在建议中。我认为 userDB 没有得到更新。但是每当我重新部署项目时,一切都运行良好。用户名显示在自动完成中。

1)xhtml

<div class="det">
                <h:form style="float:right;font-size:small;">&nbsp;&nbsp;&nbsp;
      <h:outputText value="Search your friends here."
                        style="font-size:small;color:#CCCCCC;" />
                    <p:autoComplete id="auto" value="#{searchBean.selectedUser}"
                        completeMethod="#{searchBean.completeUser}" var="p"
                        itemLabel="#{p.userName}" itemValue="#{p}"
                        converter="userConverter" forceSelection="true"
                        style="width:300px;">
                        <p:column>
                            <img src="../images/profilePicture/thumb/#{p.image}"
                                style="height: 40px; width: 40px;" />
                        </p:column>
                        <p:column>  
                    #{p.firstName} #{p.lastName}   
            </p:column>
                    </p:autoComplete> 
         &nbsp;<h:commandButton image="../Image/magnify.png"
                        action="#{searchBean.navigate}" style="height:20px;float:right;" />
                    <br />
                </h:form>
            </div>

2) 用户转换器

   package com.bean;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.entity.User;

public class UserConverter implements Converter {

    public static   List<User> userDB;
    static EntityManagerFactory emf=Persistence.createEntityManagerFactory("FreeBird");
    static EntityManager em =emf.createEntityManager();

    static {  
        userDB = new ArrayList<User>();  
        Query query = em.createQuery("SELECT u FROM User u", User.class);
        userDB =query.getResultList();

    }


    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {  
        if (submittedValue.trim().equals("")) {  
            return null;  
        } else {  
            try {  

                for (User p : userDB) {  
                    if (p.getUserName().equalsIgnoreCase(submittedValue)) {  
                        return p;  
                    }  
                }  

            } catch(Exception exception) {  
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid user"));  
            }  
        }  

        return null;  
    }  

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {  
        if (value == null || value.equals("")) {  
            return "";  
        } else {  
            return String.valueOf(((User) value).getUserName());  
        }  
    }  

}

3) 搜索豆

package com.bean;
import com.bean.UserConverter;
import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.http.HttpSession;

import com.entity.User;

public class SearchBean {
    private EntityManager em;
    private User selectedUser;
    private List<User> users;

    public SearchBean(){
        users = UserConverter.userDB;
        EntityManagerFactory emf=Persistence.createEntityManagerFactory("FreeBird");
         em =emf.createEntityManager();
    }

    public User getSelectedUser() {
        return selectedUser;
    }

    public void setSelectedUser(User selectedUser) {
        this.selectedUser = selectedUser;
    }

    public List<User> completeUser(String query){
        List<User> suggestions = new ArrayList<User>();

        for(User u : users){
            if(u.getUserName().startsWith(query))
                suggestions.add(u);
        }

        return suggestions;
    }
    public String navigate(){
        User friend=em.find(User.class,selectedUser.getEmail());
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
        session.setAttribute("frienddet",friend);
        return "searchsuccess";
    }

}

4) 注册Bean

package com.bean;


import java.util.logging.Logger;

import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.http.HttpSession;


import org.primefaces.event.FlowEvent;


import com.entity.User;

public class RegistrationBean {

    User user ;
    private EntityManager em;
     private boolean skip;  
     private static Logger logger = Logger.getLogger(RegistrationBean.class.getName()); 
    public RegistrationBean(){
        user=new User();
        EntityManagerFactory emf=Persistence.createEntityManagerFactory("FreeBird");
         em =emf.createEntityManager();
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
     public boolean isSkip() {  
            return skip;  
        }  

        public void setSkip(boolean skip) {  
            this.skip = skip;  
        } 
    public String Save(){
        System.out.println("registration save called");
        em.getTransaction().begin();
        em.persist(user);
        em.getTransaction().commit();
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
        session.setAttribute("userdet",this.user);
        return "success";


    }
     public String onFlowProcess(FlowEvent event) {  
            logger.info("Current wizard step:" + event.getOldStep());  
            logger.info("Next step:" + event.getNewStep());  

            if(skip) {  
                skip = false;   //reset in case user goes back  
                return "confirm";  
            }  
            else {  
                return event.getNewStep();  
            }  
        }

}

5)注册xhtml

<p:growl id="growl" sticky="true" showDetail="true" />

                <p:wizard widgetVar="wiz"
                    flowListener="#{registrationBean.onFlowProcess}"
                    style="text-size:small;">

                    <p:tab id="personal" title="Personal">

                        <p:panel header="Personal Details">



                            <h:panelGrid columns="3" columnClasses="label, value"
                                styleClass="grid">
                                <h:outputText value="Username*" />
                                <p:inputText id="usrname" required="true" label="Username"
                                    value="#{registrationBean.user.userName}"
                                    requiredMessage="Username required" />
                                <p:message for="usrname"></p:message>

                                <h:outputText value="Firstname: *" />
                                <p:inputText id="frstname" required="true" label="Firstname"
                                    value="#{registrationBean.user.firstName}"
                                    requiredMessage="Firstname required" />
                                <p:message for="frstname"></p:message>

                                <h:outputText value="Lastname: *" />
                                <p:inputText id="lstname" required="true" label="Lastname"
                                    value="#{registrationBean.user.lastName}"
                                    requiredMessage="Lastname required" />
                                <p:message for="lstname"></p:message>

                                <h:outputText value="Password: *" />
                                <p:password id="pwd1" value="#{registrationBean.user.password}"
                                    feedback="true" match="pwd2" label="Password" required="true"
                                    requiredMessage="Password required" />
                                <p:message for="pwd1"></p:message>

                                <h:outputText value="Confirm Password: *" />
                                <p:password id="pwd2" value="#{registrationBean.user.password}"
                                    feedback="true" label="Confirm Password" required="true" />
                                <p:message for="pwd2"></p:message>

                                <h:outputText value="Date of Birth:" />
                                <p:calendar value="#{registrationBean.user.birthDate}"
                                    pattern="dd/MM/yyyy" mode="popup" showOn="button"
                                    navigator="true"></p:calendar>
                                <p:message for="frstname"></p:message>

                                <h:outputText value="Gender: " />
                                <p:inputText label="Gender"
                                    value="#{registrationBean.user.gender}" />
                                <p:message for="frstname"></p:message>

                                <h:outputText value="Relationship Status: " />
                                <p:inputText label="Relationship Status"
                                    value="#{registrationBean.user.relationship}" />
                                <p:message for="frstname"></p:message>



                                <h:outputText value="Skip to last: " />
                                <h:selectBooleanCheckbox value="#{registrationBean.skip}" />
                            </h:panelGrid>
                        </p:panel>
                    </p:tab>

                    <p:tab id="address" title="Address">
                        <p:panel header="Adress Details">

                            <h:messages errorClass="error" />

                            <h:panelGrid columns="2" columnClasses="label, value">
                                <h:outputText value="Street: " />
                                <p:inputText value="#{registrationBean.user.street}" />

                                <h:outputText value="City: " />
                                <p:inputText label="City" value="#{registrationBean.user.city}" />

                                <h:outputText value="Pincode: " />
                                <p:inputText value="#{registrationBean.user.pincode}" />

                                <h:outputText value="State: " />
                                <p:inputText label="State"
                                    value="#{registrationBean.user.state}" />

                                <h:outputText value="Country: " />
                                <p:inputText label="Country"
                                    value="#{registrationBean.user.country}" />

                                <h:outputText value="Skip to last: " />
                                <h:selectBooleanCheckbox value="#{registrationBean.skip}" />
                            </h:panelGrid>
                        </p:panel>
                    </p:tab>

                    <p:tab id="contact" title="Contact">
                        <p:panel header="Contact Information">

                            <h:messages errorClass="error" />

                            <h:panelGrid columns="2" columnClasses="label, value">
                                <h:outputText value="Email: *" />
                                <p:inputText label="Email"
                                    value="#{registrationBean.user.email}" />

                                <h:outputText value="Contact Number: " />
                                <p:inputText value="#{registrationBean.user.contactNo}" />

                            </h:panelGrid>
                        </p:panel>
                    </p:tab>
                    <p:tab id="education" title="Education">
                        <p:panel header="Education Information">

                            <h:messages errorClass="error" />

                            <h:panelGrid columns="2" columnClasses="label, value">
                                <h:outputText value="Secondary School: " />
                                <p:inputText label="Secondary School"
                                    value="#{registrationBean.user.secondarySchool}" />

                                <h:outputText value="High School: " />
                                <p:inputText label="High School"
                                    value="#{registrationBean.user.highSchool}" />
                                <h:outputText value="College: " />
                                <p:inputText label="College"
                                    value="#{registrationBean.user.college}" />
                                <h:outputText value="University: " />
                                <p:inputText label="University"
                                    value="#{registrationBean.user.university}" />
                                <h:outputText value="Degree: " />
                                <p:inputText label="Degree"
                                    value="#{registrationBean.user.degree}" />

                            </h:panelGrid>
                        </p:panel>
                    </p:tab>
                    <p:tab id="other" title="Other">
                        <p:panel header="Other Information">

                            <h:messages errorClass="error" />

                            <h:panelGrid columns="2" columnClasses="label, value">
                                <h:outputText value="Quote: *" />
                                <p:inputText value="#{registrationBean.user.quote}" />

                                <h:outputText value="About Me: " />
                                <p:inputText value="#{registrationBean.user.aboutMe}" />
                                <h:outputText value="Interest: " />
                                <p:inputText value="#{registrationBean.user.interest}" />

                            </h:panelGrid>
                        </p:panel>
                    </p:tab>
                    <p:tab id="confirm" title="Confirmation">
                        <p:panel header="Confirmation">

                            <h:panelGrid id="confirmation" columns="6">

                                <h:outputText value="Username: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.userName}" />
                                <h:outputText value="Firstname: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.firstName}" />
                                <h:outputText value="Lastname: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.lastName}" />
                                <h:outputText value="Password: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.password}" />
                                <h:outputText value="Date of Birth: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.birthDate}" />
                                <h:outputText value="Gender: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.gender}" />
                                <h:outputText value="Relationship: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.relationship}" />
                                <h:outputText value="EmailID: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.email}" />
                                <h:outputText value="Contact No.: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.contactNo}" />
                                <h:outputText value="Street: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.street}" />
                                <h:outputText value="City: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.city}" />
                                <h:outputText value="Pincode: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.pincode}" />
                                <h:outputText value="State: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.state}" />
                                <h:outputText value="Country: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.country}" />
                                <h:outputText value="Secondary School: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.secondarySchool}" />
                                <h:outputText value="High School: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.highSchool}" />
                                <h:outputText value="College: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.college}" />
                                <h:outputText value="University: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.university}" />
                                <h:outputText value="Degree: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.degree}" />
                                <h:outputText value="Quote: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.quote}" />
                                <h:outputText value="About Me: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.aboutMe}" />
                                <h:outputText value="Interest: " />
                                <h:outputText styleClass="outputLabel"
                                    value="#{registrationBean.user.interest}" />
                                <h:outputText />
                                <h:outputText />
                            </h:panelGrid>

                            <p:commandButton value="Submit" update="growl"
                                action="#{registrationBean.Save}" />

                        </p:panel>
                    </p:tab>

                </p:wizard>
4

1 回答 1

1

static {  
        userDB = new ArrayList<User>();  
        Query query = em.createQuery("SELECT u FROM User u", User.class);
        userDB =query.getResultList();

    }

初始化您的用户列表。首次加载 UserConverter 类时会发生一次(何时执行类的静态块?)。在生成自动完成建议时,您可以参考此列表。

当您添加新用户时,此列表永远不会重新生成。这就是您没有看到新添加的用户的原因。

一种创可贴的方法是将代码移动到类方法中,并在每次添加新用户或需要生成建议列表时调用它:

public class UserConverter implements Converter {

public static void regenerateUserDB {  
    Query query = em.createQuery("SELECT u FROM User u", User.class);
    userDB = query.getResultList();
}

}

public class SearchBean {

public List<User> completeUser(String query){
    List<User> suggestions = new ArrayList<User>();
    UserConverter.regenerateUserDB();
    for(User u : UserConverter.userDB){
        if(u.getUserName().startsWith(query))
            suggestions.add(u);
    }

    return suggestions;
}
}

解决此问题的正确方法是使用依赖注入框架,因此您不必在使用的每个类中都构建新的 EMF - 这会浪费资源并可能导致问题。请参阅http://en.wikipedia.org/wiki/Dependency_injection#Java

于 2013-02-27T20:54:31.953 回答