(※参考: http://libro.tuyano.com/index3?id=50003 )さて、サーブレット側の処理ですが、これは実は先程のサンプルとほとんど違いはありません。唯一違うのは、
※リストが表示されない場合
AddBlockなどの広告ブロックツールがONになっているとリストなどが表示されない場合があります。これらのツールをOFFにしてみてください。
※index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<title>Hello App Engine</title>
	<style>
	h1 {
		font-size: 16pt;
		background: #AAFFAA;
		padding: 5px;
	}
	</style>
	<script type="text/javascript">
	function doAction(){
		var req =  createRequest();
		if (req == null){
			alert("実行できません!");
			return;
		}
		var s = document.getElementById('text1').value;
		req.open("post", "/mygaeapp", true);
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.onreadystatechange = function(){
			if (this.readyState == 4 && this.status == 200){
				var msg = document.getElementById('msg');
				msg.innerHTML = this.responseText;
			}
		}
		req.send("text1=" + encodeURIComponent(s));
		msg.innerHTML = "<<< please wait... >>>";
	}
	 	
	   function createRequest(){
		var httplist = [
			function(){ return new XMLHttpRequest(); },
			function(){ return new ActiveXObjct("Msxml2.XMLHTTP"); },
			function(){ return new ActiveXObject("Microsoft.XMLHTTP"); }
		];
		for(var i = 0;i < httplist.length;i++){
			try {
				var http = httplist[i]();
				if (http != null) return http;
			} catch(e){
				continue;
			}
		}
		return null;
	}
	</script>
</head>
<body>
	<h1>Hello App Engine!</h1>
	<p id="msg">※整数を入力:</p>
	<p name="msg"></p>
	<table>
		<tr>
			<td>入力</td>
			<td><input type="text" id="text1"></td>
		</tr>
		<tr>
			<td></td>
			<td>
				<button onclick="doAction();">送信する</button>
			</td>
		</tr>
	</table>
</body>
</html>
※MyGaeAppServlet.java
package com.tuyano.libro.mygaeapp;
import java.io.*;
import java.net.*;
import javax.servlet.http.*;
@SuppressWarnings("serial")
public class MyGaeAppServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, 
			HttpServletResponse response)
			throws IOException {
		response.setContentType("text/plain");
		request.setCharacterEncoding("utf8");
		response.setCharacterEncoding("utf8");
		PrintWriter out = response.getWriter();
		out.println("Hello, world!");
	}
	public void doPost(HttpServletRequest request, 
			HttpServletResponse response)
			throws IOException {
		response.setContentType("text/plain");
		request.setCharacterEncoding("utf8");
		response.setCharacterEncoding("utf8");
		String param = URLDecoder.decode(request.getParameter("text1"),"utf8");
		int result = 0;
		try {
			int n = Integer.parseInt(param);
			for(int i = 1;i <= n;i++){
				result += i;
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		PrintWriter out = response.getWriter();
		out.println(result);
	}
}
| << 前へ | 次へ >> |