Java – with JSF 2.0 / facelets, is there a way to attach a global listener to all Ajax calls?
Is there a way to attach a global listener to all Ajax calls in JSF? Perhaps through a stage of the audience?
This is the problem... Let's say that you use the F: Ajax tag and Apache Shiro, and you expire your session Then you come back and click a button with F: Ajax The server will respond by redirecting to the login page through 302
Users can't see anything They can click and invoke Ajax calls repeatedly, but for them, the application is just "dead"
So, my question is, is there a way to attach a listener to all Ajax calls in JSF? If so, what I want to do is monitor the response code For redirection, use window Send them by navigator
I'm always happy to hear how others solve this problem! thank you!
Solution
Yes, phaselistener can do it A systemeventlistener is also available A filter is also available
If you are in a JSF context, you can check whether the current request is an Ajax request
if (FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()) { // It's an ajax request. }
If you are not in a JSF context, such as in a filter, you can check whether the current request is a JSF Ajax request
if ("partial/ajax".equals(request.getHeader("Faces-Request"))) { // It's a JSF ajax request. }
Forcing redirection of Ajax requests requires a special XML response When you are in a JSF context, externalcontext#redirect () implicitly takes it into account All you need to do is write this:
FacesContext.getCurrentInstance().getExternalContext().redirect(url);
If you are not in a JSF context, such as in a filter, you need to write the entire XML response yourself For example
response.setContentType("text/xml"); response.getWriter() .append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") .printf("<partial-response><redirect url=\"%s\"></redirect></partial-response>",url);