css

body {
  color: #252525;
  font-family: 'Verdana','MS PGothic','Courier','Lucida Grande','Times New Roman','Consolas','Meiryo','MS Gothic';
  font-size: 13pt;
  line-height: 150%;
  letter-spacing: 1px;
  background-color: #888fff;
  margin: 20px 50px 20px 50px;
}

AjaxとServletの連携

AjaxServlet を連携するやり方について紹介します。尚、サーブレットコンテナは Jetty を用いています。


ファイルの配置

まず、Jetty のzipファイルをダウンロードし、適当な場所(ここでは D:\sdk)で解凍します。 次に webappsフォルダの直下に好きな名前のフォルダ(ここでは webapp)を作成し、更にその下にWEB-INFフォルダを作成し、その中に web.xml を入れて下さい。

  D:\sdk\jetty\webapps\webapp\SampleAjax.htm
  D:\sdk\jetty\webapps\webapp\WEB-INF\web.xml
  D:\sdk\jetty\webapps\webapp\WEB-INF\classes\SampleServlet.class

注)web.xml、SampleAjax.htm は、UTF-8 で保存してください!


 

D:\sdk\jetty\webapps\webapp\WEB-INF\web.xml

<web-app>
  <servlet>
    <servlet-name>sampleservlet</servlet-name>
    <servlet-class>SampleServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>sampleservlet</servlet-name>
    <url-pattern>sampleservlet</url-pattern>
  </servlet-mapping>
</web-app>
 

注)SampleServlet1.class、SampleServlet2.class のように、サーブレットが複数ある場合は、<web-app>・・・</web-app>の中に複数記述してください。


1.Ajaxのみのサンプル(Servletなし)

 

D:\sdk\jetty\webapps\webapp\SampleAjax.htm

<html>
<body>

<form name="io">
  <input type="button" value="実行" onClick="get()">
  <textarea id="output" cols="50" rows="5"></textarea>
</form>

<script>
function get() {
  xhr = new XMLHttpRequest();
  xhr.onload = setResponseText;
  xhr.open("GET", "/webapp/hello.txt", true);
  xhr.send();
}
</script>

<script>
function setResponseText() {
  document.getElementById("output").innerHTML = xhr.responseText;
}
</script>

</body>
</html>
 

 

D:\sdk\jetty\webapps\webapp\hello.txt

Hello Ajax!
Hello Ajax!
Hello Ajax!
Hello Ajax!
Hello Ajax!
 

2.AjaxServletを使ったサンプル(XMLHttpRequest版)

 

D:\sdk\jetty\webapps\webapp\SampleAjax.htm

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>

<form name="io">
  <input type="button" name="request" value="実行">
  <input type="text" name="input1">
  <input type="text" name="input2">
  <input type="text" name="input3">
  <output name="output"></output>
</form>

<script>
document.io.request.addEventListener("click", function () {
  var url = "/webapp/sampleservlet";
  var value1 = document.io.input1.value;
  var value2 = document.io.input2.value;
  var value3 = document.io.input3.value;
  var request = "input1" + "=" + value1 + "&" + "input2" + "=" + value2 + "&" + "input3" + "=" + value3;
  var show = function (response) {document.io.output.innerHTML = response["key1"] + "," + response["key2"] + "," + response["key3"];};
  post(url, request, show);
});
</script>

<script>
function post(url, request, callback) {
  var xhr = new XMLHttpRequest();
  xhr.addEventListener("load", function (event) {
    if (event.target.status == 200) {
      callback(JSON.parse(xhr.responseText));
    }
    delete xhr;
  });
  xhr.open("post", url, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhr.send(request);
}
</script>

</body>
</html>
 

3.AjaxServletを使ったサンプル(jQuery版)

 

D:\sdk\jetty\webapps\webapp\SampleAjax.htm

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>

<form>
  <input type="button" id="request" value="実行">
  <input type="text" id="input1">
  <input type="text" id="input2">
  <input type="text" id="input3">
  <output id="output"></output>
</form>

<script>
$("#request").on("click", function () {
  var url = "/webapp/sampleservlet";
  var request = {};
  request["input1"] = $("#input1").val();
  request["input2"] = $("#input2").val();
  request["input3"] = $("#input3").val();
  var show = function (response) {$("#output").text(response["key1"] + "," + response["key2"] + "," + response["key3"]);};
  $.post(url, request, show);
});
</script>

</body>
</html>
 

4.Servletのサンプル(共通)

上記のXMLHttpRequest版及びjQuery版に共通のServletサンプルです。
尚、SampleServlet.java において、サーブレットからクライアントに送信するデータ形式(setContentType)を application/json にしています。

 

D:\sdk\jetty\webapps\webapp\WEB-INF\src\SampleServlet.java

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

public class SampleServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    response.setContentType("application/json");
    String parameter1 = request.getParameter("input1");
    String parameter2 = request.getParameter("input2");
    String parameter3 = request.getParameter("input3");
    PrintWriter out = response.getWriter();
    out.println("{" + "\"key1\"" + ":" + "\"" + parameter1 + "\"" + "," + "\"key2\"" + ":" + "\"" + parameter2 + "\"" + "," + "\"key3\"" + ":" + "\"" + parameter3 + "\"" + "}");
    out.close();
  }
}
 

 

