Identifying ajax request or browser request in grails controller

前端 未结 3 441
小蘑菇
小蘑菇 2021-02-04 04:52

I am developing a grails application which uses lot of ajax.If the request is ajax call then it should give response(this part is working), however if I type in the URL in the b

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-04 05:30

    It's quite a common practice to add this dynamic method in your BootStrap.init closure:

        HttpServletRequest.metaClass.isXhr = {->
             'XMLHttpRequest' == delegate.getHeader('X-Requested-With')
        }
    

    this allows you to test if the current request is an ajax call by doing:

    if(request.xhr) { ... }
    

    The simplest solution is to add something like this to your todo action:

    if(!request.xhr) { 
        redirect(controller: 'auth', action: 'index')
        return false
    }
    

    You could also use filters/interceptors. I've built a solution where I annotated all actions that are ajax-only with a custom annotation, and then validated this in a filter.

    Full example of grails-app/conf/BootStrap.groovy:

    import javax.servlet.http.HttpServletRequest
    
    class BootStrap {
    
         def init = { servletContext ->
    
            HttpServletRequest.metaClass.isXhr = {->
                'XMLHttpRequest' == delegate.getHeader('X-Requested-With')
            }
    
         }
         def destroy = {
         }
    } 
    

提交回复
热议问题