Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/grails/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在GrailsURL中包含名称_Grails_Groovy_Url Rewriting_Seo - Fatal编程技术网

在GrailsURL中包含名称

在GrailsURL中包含名称,grails,groovy,url-rewriting,seo,Grails,Groovy,Url Rewriting,Seo,在我的Grails应用程序中,我有几个域类,比如Author和Book。我正在使用默认的URL映射: static mappings = { "/$controller/$action?/$id?"{ constraints { // apply constraints here } } } 因此,显示id为2的书籍的相对URL是/book/show/2。要显示id为5的作者,它是/author/show/5。Author和Book类都有name属性,但这不

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

static mappings = {
  "/$controller/$action?/$id?"{
    constraints {
      // apply constraints here
    }
  }
}
因此,显示id为2的书籍的相对URL是
/book/show/2
。要显示id为5的作者,它是
/author/show/5
Author
Book
类都有
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),最简单的方法是什么?

我没有尝试过,但是,您能尝试添加另一条规则吗:

"/author/show/$id/$name"{
    constraints {
        controller='author'
        action='show'
    }
}
然后,您将能够在控制器参数中获取id和名称

def show(id, name) {

}

你有两个选择。首先,如果您根本不打算在逻辑中使用名称(这似乎是一个选项,因为您已经有了唯一的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
          }
    }
}
前两条规则将匹配URL,如“/author/show/10/dan+brown”以及“/author/show/10”,您可以通过params.name从show方法访问name参数