实际上,两者一般都是通过HTTP的POST请求。区别是浏览器提交Form表单后,期望服务器返回一个完整的HTML页面。而AJAX调用是由XMLHttpRequest对象(不同浏览器可能不一样)发出,浏览器期望服务器返回HTML片段即可,具体是JSON、XML等都没有要求。返回到浏览器后如何使用,也是由JS脚本自己决定的。
那么对于服务器端,如何判断一个HTTP请求是不是AJAX调用?这需要看HTTP的Header。
我们可以通过Header中的x-request-with来判断。尽管不同浏览器发送AJAX请求的对象不同,但是如果使用jQuery发送AJAX请求的话,jQuery内部实现ajax的时候,已经加入了标识。jQuery源码中是这样的:xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
所以,如果项目的前台页面都是通过jQuery发送AJAX请求的话,这样判断是安全的。
下面是HTTP请求携带的Header信息。
普通Form表单提交
===MimeHeaders ===
accept = */*
referer =http://localhost:8080/user2/toQueryPage.action
accept-language = zh-CN
user-agent = Mozilla/4.0 (compatible; MSIE8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C;.NET4.0E)
accept-encoding = gzip, deflate
host = localhost:8080
connection = Keep-Alive
cache-control = no-cache
AJAX调用(IE)
===MimeHeaders ===
x-requested-with = XMLHttpRequest
accept-language = zh-cn
referer =http://localhost:8080/user2/toQueryPage.action
accept = application/json, text/javascript,*/*; q=0.01
content-type =application/x-www-form-urlencoded
accept-encoding = gzip, deflate
user-agent = Mozilla/4.0 (compatible; MSIE8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C;.NET4.0E)
host = localhost:8080
content-length = 57
connection = Keep-Alive
cache-control = no-cache
在Action类中,通过ServletRequestAware接口获得HttpServletRequest对象,再通过getHeader方法得到我们想要的头信息。
public abstract class BaseAction <ParamVo extends BaseParamVo, ResultVo extends BaseResultVo> extends ActionSupport implements ServletRequestAware { private static final String AJAX_RESULT_NAME = "ajaxResult"; private static final String XHR_OBJECT_NAME = "XMLHttpRequest"; private static final String HEADER_REQUEST_WITH = "x-requested-with"; /** * Request对象,用来判断请求是否是AJAX调用 */ private HttpServletRequest request; private ParamVo paramVo; private ResultVo resultVo; @Override public String execute() { String resultPage = SUCCESS; try { resultVo = doExecute(paramVo); } catch (BaseException e) { resultPage = ERROR; } if (XHR_OBJECT_NAME.equals(request.getHeader(HEADER_REQUEST_WITH))) { resultPage = AJAX_RESULT_NAME; } return resultPage; } }