12

My validator needs to know if it is a full request or an ajax request. In my current solution I check the http request header for the X-Requested-With element:

public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    HttpServletRequest req = (HttpServletRequest) context.getExternalContext().getRequest();
        if (req.getHeader("X-Requested-With") != null) {
           // do something
        } else {
           // do something else
        }
       ...
}

Is there a better approach to achieve this? Is my solution "safe" with respect to different browsers / javascript libs?

UPDATE:

Just found out that the X-Requested-With header is only present if the ajax request comes from the Primefaces component library (the <p:ajax>tag).

It is not present if I use plain JSF <f:ajax>. So my approach won't work with <f:ajax>.

Using <f:ajax> there is a different header:

Faces-Request:partial/ajax

The solution proposed by Osw works for <f:ajax> and <p:ajax>:

PartialViewContext#isAjaxRequest()

2 Answers 2

18

I would not rely on http header. Never tried it by myself, but you could do the following:

PartialViewContext pvc = facesContext.getPartialViewContext();
if(pvc.isAjaxRequest()) {
// ...
} else {
// ...
}

Another option is using isPartialRequest() instead of isAjaxRequest()

Sign up to request clarification or add additional context in comments.

Thanks for your answer. Sounds good. Do you know what the method does? Maybe just checks for headers too.
@Matt, sorry, no idea what it does exactly, but options are checking headers or checking request parameter map.
Updated my question. It looks like my solution isn't safe.
This is correct. And if you happen to use OmniFaces, there is the Faces-class, which provides isAjaxRequest() as a shortcut and is also available in EL as #{faces.ajaxRequest}.
1

I'd that it is a reliable way to check it. This is exactly how for example Django checks for AJAX requests:

 def is_ajax(self):
        return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

Also listed here as such: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields

Thanks for your answer. Updated my questions. Seems like my solution isn't safe.

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.