Servletコンパイル方法

下記のバッチファイルをダブルクリックして SampleServlet.javaコンパイルします。

javac0.bat(ファイル名をjavac.batにすると暴走します)

set JAVA_HOME=D:\sdk\jdk
set path=%JAVA_HOME%\bin
javac -cp D:\sdk\jetty\lib\servlet-api-3.1.jar *.java
pause
 


コンパイルしたファイル(Servlet.class)を下記のフォルダに入れてください。

D:\sdk\jetty\webapps\webapp\WEB-INF\classes

 


Webサーバの起動方法

下記のバッチファイルをダブルクリックすると Jetty が起動します。

jetty.bat

set JAVA_HOME=D:\sdk\jdk
set path=%JAVA_HOME%\bin
cd /d D:\sdk\jetty
java -jar start.jar


Webサーバへのアクセス方法

WebブラウザのURLに以下のように入力すれば、Webサーバにアクセスすることができます。


http://localhost:8080/webapp/SampleAjax.htm


参考サイト

 

css

body {
  color: #252525;
  font-family: 'Verdana','MS PGothic','Courier','Lucida Grande','Times New Roman','Consolas','Meiryo','MS Gothic';
  font-size: 13pt;
  line-height: 150%;
  letter-spacing: 1px;
  background-color: #888fff;
  margin: 20px 50px 20px 50px;
}

css

body {
  color: #252525;
  font-family: 'Verdana','MS PGothic','Courier','Lucida Grande','Times New Roman','Consolas','Meiryo','MS Gothic';
  font-size: 13pt;
  line-height: 150%;
  letter-spacing: 1px;
  background-color: #888fff;
  margin: 20px 50px 20px 50px;
}

夏は花火だ!

最近、花火を見ていないので、久しぶりに見たいな!

JavaScriptによるHTMLの操作

JavaScriptからHTMLを操作するしくみをDOMと呼びます。

 

 

index.htm

<html>
<head>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<script type="text/javascript" charset="UTF-8" src="./js/module.js"></script>
</body>
</html>
 

 

hello.htm

<html>
<body>
<script>
console.log("Hello!");
window.alert("Hello!");
document.write("Hello!" + "<br>");
document.body.innerHTML += "Hello!" + "<br>";
</script>
</body>
</html>
 

 

getElementById.htm

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>
<form>
<input type="text" id="text0">
<input type="button" id="button0">
</form>
<script>
$("#text0").val("text");
//document.getElementById("text0").value = "text";
document.write($("#text0").val() + "<br>");
document.write(document.getElementById("text0").type + "<br>");
$("#button0").val("button");
//document.getElementById("button0").value = "button";
document.write($("#button0").val() + "<br>");
document.write(document.getElementById("button0").type + "<br>");
</script>
</body>
</html>
 

 

object.htm

<html>
<body>
<script>
var object = {};
//var object = new Object();
//object.key0 = "value0";
//object.key1 = "value1";
//object.key2 = "value2";
object["key" + 0] = "value0";
object["key" + 1] = "value1";
object["key" + 2] = "value2";
document.write(JSON.stringify(object) + "<br>");
document.write(JSON.stringify({key0:"value0", key1:"value1", key2:"value2"}) + "<br>");
for (var key in object) {
  document.write(key + ":" + object[key] + "<br>");
}
</script>
</body>
</html>
 

 

array.htm

<html>
<body>
<script>
var array = [];
//var array = new Array();
array.push("a0");
array.push("a1");
array.push("a2");
array.pop();
document.write(JSON.stringify(array) + "<br>");
for (var index in array) {
  document.write(index + ":" + array[index] + "<br>");
}
</script>
</body>
</html>
 

 

