【问题标题】:How to detect which view file has been rendered in grails如何检测在grails中渲染了哪个视图文件
【发布时间】:2013-10-25 14:40:13
【问题描述】:

当视图文件被 grails 渲染时,我必须知道它。一种方法是过滤器中的 grails afterView 操作。在这里,我找不到知道渲染了哪个视图文件的方法。 那么,有没有什么方法可以让我知道哪个视图文件已经被 render 方法渲染了?

【问题讨论】:

  • 你能提供一个用例的例子吗?您想根据 viewName 在 afterView 过滤器中添加一些内容吗?
  • 是的,我正在服务器端进行访问页面跟踪。是的,我只想记录视图文件名以进行跟踪。实际上,这个文件映射到某个页面对象,这就是将要使用的对象。

标签: grails filter


【解决方案1】:

这并不漂亮,但在大多数情况下它应该可以工作。在afterafterView 中使用它:

String viewName
def webRequest = RequestContextHolder.currentRequestAttributes()
if (webRequest.renderView) {
   def controller = request.getAttribute(GrailsApplicationAttributes.CONTROLLER)
   def modelAndView = getModelAndView()
   if (!modelAndView && controller) {
      modelAndView = controller.modelAndView
   }
   if (modelAndView) {
      viewName = modelAndView.viewName
   }
   else if (controller) {
      // no ModelAndView, so infer from controller and action
      viewName = '/' + controllerName + '/' + actionName
   }
   else {
      // no controller, direct GSP
      String uri = webRequest.attributes.urlHelper.getPathWithinApplication(request)
      for (info in WebUtils.lookupUrlMappings(servletContext).matchAll(uri)) {
         if (info?.viewName) {
            viewName = info.viewName
            break
         }
      }
   }
}

您将需要这些导入:

import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.codehaus.groovy.grails.web.util.WebUtils
import org.springframework.web.context.request.RequestContextHolder

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-17
    相关资源
    最近更新 更多