Spring MVC检测到Ajax请求

编程入门 行业动态 更新时间:2024-10-07 18:26:48
本文介绍了Spring MVC检测到Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何以最佳方式检测ajax请求?

How to detect an ajax request in the best possible way?

我当前在控制器中使用它:

I'm currently using this in my controller:

private boolean isAjax(HttpServletRequest request){ String header = request.getHeader("x-requested-with"); if(header != null && header.equals("XMLHttpRequest")) return true; else return false; }

但是我不喜欢这种方式,我认为Spring应该有更好的解决方案.

But I don't like this way, I think there should have a better solution with Spring.

推荐答案

这是检测Ajax请求的唯一通用"方法.

That is the only "generic" way to detect an Ajax request.

但是请记住:这不是故障预防,这只是尽力而为的尝试,可以在不发送 X-Requested-With 标头.

But keep in mind: that's not failproof, it is just a best effort attempt, it is possible to make an Ajax request without sending the X-Requested-With headers.

jQuery通常包含该标头.也许另一个库没有.该协议当然不认为该标头是必需的.

jQuery usually includes that header. Maybe another lib doesn't. The protocol certainly doesn't consider that header mandatory.

请注意:您的代码是完全有效的,尽管您可以编写得更简单:

Just a note: Your code is perfectly valid, though you could write it a bit simpler:

private boolean isAjax(HttpServletRequest request) { String requestedWithHeader = request.getHeader("X-Requested-With"); return "XMLHttpRequest".equals(requestedWithHeader); }

更多推荐

Spring MVC检测到Ajax请求

本文发布于:2023-11-26 21:51:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635334.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:检测到   Spring   MVC   Ajax

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!