function_with_indices.htm (インデクス付関数)

<html>
<body>
<script>
var dispatch = {};
dispatch["abcde"] = function () {document.write("<p>abcde</p>");};
dispatch["fghij"] = function () {document.write("<p>fghij</p>");};
dispatch["klmno"] = function () {document.write("<p>klmno</p>");};
</script>
<script>
dispatch["abcde"]();
dispatch["fghij"]();
dispatch["klmno"]();
</script>
</body>
</html>
 

 

robot1.htm

<html>
<body>
<script>
function Robot(x, y) {
  this.x = x; // -> public
  this.y = y; // -> public
  this.move = function (dx, dy) {
    this.x += dx;
    this.y += dy;
  }
  this.show = function () {
    document.write("x = " + this.x + "<br>");
    document.write("y = " + this.y + "<br>");
  }
}
</script>
<script>
var robot = new Robot(0, 0);
robot.move(1, 1);
robot.show();
document.write("x = " + robot.x + "<br>");
document.write("y = " + robot.y + "<br>");
</script>
</body>
</html>
 

 

robot2.htm

<html>
<body>
<script>
function Robot(x, y) {
  var x = x; // -> private
  var y = y; // -> private
  this.move = function (dx, dy) {
    x += dx;
    y += dy;
  }
  this.show = function () {
    document.write("x = " + x + "<br>");
    document.write("y = " + y + "<br>");
  }
}
</script>
<script>
var robot = new Robot(0, 0);
robot.move(1, 1);
robot.show();
document.write("x = " + robot.x + "<br>"); // -> x = undefined
document.write("y = " + robot.y + "<br>"); // -> y = undefined
</script>
</body>
</html>
 

 

robot3.htm

<html>
<body>
<script>
function Robot(x, y) {
  this.x = x; // -> public
  this.y = y; // -> public
}
Robot.prototype.move = function (dx, dy) {
  this.x += dx;
  this.y += dy;
};
Robot.prototype.show = function () {
  document.write("x = " + this.x + "<br>");
  document.write("y = " + this.y + "<br>");
};
</script>
<script>
var robot = new Robot(0, 0);
robot.move(1, 1);
robot.show();
document.write("x = " + robot.x + "<br>");
document.write("y = " + robot.y + "<br>");
robot.print = function () {
  document.write("x = " + this.x + "<br>");
  document.write("y = " + this.y + "<br>");
};
robot.print();
</script>
</body>
</html>
 

 

table.htm

<html>
<body>

<div id="output"></div>

<script>
  var m = 3;
  var n = 5;
  var table = "<table id='table' border='1'>";
  table += "<tr>";
  for (var j = 0; j < n; j++) {
    table += "<th width='100' height='25'>" + "item" + j + "</th>";
  }
  table += "</tr>";
  for (var i = 1; i <= m; i++) {
    table += "<tr>";
    for (var j = 0; j < n; j++) {
      table += "<td id=" + "'" + "cell" + "_" + i + "_" + j + "'" + "contenteditable='true'>" + "cell" + "_" + i + "_" + j + "</td>";
    }
    table += "</tr>";
  }
  table += "</table>";
</script>

<script>
  //document.write(table);
  document.getElementById("output").innerHTML = table;
  var table = document.getElementById("table");
  for (var i = 0; i <= m; i++) {
    for (var j = 0; j < n; j++) {
      document.write(table.rows[i].cells[j].innerHTML + "<br>");
    }
  }
  for (var i = 1; i <= m; i++) {
    for (var j = 0; j < n; j++) {
      document.write(document.getElementById("cell" + "_" + i + "_" + j).innerHTML + "<br>");
    }
  }
  document.getElementById("cell_1_1").innerHTML = "Hello!";
</script>

</body>
</html>
 

 

input.htm

<html>
<body>
<script>
var array = [];
for (var i = 0; i < 10; i++) {
  array.push(document.createElement("input"));
  array[i].type = "button";
  array[i].value = "button" + i;
  document.body.appendChild(array[i]);
  document.write("<br/>");
}
</script>
</body>
</html>
 

 

submit1.htm

<html>
<body>
<form action="http://www.google.com/search" target="_blank">
<input type="hidden" name="hl" value="ja">
<input type="text" name="hq" value="inurl" size="50">
<input type="text" name="q" value="keyword" size="50">
<input type="submit" value="search">
</form>
</body>
</html>
 

 

submit2.htm

