【问题标题】:Include name in Grails URLs在 Grails URL 中包含名称
【发布时间】:2012-05-16 18:21:33
【问题描述】:

在我的 Grails 应用程序中,我有几个域类,例如 AuthorBook。我正在使用默认的 URL 映射:

static mappings = {
  "/$controller/$action?/$id?"{
    constraints {
      // apply constraints here
    }
  }
}

因此,显示 id 为 2 的图书的相对 URL 是 /book/show/2。要显示 ID 为 5 的作者,它是 /author/show/5AuthorBook 类都有一个 name 属性,但不能保证它是唯一的。

出于 SEO 原因,我想在这些 URL 中包含此名称,例如将显示书籍的 URL 更改为 /book/show/2/the+davinci+code,将显示作者的 URL 更改为 /author/show/5/dan+brown

为了防止破坏任何现有(外部)链接到我的页面,我希望同时支持这两种格式,这样以下任一格式都会显示 Dan Brown 的页面

  • /author/show/5
  • /author/show/5/dan+brown

我从现在的位置(仅带有 ID 的 URL)到我想去的位置(也支持带有 ID 和名称的 URL)的最简单方法是什么?

【问题讨论】:

    标签: grails groovy url-rewriting seo


    【解决方案1】:

    我没试过,但是你能不能尝试添加另一个规则:

    "/author/show/$id/$name"{
        constraints {
            controller='author'
            action='show'
        }
    }
    

    那么您将能够在控制器参数中同时获取 id 和 name

    def show(id, name) {
    
    }
    

    【讨论】:

      【解决方案2】:

      唐,

      你有两个选择。首先,如果您根本不打算在逻辑中使用名称(这似乎是一种选择,因为您已经拥有唯一的 id),那么您可以通过以下方式修改 url 映射:

      static mappings = {
        "/$controller/$action?/$id?/$extra?"{
          constraints {
            // apply constraints here
          }
        }
      }
      

      这将为所有请求添加额外的可选参数。如果您只想为 AuthorBook 控制器执行此操作,那么您应该像这样修改 UrlMappings.groovy

      static mappings = {
          "/author/show/$id?/$name?" (controller:"author", action: "show")
          "/book/show/$id?/$name?" (controller:"book", action: "show")
          "/$controller/$action?/$id?" {
                constraints {
                // apply constraints here
                }
          }
      }
      

      前两条规则将匹配诸如“/author/show/10/dan+brown”之类的 url,以及仅匹配“/author/show/10”,您可以从 show 访问 name 参数方法通过 params.name.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多