20

HTTP PUT であると思われるコントローラー アクションがありますが、コントローラー アクションで @RequestParam を使用しようとすると、Spring が文句を言います。HTTP PUT メソッドではリクエストパラメータが許可されていませんか?それが Spring が拒否している理由ですか?

@RequestMapping(value = "/{helpDocumentId}/vote", method = RequestMethod.PUT)
public void voteHelpfulness(@PathVariable long helpDocumentId, @RequestParam boolean isHelpful) {
    helpManager.voteOnHelpDocument(helpDocumentId, isHelpful);
}

実行すると、次のエラーがスローされます。

org.springframework.web.bind.MissingServletRequestParameterException: Required boolean parameter 'isHelpful' is not present

もちろん、isHelpfulパラメータは存在します。上記のコードを HTTP POST で完全に機能させることができるので、これが問題ではないことはわかっています。

     $.ajax({
            url: "/help/" + helpDocumentId + "/vote.json",
            type: "PUT",
            data: {
                isHelpful: isHelpful
            },
            success: function(response) {
                // ....
            }
     });

PUT は正しい http メソッドですか? このアクションは を変更しhelpDocumentますが、作成はしません。

4

4 に答える 4

15

Since Spring 3.1, HttpPutFormContentFilter can be used to handle application/x-www-form-urlencoded data:

Filter that makes form encoded data available through the ServletRequest.getParameter*() family of methods during HTTP PUT requests.

The Servlet spec requires form data to be available for HTTP POST but not for HTTP PUT requests. This filter intercepts HTTP PUT requests where content type is 'application/x-www-form-urlencoded', reads form encoded content from the body of the request, and wraps the ServletRequest in order to make the form data available as request parameters just like it is for HTTP POST requests.

For other incoming data, such as JSON, you'll need @RequestBody as explained in JQuery, Spring MVC @RequestBody and JSON - making it work together, to not run into a 415 Unsupported Media Type.

于 2013-01-28T18:41:48.077 に答える
6

Spring コントローラーは GET/HEAD/POST/PUT/DELETE/OPTIONS/TRACE をサポートしますが、ブラウザーがこれらのリクエスト メソッドを送信できない可能性があるため、機能しません。

回避策は、Spring が提供する「org.springframework.web.filter.HiddenHttpMethodFilter」を使用することです。リクエスト メソッドに隠しパラメータを渡す必要があります。このフィルターでサポートされるデフォルトのパラメーターは「_method」です。

詳細については、フィルターの javadoc を確認してください。

于 2011-12-05T12:00:19.470 に答える
3

上記のように、これは のバグのようspring/servlet APIです。実際には、リクエストはリクエスト パラメータではなく、PUT機能するはずです。Request Body (or payload)そういう意味ではサーブレットAPI&Springの扱いは正しい。

そうは言っても、呼び出しからデータ要素を渡さずjavascript/jQuery、URL 自体の一部としてパラメーターを渡すことは、より優れた、より簡単な回避策です。つまり、GET呼び出しで行うように、url フィールドにパラメーターを設定します。

$.ajax({
            url: "/help/" + helpDocumentId + "/vote.json" + "?param1=param2Val&..",
            type: "PUT",
            data: "",
            success: function(response) {
                // ....
            }
     });

これは単純なパラメーターでは機能しますが、複雑な JSON 型では機能しないと思います。お役に立てれば。

于 2012-01-20T11:22:43.847 に答える
0

コメントの推奨事項に従い、に変更@RequestParamしました@RequestBodyが、うまくいきました(私のパラメーターは文字列です)。

これは Spring のバグであることに同意します。これは、実稼働環境 (を使用している場合) で失敗するのとまったく同じコードが@RequestParamlocalhost でも正常に機能するためです。

于 2015-01-26T18:04:13.753 に答える