1

I'm try to generate a commandButton on primefaces 5.1, but I have an error:

Here the xhtml file:

<h:head>
</h:head>

<h:body styleClass="appDefaultBg">

    <h:form>
        <p:remoteCommand autoRun="true" action="#{bean.pageRender()}" update=":pageElement" />
    </h:form>

    <h:panelGroup id="pageElement">
    </h:panelGroup>

</h:body>

Here the bean class:

@ManagedBean(name = "bean")
@SessionScoped
public class Bean implements Serializable {

private static final String PAGE_ELEMENT = "pageElement";

private UIComponent page;

@PostConstruct
public void init() {
    findComponent();
}

public void findComponent() {
    FacesContext.getCurrentInstance().getViewRoot().invokeOnComponent(FacesContext.getCurrentInstance(), PAGE_ELEMENT, new ContextCallback() {
        @Override
        public void invokeContextCallback(FacesContext context, UIComponent component) {
            page = component;
        }
    });
}

public void pageRender() {
    HtmlForm form = new HtmlForm();

    Panel panel = new Panel();
    panel.setId("filter");
    panel.setHeader("Header");

    CommandButton customButton = new CommandButton();
    customButton.setValue("Click me!");
    customButton.addActionListener(new CustomActionListener(5));

    panel.getChildren().add(customButton);
    form.getChildren().add(panel);
    page.getChildren().add(form);

}
}

Here the CustomActionListener:

public class CustomActionListener implements ActionListener {

    private int u;

    public CustomActionListener(int u) {
        this.u = u;
    }

    @Override
    public void processAction(ActionEvent event) throws AbortProcessingException {
        System.out.println(u);
    }
}

The error that I receive when I press the button is:

GRAVE: java.lang.InstantiationException: my.package.CustomActionListener
java.lang.IllegalStateException: java.lang.InstantiationException: my.package.CustomActionListener
    at javax.faces.component.StateHolderSaver.restore(StateHolderSaver.java:153)
    at javax.faces.component.AttachedObjectListHolder.restoreState(AttachedObjectListHolder.java:158)
    at javax.faces.component.UIComponentBase.restoreState(UIComponentBase.java:1611)
    at com.sun.faces.application.view.StateHolderSaver.restore(StateHolderSaver.java:165)
    at com.sun.faces.application.view.FaceletPartialStateManagementStrategy.restoreDynamicAdd(FaceletPartialStateManagementStrategy.java:274)
    at com.sun.faces.application.view.FaceletPartialStateManagementStrategy.restoreDynamicActions(FaceletPartialStateManagementStrategy.java:227)
    at com.sun.faces.application.view.FaceletPartialStateManagementStrategy.restoreView(FaceletPartialStateManagementStrategy.java:395)
    at com.sun.faces.application.StateManagerImpl.restoreView(StateManagerImpl.java:138)
    at com.sun.faces.application.view.ViewHandlingStrategy.restoreView(ViewHandlingStrategy.java:123)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.restoreView(FaceletViewHandlingStrategy.java:585)
    at com.sun.faces.application.view.MultiViewHandler.restoreView(MultiViewHandler.java:150)
    at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:197)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:121)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    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.springframework.orm.hibernate3.support.OpenSessionInViewFilter.doFilterInternal(OpenSessionInViewFilter.java:198)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at com.synapsis.catalina.realm.filter.AlertChangePWDBefore.doFilter(AlertChangePWDBefore.java:106)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at com.synapsis.catalina.realm.filter.SingleLogOnFilter.doFilter(SingleLogOnFilter.java:123)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at com.synapsis.catalina.realm.filter.DefaultUserFilter.doFilter(DefaultUserFilter.java:118)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at com.synapsis.sio.ward.usercontext.controller.filter.UserContextFilter.doFilter(UserContextFilter.java:168)
    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:610)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.authenticator.SingleSignOn.invoke(SingleSignOn.java:339)
    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:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.InstantiationException: my.package.CustomActionListener
    at java.lang.Class.newInstance(Class.java:359)
    at javax.faces.component.StateHolderSaver.restore(StateHolderSaver.java:150)
    ... 51 more

