简体   繁体   English

具有POJO和CommandButton的Primefaces自动完成

[英]Primefaces autoComplete with POJO and CommandButton

I have some trouble using Primefaces autoComplete feature. 使用Primefaces自动完成功能时遇到一些麻烦。 First I would like to show my xhtml file. 首先,我想显示我的xhtml文件。

<?xml version='1.0' encoding='UTF-8' ?>
<!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:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:o="http://openfaces.org/"
xmlns:om="http://omnifaces.org/ui"
xmlns:of="http://omnifaces.org/functions"
xmlns:p="http://primefaces.org/ui" >
<ui:composition template="/Template/basicTemplate.xhtml">
    <ui:define name="content">
        <h:form> <h1>Firma anlegen</h1>
        <h:panelGrid columns="2" cellpadding="5">
            <h:outputLabel for="name" value="Name:" style="font-weight:bold" />
            <p:inputText id="name" value="#{registerCompanyBean.company.name}" />
            <h:outputLabel for="name" value="Straße:" style="font-weight:bold" />
            <p:inputText id="street" value="#{registerCompanyBean.postalAddress.street}" />
            <h:outputLabel for="name" value="PLZ:" style="font-weight:bold" />
            <p:inputText id="zipCode" value="#{registerCompanyBean.postalAddress.zipCode}" />
            <h:outputLabel for="name" value="Ort:" style="font-weight:bold" />
            <p:inputText id="city" value="#{registerCompanyBean.postalAddress.city}" />
            <h:outputLabel for="name" value="Land:" style="font-weight:bold" />
            <p:inputText id="country" value="#{registerCompanyBean.postalAddress.country}" />

            <p:outputLabel value="Branche:" for="dd"  style="font-weight:bold" />
            <p:autoComplete id="dd" dropdown="true" value="#{registerCompanyBean.buisnessCategory.name}" completeMethod="#{registerCompanyBean.completeBuisnessCategory}"
                            var="buisnessCategory" itemLabel="#{buisnessCategory.name}" itemValue="#{buisnessCategory}"  converter="buisnessCategoryConverter" forceSelection="true" >
            </p:autoComplete>

        </h:panelGrid>

        <H1>Wartelisten</H1>
        <h:panelGrid columns="2" cellpadding="5">
        </h:panelGrid>
        <p:commandButton id="save" value="Save" action="#{registerCompanyBean.save}" ajax="false"/>
        </h:form>
    </ui:define>
    </ui:composition>
</html>

The Page start without any Error. 页面开始没有任何错误。 I can fill in the input fields and I can use the drop-down Box as aspected. 我可以填写输入字段,并可以使用方面的下拉框。 I can even use the autoComplete function but when I push the CommandButton I get a NullPointerException. 我什至可以使用autoComplete函数,但是当我按下CommandButton时,会收到NullPointerException。 If I remove the ajax attribute of the commandButton, the CommandButton does nothing ( no function call at all). 如果我删除了commandButton的ajax属性,则CommandButton将不执行任何操作(根本不执行任何函数调用)。 So for me it seems that I have to add the ajax=false attribute. 因此,对于我来说,似乎必须添加ajax = false属性。 Any Ideas??? 有任何想法吗???

Thx 谢谢

Michael Schmidt For better understanding I add all the other files. 为了更好地理解,我添加了所有其他文件。

The Converter: 转换器:

/**
*
* @author mibschmidt
*/
@FacesConverter("buisnessCategoryConverter")
public class BuisnessCategoryConverter implements Converter{

    @Override
    public Object getAsObject(FacesContext fc, UIComponent uic, String value) {
        if(value != null && value.trim().length() > 0) {
            try {
                BuisnessCategoryService service = (BuisnessCategoryService) fc.getExternalContext().getApplicationMap().get("buisnessCategoryService");
                return service.findAll().get(Integer.parseInt(value));
            } catch(NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid BuisnessCategory."));
            }
        }
        else {
            return null;
        }
    }

    @Override
    public String getAsString(FacesContext fc, UIComponent uic, Object object) {
        if(object != null) {
            return String.valueOf(((BuisnessCategory) object).getID());
        }
        else {
            return null;
        }
    }   
} 

