Grails形式& URL映射

时间:2012-06-22 07:49:30

标签: forms grails gsp

我正在编写一个Grails应用程序,我想设置一个允许用户输入图像ID号的表单,该值将传递给控制器​​/操作,该控制器/操作从S3检索给定图像ID的图像

所需的网址格式为example.com/results/1234。我设置了以下URL映射:

class UrlMappings {

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

        "/results/$id?" {
            controller = "s3Image"
            action = "getS3Image"
        }

        "/"(view:"/index")
        "500"(view:'/error')
    }
}

以下是我如何设置表单:

<g:form  controller="results" method="get">
    <input type="text" name="id" class="input-xxlarge" placeholder="http://www.example.com">
      <button class="btn btn-inverse">Submit</button>
</g:form> 

但是,这似乎将表单提交到example.com/results?id=12345。

我如何更改表单或映射,以便在提交表单后生成所需的URL?

谢谢!

4 个答案:

答案 0 :(得分:3)

<g:form  controller="results" method="get">

将生成一个HTML表单,其操作URL为/results(名为“results”的控制器的反向URL映射,没有操作或id)。提交此表单后,浏览器会将?id=1234添加到此URL的末尾,因为表单方法是GET。这不是您可以在服务器端的URL映射中影响的内容。

相反,您应该将表单POST发送到重定向到getS3Image操作的其他控制器操作。重定向将有权访问服务器端的ID,因此可以为重定向生成友好的URL。

UrlMappings:

"/results/$id?" {
    controller = "s3Image"
    action = "getS3Image"
}

"/findImage" {
    controller = "s3Image"
    action = "find"
}

S3ImageController:

def find() {
    redirect(action:"getS3Image", id:params.id)
}

def getS3Image() {
    // as before
}

GSP:

<g:form  controller="s3Image" action="find" method="post">
    <input type="text" name="id" class="input-xxlarge" placeholder="http://www.example.com">
      <button class="btn btn-inverse">Submit</button>
</g:form>

答案 1 :(得分:1)

德里克,

你所看到的是正确的行为。对于GET请求,您有两件事

  1. 请求的网址
  2. 参数
  3. 使用urlencode在url之后附加参数,并用&amp;分隔,因此,当您使用网址http://mydomain.com/controller/action/表单时,在此表单中您有两个字段:id,name,然后,在提交后,他们将像这样传递:http://mydomain.com/controller/action/?id=3&name=someName

    URLMappings仅映射其中的URL部分。因此,在您的示例中,UrlMapping仅与/ results /匹配,并且不传递ID。

    但是没关系,因为您仍然可以访问控制器中的id参数,就这样做(在s3Image控制器内):

    def getS3Image() {
         def id = params.id
    }
    

答案 2 :(得分:0)

我认为你有两个问题。首先,UrlMappings规则按照从上到下的外观顺序进行匹配。 grails匹配的第一条规则是"/$controller/$action?/$id?"。移动您的规则"/results/$id?",它应该优先。 - 检查帖子下面的评论。

你的第二个错误是表格的声明。我想你的意思是:

<g:form controller="s3Image" method="getS3Image">

答案 3 :(得分:0)

在UrlMapping中尝试非常简单的更改:

"/results/$id?" {
    controller = "s3Image"
    action = "getS3Image"
    id = $id
}

然后确定您可以通过以下方式在s3Image控制器中访问该标识:

def id = params.id