Spring WebUtilsとServletRequestUtilsのガイド

1概要

この簡単な記事では、Spring MVCに組み込まれているWebリクエストutil WebUtils ServletRequestUtils について説明します。

** 2 WebUtils ServletRequestUtils

**

ほとんどすべてのアプリケーションで、着信HTTPリクエストからいくつかのパラメータを取得する必要がある状況に直面しています。

そのためには、次のような本当に忙しいコードセグメントをいくつか作成する必要がありました。

HttpSession session = request.getSession(false);
if (session != null) {
    String foo = session.getAttribute("parameter");
}

String name = request.getParameter("parameter");
if (name == null) {
    name = "DEFAULT";
}

WebUtils ServletRequestUtils を使用すると、1行のコードでそれを実行できます。

これらのユーティリティがどのように機能するかを見るために、簡単なWebアプリケーションを作成しましょう。

** 3サンプルページ

**

URLをリンクできるようにするには、サンプルページを作成する必要があります。 Spring Boot およびhttps://search.maven.org/classic/#searchを使用します。テンプレートエンジンとして%7Cga%7C1%7Ca%3A%22thyleleaf%22[ Thymeleaf ]。それらに必要な依存関係を追加する必要があります。

簡単なフォームでページを作りましょう:

<form action="setParam" method="POST">
    <h3>Set Parameter:  </h3>
    <p th:text="${parameter}" class="param"/>
    <input type="text" name="param" id="param"/>
    <input type="submit" value="SET"/>
</form>
<br/>
<a href="other">Another Page</a>

ご覧のとおり、 POST リクエストを開始するためのフォームを作成しています。

ユーザーを次のページに転送するリンクも1つあります。このページでは、session属性から送信されたパラメーターを表示します。

そして2ページ目を作りましょう。

Parameter set by you: <p th:text="${parameter}" class="param"/>

** 4使い方+

**

ビューの構築が完了したので、コントローラを作成し、 ServletRequestUtils を使用してrequestパラメータを取得しましょう。

@PostMapping("/setParam")
public String post(HttpServletRequest request, Model model) {
    String param
      = ServletRequestUtils.getStringParameter(
        request, "param", "DEFAULT");

    WebUtils.setSessionAttribute(request, "parameter", param);

    model.addAttribute("parameter", "You set: " + (String) WebUtils
      .getSessionAttribute(request, "parameter"));

    return "utils";
}

ServletRequestUtils getStringParameter APIを使用してリクエストパラメータ名 param を取得していることに注意してください。コントローラに値が入力されていない場合は、デフォルト値がリクエストパラメータに割り当てられます。

そしてもちろん、session属性に値を設定するために使用されていた WebUtils のうち setSessionAttribute APIに注目してください。セッションがすでに存在しているかどうかを明示的にチェックする必要も、バニラサーブレットにリンクする必要もありません。 Springはそれをその場で設定します。

同様に、次のセッション属性を表示するもう一方のハンドラを作成しましょう。

@GetMapping("/other")
public String other(HttpServletRequest request, Model model) {

    String param = (String) WebUtils.getSessionAttribute(
      request, "parameter");

    model.addAttribute("parameter", param);

    return "other";
}

アプリケーションを作成するために必要なのはこれだけです。

ここで注意すべき1つの簡単な点は、 ServletRequestUtils には、必要に応じてリクエストパラメータを自動的に型キャストする、いくつかの素晴らしい組み込み機能があることです。

これが、requestパラメータを Long に変換する方法です。

Long param = ServletRequestUtils.getLongParameter(request, "param", 1L);

同様に、リクエストパラメータを他の型に変換することができます。

boolean param = ServletRequestUtils.getBooleanParameter(
  request, "param", true);

double param = ServletRequestUtils.getDoubleParameter(
  request, "param", 1000);

float param = ServletRequestUtils.getFloatParameter(
  request, "param", (float) 1.00);

int param = ServletRequestUtils.getIntParameter(
  request, "param", 100);

もう1つ注意すべき点は、 ServletRequestUtils には、リクエストパラメータを取得するための別のメソッド getRequiredStringParameter(ServletRequest request、String name) があります。違いは、パラメータが着信要求に見つからない場合、 ServletRequestBindingException がスローされることです。これは、重要なデータを扱う必要があるときに便利です。

以下はサンプルコードの抜粋です。

try {
    ServletRequestUtils.getRequiredStringParameter(request, "param");
} catch (ServletRequestBindingException e) {
    e.printStackTrace();
}

アプリケーションをテストするための簡単なJUnitテストケースを1つ作成することもできます。

@Test
public void givenParameter__setRequestParam__andSetSessionAttribute()
  throws Exception {
      String param = "testparam";

      this.mockMvc.perform(
        post("/setParam")
          .param("param", param)
          .sessionAttr("parameter", param))
          .andExpect(status().isOk());
  }

5結論

この記事では、 WebUtils ServletRequestUtils を使用すると、定型コーディングのオーバーヘッドを大幅に削減できることがわかりました。しかし、その一方で、それは確かにSpringフレームワークへの依存を強めます - それが懸念であるならば、それは留意するべき何かです。

いつものように、ソースコードはhttps://github.com/eugenp/tutorials/tree/master/spring-boot[over on GitHub]から入手できます。