webサーバーを作る |
---|
import java.net.*; import java.io.*; import com.dalsemi.tininet.http.*; public class tiniweb { boolean webServerEnabled = true; Object lock= new Object(); HTTPServer httpServer; boolean loggingFailed = false; public int httpPort = HTTPServer.DEFAULT_HTTP_PORT; public String webLog = "/web.log"; public String webRoot = "/www"; public String webIndex = "index.html"; boolean debugOn=true; public static void main(String[] args) { new tiniweb().start(); } public void start(){ try { // httpPort上にHTTPサーバーのインスタンスを作る httpServer = new HTTPServer(httpPort); // デフォールトのindexページをオーバーライドする httpServer.setIndexPage(webIndex); // デフォールトのHTTPルートをオーバーライドする httpServer.setHTTPRoot(webRoot); // デフォールトのログファイル名をオーバーライドする httpServer.setLogFilename(webLog); } catch(HTTPServerException h) { System.out.println(h.toString()); } try { // ログを開始 // 注意: ログファイルはいつも最後に追加されます // 従って管理していないとメモリーを消費します。 httpServer.setLogging(true); } catch(HTTPServerException h) { // ログファイルに問題が起こった loggingFailed = true; if(debugOn) { System.out.println(h.toString()); } } while(webServerEnabled) { httpServer.serviceRequests(lock); //... } } } |
メソッド | 説明 |
---|---|
GET | URLで指定したリソースを取得します |
POST | 指定したURLにデータを転送します |
POSTメソッドに対応する |
---|
import java.io.*; import java.util.*; import com.dalsemi.tininet.http.*; /* コマンド入力に"command"を入れ、値入力に任意の値を入れると その値を付け加えて表示する。 */ public class tiniServer implements PostScript { String indextop = "<html><head><title>TiniWebServer</title></head>"+ "<body><h1>TiniWebServer</h1><br>"+ "<FORM METHOD=\"POST\" ENCTYPE=\"application/x-www-form-urlencoded\" ACTION=\"tiniServer\">\r\n"+ "コマンド: <INPUT TYPE=\"text\" NAME=\"command\"><br>\r\n"+ " 値: <INPUT TYPE=\"text\" NAME=\"value\"><br>\r\n"+ " 0<INPUT TYPE=\"submit\" VALUE=\"実行\"><br>\r\n"+ "</FORM>"; String indexbottom = "</body></html>"; public void handlePost( Vector data, OutputStream out, HTTPWorker work ) { StringBuffer strBuff = new StringBuffer (); PostElement pe; strBuff.append(indextop); try { pe = (PostElement)data.elementAt(0); String command = pe.value; if(command.equals("command")) { pe = (PostElement)data.elementAt(1); strBuff.append(pe.value); } out.write( work.encodeBody( HTTPServer.HTTP_OK, "OK", HTTPServer.MIME_TEXT_HTML, strBuff.length() ) ); strBuff.append(indexbottom); out.write( strBuff.toString().getBytes() ); out.flush(); } catch(Exception e){ System.out.println(e); } } } |
index.html |
---|
<html> <head> <title>TiniWebServer</title> </head> <body> <h1>TiniWebServer</h1> <br> <FORM METHOD="POST" ENCTYPE="application/x-www-form-urlencoded" ACTION="tiniServer"><br> コマンド: <INPUT TYPE="text" NAME="command"><br> 値: <INPUT TYPE="text" NAME="value"><br> <INPUT TYPE="submit" VALUE="実行"><br> </FORM> </body> </html> |
コマンド、値、実行が文字化けします。これを直しなさい。