コンピュータクワガタ

かっぱのかっぱによるコンピュータ関連のサイトです

Spring MVC 4.0 No. 008 Reader/InputStreamで受け取る

RequestBodyのデータをReaderやInputStreamで受け取ることができます。今回はより簡単なReaderで受け取っています。読み取った1行目のデータをレスポンスに返しています。

@RequestMapping("/readerForm")
public String readerForm() {
    return "req/readerForm";
}

@RequestMapping(value = "/readerRecv", method = RequestMethod.POST)
public String readerRecv(BufferedReader reader, Model model)
        throws IOException {
    model.addAttribute("body", reader.readLine());
    return "req/readerRecv";
}

POSTデータ送信用のJSP、readerForm.jspです。

<%@page contentType="text/html; charset=utf-8" %><%--
--%><!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>サンプル</title>
 </head>
 <body>
  <form action="readerRecv" method="post">
   名前: <input type="text" name="name" size="20"><br>
   年齢: <input type="text" name="age" size="20"><br>
   <input type="submit" value="送信">
  </form>
 </body>
</html>

リクエストボディ表示用のreaderRecv.jspです。

<%@page contentType="text/html; charset=utf-8" %><%--
--%><!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>サンプル</title>
 </head>
 <body>
nameの値は <c:out value="${name}" /><br>
ageの値は <c:out value="${age}" /><br>
bodyの値は <c:out value="${body}" /><br>
 </body>
</html>

ソースは https://github.com/kuwalab/spring-mvc40 にあります。タグ008が今回のサンプルです。

まとめ http://kuwalab.hatenablog.jp/entry/spring
最初 http://kuwalab.hatenablog.jp/entry/spring_mvc/001
前回 http://kuwalab.hatenablog.jp/entry/spring_mvc/007
次回 http://kuwalab.hatenablog.jp/entry/spring_mvc/009