Permalink
Browse files

fix for GRAILS-5542 "'request.xhr' incorrectly identifies ajax requests"

  • Loading branch information...
1 parent 79824f4 commit 51c4921c97440cb54623a6e26709a7e41e60cf29 @graemerocher graemerocher committed Nov 19, 2012
@@ -31,6 +31,6 @@ class ServletsGrailsPlugin {
def dependsOn = [core:version]
def doWithDynamicMethods = { ctx ->
- ServletsGrailsPluginSupport.enhanceServletApi()
+ ServletsGrailsPluginSupport.enhanceServletApi(application.config)
}
}
@@ -32,9 +32,14 @@ import org.codehaus.groovy.grails.plugins.web.api.ServletRequestApi
class ServletsGrailsPluginSupport {
- static enhanceServletApi() {
+ static enhanceServletApi(ConfigObject config = new ConfigObject()) {
def requestEnhancer = new MetaClassEnhancer()
- requestEnhancer.addApi new ServletRequestApi()
+ final servletRequestApi = new ServletRequestApi()
+ final xhrIdentifier = grails?.web?.xhr?.identifier
+ if(xhrIdentifier instanceof Closure) {
+ servletRequestApi.xhrRequestIdentifier = xhrIdentifier
+ }
+ requestEnhancer.addApi servletRequestApi
def getAttributeClosure = { String name ->
def mp = delegate.class.metaClass.getMetaProperty(name)
@@ -28,6 +28,8 @@ import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
*/
class ServletRequestApi {
+ Closure xhrRequestIdentifier = { false }
+
/**
* Whether the request has been redirected
*
@@ -49,7 +51,7 @@ class ServletRequestApi {
* @return test whether the current request is an XHR request
*/
boolean isXhr(HttpServletRequest instance) {
- instance.getHeader('X-Requested-With') != null
+ instance.getHeader('X-Requested-With') == "XMLHttpRequest" || xhrRequestIdentifier(instance)
}
/**
@@ -0,0 +1,41 @@
+package org.codehaus.groovy.grails.plugins.web.api
+
+import spock.lang.Specification
+import org.springframework.mock.web.MockHttpServletRequest
+
+/**
+ */
+class ServletRequestApiSpec extends Specification{
+
+
+ void "Test identification of XHR requests"() {
+ given:"An instance of the servlet API extension"
+ def api = new ServletRequestApi()
+
+ when:"a regular request is used"
+ def request = new MockHttpServletRequest()
+ then:"it isn't an XHR request"
+ api.isXhr(request) == false
+
+ when:"A non XHR request is sent with the X-Requested-With header"
+ request.addHeader("X-Requested-With","com.android.browser")
+
+ then:"It is not an XHR request"
+ api.isXhr(request) == false
+
+ when:"A request is sent with a X-Requested-With value of XMLHttpRequest"
+ request = new MockHttpServletRequest()
+ request.addHeader("X-Requested-With", "XMLHttpRequest")
+
+ then:"It is an XHR request"
+ api.isXhr(request) == true
+
+ when:"A custom XHR request identifier is used"
+ api.xhrRequestIdentifier = { r -> r.getHeader('X-Requested-With') == 'Ext.basex' }
+ request = new MockHttpServletRequest()
+ request.addHeader("X-Requested-With", "Ext.basex")
+
+ then:"It is an XHR request"
+ api.isXhr(request) == true
+ }
+}

0 comments on commit 51c4921

Please sign in to comment.