5

私はSpringで作業しており、コントローラーで@ResponseBodyへのajax呼び出しを試みています。

アップデート

さて、言われた変更をajax設定に追加しました。私のパラメータ「jtSearchParam」には、IEでも同じエンコーディングの問題があります。+ 別のエラー 406 が発生しました。応答ヘッダーのコンテンツ タイプが間違っています。

これが私の新しいコードです

コントローラ:

@RequestMapping(method = RequestMethod.POST, consumes="application/json; charset=utf-8", produces="application/json; charset=utf-8")
    public @ResponseBody JSONObject getUsers(@RequestParam int jtStartIndex, @RequestParam int jtPageSize,
            @RequestParam String jtSorting, @RequestParam String jtSearchParam,
            HttpServletRequest request, HttpServletResponse response) throws JSONException{

        Gson gson = new GsonBuilder()
                .setExclusionStrategies(new UserExclusionStrategy())
                .create();

        List<User> users = userService.findUsers(jtStartIndex ,jtPageSize, jtSorting, jtSearchParam);
        Type userListType = new TypeToken<List<User>>() {}.getType();

        String usersJsonString = gson.toJson(users, userListType);
        int totalRecordCount = userDao.getAmountOfRows(jtSearchParam);

        usersJsonString = "{\"Message\":null,\"Result\":\"OK\",\"Records\":" + usersJsonString + ",\"TotalRecordCount\":" + totalRecordCount + "}";

        JSONObject usersJsonObject = new JSONObject(usersJsonString);

        return usersJsonObject;
    }

ご覧のとおり、コンテンツタイプを設定しましproducesたが、それは役に立ちません。応答ヘッダーをデバッグすると、次のようになります: (これにより、ブラウザーから 406 Not Acceptable が発生します)

応答ヘッダー

そして私の新しいajax設定:

...
headers: { 
                 Accept : "application/json; charset=utf-8",
                "Content-Type": "application/json; charset=utf-8"
            },
            contentType: "application/json; charset=utf-8",
            mimeType:"application/json; charset=UTF-8",
            cache:false,
            type: 'POST',
            dataType: 'json'
...

そして、私のパラメータはIEでも同じように見えます!

IE デバッグ値

4

4 に答える 4

5

さて、json コンテンツ タイプの問題は次のように解決できます。

ResponseEntity を使用すると、応答ヘッダーの content-type を変更できます。これにより、ajax は json オブジェクトを正しい方法で解釈でき、406 Http エラーが発生しなくなります。

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<String> getUsers(@RequestParam int jtStartIndex, @RequestParam int jtPageSize,
        @RequestParam String jtSorting, @RequestParam String jtSearchParam,
        HttpServletRequest request, HttpServletResponse response) throws JSONException{

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/json; charset=utf-8");

    Gson gson = new GsonBuilder()
            .setExclusionStrategies(new UserExclusionStrategy())
            .create();

    List<User> users = userService.findUsers(jtStartIndex ,jtPageSize, jtSorting, jtSearchParam);
    Type userListType = new TypeToken<List<User>>() {}.getType();

    String usersJsonString = gson.toJson(users, userListType);
    int totalRecordCount = userDao.getAmountOfRows(jtSearchParam);

    usersJsonString = "{\"Message\":null,\"Result\":\"OK\",\"Records\":" + usersJsonString + ",\"TotalRecordCount\":" + totalRecordCount + "}";

    return new ResponseEntity<String>(usersJsonString, responseHeaders, HttpStatus.OK);
}

エンコーディングの問題は、次のように解決できます。

IE は「ü、ä など」をエンコードしません。正しくは、「jtSearchParam=wü」のように URL に追加するだけですが、実際には「jtSearchParam=w%C3%BC」のようになります (そうでない場合は、 IE を使用する場合はサーバー側)

encodeURIそのため、特定の値を URLに追加する場合は、実際に URL に追加する前に、その値に対してJavaScript メソッドを必ず使用してください。 例:

encodeURI(jtSearchParam)

于 2013-05-02T06:40:38.137 に答える
3

プレーン テキストと json の間で使用しているコンテンツ タイプで競合を見つけることができます

dataType: 'json'

contentType: "text/html; charset=utf-8"

ヘッダーとコンテンツ タイプのすべての部分に json を使用することをお勧めします application/json。messageConverters でも、jackson jar を追加するだけで Java オブジェクトが json に変換されます。@ResponseBody Stringユーザー@ResponseBody Userがpojo Bean には、属性のゲッターとセッターが含まれています。

于 2013-04-29T07:16:31.943 に答える
2

パラメータのエンコーディングの問題

これが起こっている理由は 2 つあります。

  1. 何らかの理由で、ブラウザはページが UTF-8 でエンコードされていないと判断します
  2. あなたは含まれていませんCharacterEncodingFilter

CharacterEncodingFilter、Spring ユーザーが経験するエンコーディングの問題のほとんどを解決します。の最初のフィルタである必要がありweb.xmlます。

<filter>
    <filter-name>encodingfilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>forceEncoding</param-name>
        <param-value>true</param-value>
    </init-param>

</filter>

<filter-mapping>
    <filter-name>encodingfilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

GET 要求を使用し、Tomcat を使用する予定がある場合Connectorは、サーバー構成の要素にプロパティがあることを確認してくださいURIEncoding="utf-8"。他のサーバーでは、同様の設定が必要な場合と必要でない場合があります。

JSON リターンの問題

Jackson Mapperこれは、クラスパスと@ResponseBodyメソッドの戻り値の型にを追加するのと同じくらい簡単です。あなたの場合Message、JSON 応答に似たクラスを作成することをお勧めします。最も単純なケースでは、メソッドは次のようになります。

   public @ResponseBody Message getUsers(int jtStartIndex, jtPageSize, String jtSorting, String jtSearchParam) {

      List<User> users = userService.findUsers(jtStartIndex ,jtPageSize, jtSorting, jtSearchParam);
      int totalRecordCount = userDao.getAmountOfRows(jtSearchParam);

      Message message = new Message();
      message.setRecords(users);
      message.setTotalRecordCount(totalRecordCount);

      return message;
  }

@RequestParamメソッドのパラメーターがリクエストパラメーターと同じ名前の場合、通常は必要ないため、意図的に省略しました。

content-typejQuery を使用する場合、コンテンツを JSON として正常に解析できる限り、実際の応答が何であるかはほとんど問題になりません。dataType: 'json'ただし、jQuery が間違った推測をするのを防ぐために使用してください。

content-typeもちろん、 を使用する場合は重要ですproduces。リクエスト マッピングを絞り込む必要がない場合は、削除することをお勧めします。

于 2013-04-30T19:07:03.867 に答える