2

I have some filters, which grab e.g. a parameter like "id" to check some right (used to load some contents). These filters should ignore all ajax-requests, because e.g. the rights does not have to be checked after every little request (only on page load)

The Problem is, that when I perform an ajax-request, it throws me a null-pointer, because I don't append the ID with ajax requests. I found out, that it still works, when I use and it fails, when I use (both perform ajax requests).

This is my filter:

public class ExtendedAccessFilter implements Filter {


    @Override 
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

            //ignore filter if it is an ajax-request (DOES NOT WORK if not p:commandButton!)
        if(isAJAXRequest(req)){
            chain.doFilter(request, response);
            System.out.println("ABORT FILTER, AJAX");
            return;
        }

        //Nullpointer thrown here (because no Id is submitted)
        int requestedId = Integer.parseInt(request.getParameter("id"));

}

    private boolean isAJAXRequest(HttpServletRequest request) {
      boolean check = false;
      String facesRequest = request.getHeader("Faces-Request");
      if (facesRequest != null && facesRequest.equals("partial/ajax")) {
        check = true;
      }
      return check; 
    }

}

Am I doing something wrong?

Niko
  • 1,054
  • 5
  • 25
  • 52

1 Answers1

1

You are doing it right way. You can also do it using JSF API by checking if PartialViewContext exists and it is an Ajax Request

if(FacesContext.getCurrentInstance().getPartialViewContext() !=null &&
      FacesContext.getCurrentInstance().getPartialViewContext().isAjaxRequest()) {

}
Avinash Singh
  • 3,421
  • 2
  • 20
  • 21
  • 1
    I don't know why this is the accepted answer since `FacesContext` is not available in a filter... See for example: https://stackoverflow.com/a/14046241/3375325 – jansohn Dec 01 '17 at 12:23