index.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Hello</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(function() {
$("button").click(function() {
$.get("/hello", function(data) {
$("div").text(data);
});
});
});
</script>
</head>
<body>
<button>Submit</button>
<div></div>
</body>
</html>
Hello.java
package com.test;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class Hello extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
web.xml
<web-app version="2.5" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>com.test.Hello</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>jQueryを利用しないでJavaScriptのみで書こうとした場合、以下のようになります。 buttonタグのonclick属性とメソッド名を紐づけないといけない、XMLHttpRequestを理解して書かないといけない、IEの対応などブラウザごとの対応も必要になってくるなど大変ですね。
<html>
<head>
<title>Hello</title>
<script type="text/javascript">
function submit(){
if(window.XMLHttpRequest){
req = new XMLHttpRequest();
}else if(window.ActiveXObject){
req = new ActiveXObject("Microsoft.XMLHTTP");
}else{
return false;
}
req.onreadystatechange=callback;
req.open("GET","/hello",true);
req.send(null);
}
function callback(){
if(req.readyState==4 && req.status==200){
document.getElementById("result").innerHTML=req.responseText;
}
}
</script>
</head>
<body>
<button onclick="submit()">Submit</button>
<div id="result">
</div>
</body>
</html>
2 件のコメント:
大変参考になりました。
ありがとうございました。
コメントありがとうございます。
随分前に書いたものですが役立ったようで良かったです。
とりあえず動くだけなので勉強用のものとしていただければと思います。
コメントを投稿