确定在Grails的控制器Ajax请求或浏览器请求 [英] Identifying ajax request or browser request in grails controller

查看:124
本文介绍了确定在Grails的控制器Ajax请求或浏览器请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发,它使用大量ajax.If的请求是Ajax调用,那么它应该给予回应(这部分工作)Grails应用程序,但是如果我输入在浏览器的URL就应该把我送到家/索引页,而不是要求page.Below为样本GSP $ C $下AJAX调用。

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 browser it should take me to the home/index page instead of the requested page.Below is the sample gsp code for ajax call.

<g:remoteFunction action="list" controller="todo" update="todo-ajax">

<div id ="todo-ajax">
//ajax call rendered in this area
</div>

如果我们输入的http://本地主机:8080 /短跑/待办事项/列表在浏览器地址栏,控制器应该重定向到的http://本地主机:8080 /短跑/认证/指数

if we type http://localhost:8080/Dash/todo/list in the browser URL bar, the controller should redirect to http://localhost:8080/Dash/auth/index

如何在控制器验证这一点。

How to validate this in controller.

推荐答案

这是一个相当普遍的做法,在你的BootStrap.init关闭添加这个充满活力的方法:

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')
    }

这使您可以测试,如果当前请求是一个Ajax调用这样做:

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

if(request.xhr) { ... }

最简单的解决办法是这样的事情添加到您的TODO行动:

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.

在grails-app / conf目录/ BootStrap.groovy中的完整例子:

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 = {
     }
}

这篇关于确定在Grails的控制器Ajax请求或浏览器请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