If I remove arguments from constructor i doesn't receive this error. But I need to pass an argument to my CustomerActionListener. How can I fix?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
programmer
  • 35
  • 6
  • What are you trying to achieve (from a functional point of view, not technical)? Since the code example is something I've never seen before. – Kukeltje Jan 29 '15 at 10:56
  • What I want to do is to create a page from java code, dynamically. – programmer Jan 29 '15 at 11:16
  • Lots of examples for this: http://java.dzone.com/articles/creating-jsf-pages-pure-java... But it looks like you want to do it sort of lazy or rather update a part of the page was loaded (do it via a remote command with an autorun="true"...) Or does the page actually work when not passing the argument? Or do I miss something ? – Kukeltje Jan 29 '15 at 11:28
  • thanks for the link. As you can see they create an actionListener so as me. But I need to pass some arguments into the constructor, or in other way. The problem is that if I generate the constructor with arguments I will have the described error, otherwise, with a set method, I can see that the button click action will generate a new ActionListener, and so I lost the setted parameter. – programmer Jan 29 '15 at 11:36
  • Did you try `CustomActionListener al = new CustomActionListener(); al.setU(5); customButton.addActionListener(al);` Or something similar? (sorry for the formatting... cannot get it right in a comment) – Kukeltje Jan 29 '15 at 12:03
  • And don't use 'new CommandButton()' etc... use FacesContext.getCurrentInstance()..getApplication().createComponent(CommandButton.COMPONENT_TYPE); – Kukeltje Jan 29 '15 at 12:13
  • Nothing changes with the createComponent method. – programmer Jan 29 '15 at 12:58

2 Answers2

0

You need to have a default constructor at CustomActionListener (apart from the customized one).

Luís Soares
  • 5,726
  • 4
  • 39
  • 66
  • while this is true, it will cause the ActionListener to be (re-)constructed with a unset value. So he losses the chance to get the "5" inside the event processing. – dognose Jan 28 '15 at 19:50
  • Sorry Luis but I can't understand what you mean with: call an actionListener directly... – programmer Jan 29 '15 at 09:23
  • But I want create a page from java code, dynamically. – programmer Jan 29 '15 at 11:19
  • 1
    why? curiosity. still... why don't you create a setU(int u) and set it after the constructor – Luís Soares Jan 29 '15 at 11:49
  • I did try this solution. But when I press the button, the value is null. This because the CustomActionListener will be created again. – programmer Jan 29 '15 at 12:51
  • I'm try this solution because I doesn't know the page content... I have to create it dynamically... in example, a client user, can add some input field by the definition of them in an appropriate structure. – programmer Jan 29 '15 at 12:56
  • You mean.. any user can add fields? There are components for that. Creating components in Java is not nice... web designers don't have an easy task.. – Luís Soares Jan 29 '15 at 14:20
  • Yes, any user can add fields, button and table. Exists a component for that? Can you help me to find the way?? – programmer Jan 29 '15 at 14:50
  • I agree with @BalusC This seems a XY problem. check this: http://www.primefaces.org/showcase/ui/misc/collector.xhtml and this: http://pastebin.com/uaunHXYa – Luís Soares Jan 29 '15 at 15:31
0

Ignoring the strange design approach (feel free to ask a question on how to properly achieve the concrete functional requirement for which you possibly incorrectly thought that this would be the right solution), you can solve it by letting it implement Externalizable. This is an extension on Serializable which allows you to take over the responsibility to serialize properties.

Here's a kickoff example:

public class CustomActionListener implements ActionListener, Externalizable {

    private int u;

    public CustomActionListener() {
        // Keep default c'tor alive for serialization.
    }

    public CustomActionListener(int u) {
        this.u = u;
    }

    @Override
    public void processAction(ActionEvent event) throws AbortProcessingException {
        System.out.println(u);
    }

    @Override
    public void writeExternal(ObjectOutput output) throws IOException {
        output.writeInt(u);
    }

    @Override
    public void readExternal(ObjectInput input) throws IOException, ClassNotFoundException {
        u = input.readInt();
    }

}
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Sorry, but why did you say that this is a strange approach? I need to design the page dynamically... And for dynamically I mean that a logged Client user, can have the possibility to add some input text, or table, ... with the definition of this into a specific configuration place. – programmer Jan 29 '15 at 13:02
  • Yes, I'm agree with you. But I have to offer this possibility at a logged User. Have you got a better solution to suggest me? Ah.. your solution does work. – programmer Jan 29 '15 at 13:22