Странности метода Grails «не разрешены»

У меня есть простой код контроллера, например:

// UserController.groovy

class UserController {

    static allowedMethods = [
            signIn:       'GET',
            authenticate: 'POST',
            signOut:      'POST',
            register:     'GET',
            save:         'POST'
    ]

    // ... code omitted

    def register() { }

    def save() {
        render 'ok'
    }
}

Форма регистрации:

<!-- register.gsp -->
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name="layout" content="main" />
    <title>Withme: Register</title>
</head>
<body>
    <g:form mapping="register">
        <!-- Code omitted -->
        <g:actionSubmit value="Register" />
    </g:form>
</body>
</html>

И сопоставления URL:

//UrlMappings.groovy

class UrlMappings {
    static mappings = { 
        name register: '/register'(controller: 'user') {
            action = [GET: 'register', POST: 'save']
        }
    }
}

Теперь о странной части. При выполнении запроса с помощью curl все работает как положено:

$ curl http://localhost:8080/withme/register -X GET -v -L
... form rendered ...

$ curl http://localhost:8080/withme/register -X POST -v -L
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Content-Type: text/html;charset=utf-8
< Transfer-Encoding: chunked
< Date: Thu, 08 Aug 2013 07:41:23 GMT
< 
* Connection #0 to host localhost left intact
ok* Closing connection #0 

Доступ к /register с помощью браузера возвращает форму. Но когда я отправляю его в браузере, возвращается 405!

HTTP Status 405 -

type Status report

message

description The specified HTTP method is not allowed for the requested resource.
Apache Tomcat/7.0.42

Firebug подтверждает, что POST выполняется:

POST http://localhost:8080/withme/register | 405 Method Not Allowed | localhost:8080

Я отключил все фильтры в своем приложении.

Интересно, в чем разница между curl и POST-запросами браузера? Почему Grails обрабатывает это по-другому? И, наконец, как это исправить.

Grails 2.2.4 Groovy Версия: 2.1.6 JVM: 1.7.0_21 Поставщик: Oracle Corporation ОС: Mac OS X

Обновить

Я понял, что тело запроса имеет значение. Отправка запроса с завитком без тела завершается успешно, но установка тела приводит к сбою запроса. Неплохо:

$ curl http://localhost:8080/withme/register -X POST -v -L
* About to connect() to localhost port 8080 (#0)
*   Trying ::1...
* connected
* Connected to localhost (::1) port 8080 (#0)
> POST /withme/register HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5
> Host: localhost:8080
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< Content-Type: text/html;charset=utf-8
< Transfer-Encoding: chunked
< Date: Thu, 08 Aug 2013 09:39:22 GMT
< 
* Connection #0 to host localhost left intact
ok* Closing connection #0

И плохой:

$ curl http://localhost:8080/withme/register -X POST -v -L -d "email=&password=&passwordConfirmation=&firstName=&lastName=&country=&city=&_action_Register=Register"
* About to connect() to localhost port 8080 (#0)
*   Trying ::1...
* connected
* Connected to localhost (::1) port 8080 (#0)
> POST /withme/register HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8x zlib/1.2.5
> Host: localhost:8080
> Accept: */*
> Content-Length: 100
> Content-Type: application/x-www-form-urlencoded
> 
* upload completely sent off: 100 out of 100 bytes
< HTTP/1.1 405 Method Not Allowed
< Server: Apache-Coyote/1.1
< Content-Type: text/html;charset=utf-8
< Content-Length: 977
< Date: Thu, 08 Aug 2013 09:40:31 GMT
< 
* Connection #0 to host localhost left intact
<html><head><title>Apache Tomcat/7.0.42 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 405 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>The specified HTTP method is not allowed for the requested resource.</u></p><HR size="1" noshade="noshade"><h3>Apache Tomcat/7.0.42</h3></body></html>* Closing connection #0

Все же какая разница?


person lambdas    schedule 08.08.2013    source источник


Ответы (1)


Я решил странную проблему.

Grails отображает <g:actionSubmit value="Register" /> как

<input type="submit" value="Register" name="_action_Register">

Обратите внимание на странное имя. Grails выводит его из атрибута value и использует при выборе вызываемого действия. В моем случае это вызывает проблемы, потому что POST /register должно обрабатываться действием save.

Изменение его на <input type="submit" value="Register"> решит проблему.

person lambdas    schedule 08.08.2013
comment
Интересно, но если у вас есть форма с правильным действием, просто используйте g:submitButton. Как вы поняли, g:actionSubmit создаст это волшебное имя и отправит вашу форму другому действию (используйте, когда вам нужно действие отправки != действие формы). - person ; 08.08.2013
comment
Я бы не назвал это странной проблемой — так это работает согласно документации. - person ikumen; 08.08.2013