The ManageBean: ManageBean:

@Controller
@Scope("session")
public class RegisterCompanyBean extends GenericCRUDController<Company, CompanyService> implements Serializable {


    @Autowired
    private BuisnessCategoryService buisnessCategoryService;
    private BuisnessCategory buisnessCategory;

    public BuisnessCategoryService getBuisnessCategoryService() {
        return buisnessCategoryService;
    }

    public void setBuisnessCategoryService(BuisnessCategoryService buisnessCategoryService) {
        this.buisnessCategoryService = buisnessCategoryService;
    }

    public BuisnessCategory getBuisnessCategory() {
        return buisnessCategory;
    }

    public void setBuisnessCategory(BuisnessCategory buisnessCategory) {
        this.buisnessCategory = buisnessCategory;
    }

    @Autowired
    private PostalAddressService postalAddressService;
    private PostalAddress postalAddress =new PostalAddress();

    public PostalAddressService getPostalAddressService() {
        return postalAddressService;
    }

    public void setPostalAddressService(PostalAddressService postalAddressService) {
        this.postalAddressService = postalAddressService;
    }

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

    @Autowired
    private CompanyService companyService;
    private Company company= new Company();


    public PostalAddress getPostalAddress() {
        return postalAddress;
    }

    public void setPostalAddress(PostalAddress postalAddress) {
        this.postalAddress = postalAddress;
    }

    public CompanyService getCompanyService() {
        return companyService;
    }

    public void setCompanyService(CompanyService companyService) {
        this.companyService = companyService;
    }

    public List<BuisnessCategory> getBuisnessCategoryList() {
        return buisnessCategoryService.findAll();
    }

    @Override
    protected CompanyService getService() {
        return companyService;
    }

    public void saveButtonAction(ActionEvent actionEvent) {
        addMessage("Speichern der Firma");
    }



    @Override
    public String save() {

        List <PostalAddress> pAL = new ArrayList<>();
        pAL.add(postalAddressService.save(postalAddress));
        company.setPostalAddress(pAL);
        company.setBuisnessCategory(buisnessCategoryService.save(buisnessCategory));
        company=companyService.save(company);
        if(company==null){
            addMessage("Fehler beim Registrieren der Firma");
        }else{
            addMessage(String.valueOf(company.getID()));
        }

        return super.save(); //To change body of generated methods, choose Tools | Templates.
    }

    public List<BuisnessCategory> completeBuisnessCategory(String query) {
        List<BuisnessCategory> allBuisnessCategory = buisnessCategoryService.findAll();
        List<BuisnessCategory> filteredBuisnessCategory = new ArrayList<>();

        for (int i = 0; i < allBuisnessCategory.size(); i++) {
            BuisnessCategory bk = allBuisnessCategory.get(i);
            if(bk.getName().toLowerCase().contains(query.toLowerCase())) {
                filteredBuisnessCategory.add(bk);
            }
        }

        return filteredBuisnessCategory;
    }

    public void addMessage(String summary) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, summary,  null);
        FacesContext.getCurrentInstance().addMessage(null, message);
    }

}

The Error Message: 错误消息:

at com.wedusch.waitlist.jsf.util.BuisnessCategoryConverter.getAsObject(BuisnessCategoryConverter.java:33)
at org.primefaces.component.autocomplete.AutoCompleteRenderer.getConvertedValue(AutoCompleteRenderer.java:604)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1030)
at javax.faces.component.UIInput.validate(UIInput.java:960)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1233)
at javax.faces.component.UIInput.processValidators(UIInput.java:698)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1214)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1172)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

You must initial object(buisnessCategory) before usage( #{registerCompanyBean.buisnessCategory.name} ). 使用前必须先初始化对象(buisnessCategory)( #{registerCompanyBean.buisnessCategory.name} )。

Initial at constructor 初始于构造函数

public RegisterCompanyBean(){
    buisnessCategory = new BuisnessCategory();
}

Or initial by @PostConstruct 或由@PostConstruct初始化

@PostConstruct
public void init(){
   buisnessCategory = new BuisnessCategory(); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM