区分在JSF的自定义验证完整的请求Ajax请求自定义、完整、JSF、Ajax

2023-09-10 16:40:09 作者:浮光掠影。

我的验证需要知道,如果它是一个完整的请求或Ajax请求。在我目前的解决方案,我检查了 X-要求 - 以元素中的HTTP请求头:

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
        }
       ...
}

有没有更好的方式来实现这一目标?是我的解决方案安全对于不同的浏览器/ JavaScript的库?

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

更新:

刚刚发现的 X-请求,使用的头部仅有present如果Ajax请求来自Primefaces组件库(即<电话号码:AJAX&GT ; 标记)。

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).

这是不可以 present如果我使用普通的JSF &LT; F:AJAX&GT; 。 所以我的做法会不会与工作 &LT; F:。AJAX&GT;

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

使用&LT; F:AJAX&GT; 有不同的页眉:

Faces-Request:partial/ajax

提出OSW该解决方案适用于&LT; F:AJAX&GT; &LT;电话号码:AJAX&GT;

PartialViewContext#isAjaxRequest()

推荐答案

我不会依赖于HTTP标头。从来没有尝试过我自己,但你可以做到以下几点:

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 {
// ...
}

另一种方法是使用 isPartialRequest()而不是 isAjaxRequest()