问题
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?
回答1:
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.
}
回答2:
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).
回答3:
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.
来源:https://stackoverflow.com/questions/21440904/how-to-call-bean-method-on-every-page-request