「JSONによるServletとJSPの通信」

 Ajax絡みの処理を書くことになりそうなので、それと合わせてサーバとの通信にJSONを使おうとちょっと調べて見た。
 サーバ側はJavaで、クライアント側はJSP。ただ、サーバ側はJSON形式の文字列が返せれば良いのだから、実装言語は実際には問わないが。
 あとサーバ側での実装の検証でJson-libもちょっと試したけど、それはちょっと省略。サーバとの非同期通信には、prototype.jsを使用。
 以下のサンプルでやっていることは、

  • クライアント側でボタンを押すと、サーバと非同期通信。
  • サーバ側は、リクエストを受けたらJSON形式で文字列を返す。
  • クライアント側は、返ってきたJSON形式の文字列を解析して、それを表示する。

 上記は本当に単純なことしかやっていないけど。

JSPソース

<%@ page language="java" contentType="text/html; charset=windows-31j"
	pageEncoding="windows-31j"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-31j">
<script language="javascript" src="/JsonSample/prototype.js"></script>
<script>
<!--
function test() {
  var myAjax = new Ajax.Request(
    '/JsonSample/JsonServlet', 
    {
      method: 'get', 
      parameters: "", 
      onComplete: callback
     });
}
    
function callback(originalRequest) {
  try{
    var res = eval('(' + originalRequest.responseText + ');');
    $("place1").innerHTML = res['html'];
  }catch(e){
    alert(e.description);
  }
}
//-->

</script>
<title>Insert title here</title>
</head>
<body>
<input type="button" name="submit" onclick="test();" value="submit">
<table>
  <tr>
    <td>
      <div id="place1">ここに挿入する</div>
    </td>
  </tr>
</table>
</body>
</html>

Javaソース

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JsonServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    public JsonServlet() {
        super();
    }   	
	
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("{'html': '<h1>JsonSample</h1>'}");
        response.getWriter().flush();
    }  	
	
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().write("{'html': '<h1>JsonSample</h1>'}");
        response.getWriter().flush();
    }   	  	    
}