0

In my work we develop an JSF 2 application. And I need to create a listener bean with one method which have to be executed on every page request. How to accomplish this task?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
vladislavn
  • 388
  • 1
  • 8
  • 20

3 Answers3

0

The answer of your question can be found here.

This method is crucial:

public void beforePhase(PhaseEvent event) {
    if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
        // Do here your job which should run right before the RENDER_RESPONSE.
    }
}

Here you can react on every lifecycle phase and call your apropriate functions inside the needed PhaseId. I hope it helps.

As I see that you use JSF 2, you could also use the following method:

Use this inside your xhtml page:

<f:event type="preRenderView" listener="#{bean.preRenderView}" />

and call the apropriate method in your bean:

public void preRenderView() {
    // Do here your job which should run right before the RENDER_RESPONSE.
}
Community
  • 1
  • 1
Metalhead89
  • 1,740
  • 9
  • 30
  • 58
  • That's the answer to the question *"How to implement a PhaseListener which runs at end of lifecycle?"* which is not necessarily the same question as *"How to call bean method on every page request"*. Even then, if that answer would have applied, you'd better have voted for close as duplicate instead of blatantly copypasting someone else's answer. – BalusC Jan 30 '14 at 08:51
  • @BalusC Of course it is not the same question but it can be used in the bean. And as you mentioned in your answer, the `preRenderView` method would also fit his needs – Metalhead89 Jan 30 '14 at 08:54
0

One way to do it is filter. Create class:

public class MonitoringFilter implements Filter {
    @Override
    public void doFilter(ServletRequest _request, ServletResponse _response,
        FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)_request;
        HttpServletResponse response = (HttpServletResponse)_response;

        // your code here
        chain.doFilter(_request, _response);
    }
}

Register it in web.xml:

  <filter>
    <filter-name>monitoringFilter</filter-name>
    <filter-class>xyz.MonitoringFilter</filter-class>
  </filter>

  <filter-mapping>
    <filter-name>monitoringFilter</filter-name>
    <url-pattern>/*.jsf</url-pattern>
  </filter-mapping>

(setup proper path in url-pattern).

Vasil Lukach
  • 3,658
  • 3
  • 31
  • 40
0

I solved it. At first I tried with filter but it didn't because the filter is called at begining of the request, but at that time FacesContext is not initialised and I needed because I have to retrieve the requested url. So after that I tried with phase listener and it works! In beforePhase() method I listen for PhaseId.RENDER_RESPONSE. Thank you all for guidance.

vladislavn
  • 388
  • 1
  • 8
  • 20