<html>
<head>
<script>
function request() {
  document.requestform.name1.value = document.getElementById("id1").value;
  document.requestform.name2.value = document.getElementById("id2").value;
  document.requestform.submit();
}
</script>
</head>
<body>
<form>
<input type="text" id="id1" value="value1" size="50" style="font-size:15pt">
<input type="text" id="id2" value="value2" size="50" style="font-size:15pt">
</form>
<form name="requestform" action="http://www.xxxxx.jp/request" target="_blank">
<input type="hidden" name="name1" value="">
<input type="hidden" name="name2" value="">
<input type="button" value="request" onclick="request()" style="width:100px; height:35px; font-size:15pt">
</form>
</body>
</html>
 

 

event1.htm

<html>
<head>
</head>
<body>

<form name="io">
<input type="text" name="input1">
<input type="text" name="input2">
<input type="button" name="button" value="実行" onclick="execute(0)">
<output name="output"></output>
</form>

<script>
function execute(x) {
  document.io.output.innerHTML = Number(x) + Number(document.io.input1.value) + Number(document.io.input2.value);
}
</script>

</body>
</html>
 

 

event2.htm

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<body>

<form>
<input type="text" id="input1">
<input type="text" id="input2">
<input type="button" id="button" value="実行">
<output id="output"></output>
</form>

<script>
$("#button").on("click", function () {execute(0);});
//document.getElementById("button").addEventListener("click", function () {execute(0);}, false);
</script>

<script>
function execute(x) {
  document.getElementById("output").innerHTML = Number(x) + Number(document.getElementById("input1").value) + Number(document.getElementById("input2").value);
}
</script>

</body>
</html>
 

 

keyevent.htm

<html>
<body>

<input type="text" id="input1">
<input type="text" id="input2">
<output id="output"></output>

<script>
document.getElementById("input1").onkeydown = function (event) {
  document.getElementById("output").innerHTML = String.fromCharCode(event.keyCode);
}
</script>

<script>
document.getElementById("input2").onkeyup = function () {
  document.getElementById("output").innerHTML = document.getElementById("input2").value;
}
</script>

</body>
</html>
 

 


 

array.htm

<html>
<body>

<script>
var array = [];
array = ["a0", "a1", "a2", "a3", "a4"];
array = array.concat(["a5", "a6", "a7", "a8", "a9"]);
document.body.innerHTML += array + "<br>";
array.push("a10", "a11", "a12");
document.body.innerHTML += array + "<br>";
array.splice(5, 3, "a15", "a16", "a17");
document.body.innerHTML += array + "<br>";
array.splice(10, 3);
document.body.innerHTML += array + "<br>";
array = array.slice(5, 8);
document.body.innerHTML += array + "<br>";
</script>

<script>
array = ["a0", "a1", "a2", "a3", "a4"];
var string = array.join(",");
document.body.innerHTML += string + "<br>";
array = string.split(",");
document.body.innerHTML += array + "<br>";
string = "abcdefghij";
document.body.innerHTML += string.slice(2) + "<br>";
document.body.innerHTML += string.slice(2, 5) + "<br>";
document.body.innerHTML += string.substr(2, 3) + "<br>";
document.body.innerHTML += string.substring(2, 5) + "<br>";
</script>

</body>
</html>
 

 

indexOf.htm

<html>
<body>
<script>
var array = ["abcde", "fghij", "klmno"];
document.write(array.indexOf("abcde") + "<br>"); // -> 0
document.write(array.indexOf("fghij") + "<br>"); // -> 1
document.write(array.indexOf("klmno") + "<br>"); // -> 2
</script>
</body>
</html>
 

 

redirect.htm

<script>
$("#login").on("click", function () {
  var url = "/webapp/loginservlet";
  var request = {};
  request["user"] = $("#user").val();
  request["password"] = $("#password").val();
  $.post(url, request, redirect);
});
</script>

<script>
function redirect(response) {
  if (response["status"] === "success") {
    location.href = response["url"];
    //location.assign(response["url"]);
    //location.replace(response["url"]);
  }
  else {
    $("#message").text(response["error"]);
  }
}
</script>
 

 

selector.htm

<form>
<input type="button" id="ibutton" value="実行">
<input type="button" class="cbutton" value="実行">
</form>

<script>
$("#ibutton").on("click", function () {.....});
$(".cbutton").on("click", function () {.....});
</script>
 

 

immediate_function.htm

(function () {
  .....
} ());
 

 


参考サイト