0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Vol.1 『[改訂新版]プロになるためのWeb技術入門』のGoによるアプリをJavaに置き換える

Last updated at Posted at 2025-10-04

この記事では、小森祐介さんの『[改訂新版]プロになるためのWeb技術入門』(技術評論社)の第6章「従来型のWebアプリケーション」に登場するアプリを題材にし、Javaで書き換えながらWeb周りの技術を理解していくことを目的としております。

この記事に記載してあるコードは、同書p155に掲載してあるGo言語によるソースコード(「Goで文字列を返すプログラム」)がもとになっています。

オリジナルのライセンス文は以下になります。

MIT License
Copyright (c) 2024 KOMORI Yusuke
ライセンス条文 (https://github.com/little-forest/webtech-fundamentals/tree/v1-latest?tab=MIT-1-ov-file)

Springでやってしまってもいいのですが、HTTPの仕組みを学ぶのが目的なので標準ライブラリのHttpServerを使用いたします。

     1	package webtech_fundamentals;
     2	
     3	import java.io.IOException;
     4	import java.io.OutputStream;
     5	import java.lang.System.Logger;
     6	import java.lang.System.Logger.Level;
     7	import java.net.InetSocketAddress;
     8	
     9	import com.sun.net.httpserver.HttpExchange;
    10	import com.sun.net.httpserver.HttpHandler;
    11	import com.sun.net.httpserver.HttpServer;
    12	
    13	public class Main {
    14		private static final Logger logger =System.getLogger(Main.class.getName());
    15	
    16		public static void main(String[] args) {
    17			
    18			int port = 8080;
    19	
    20			try {
    21				HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
    22				server.createContext("/", new HelloHandler());
    23				server.start();
    24				logger.log(Level.INFO,"Server started on port:" + port);
    25			} catch (IOException e) {
    26				logger.log(Level.ERROR,"failed to start:" + e.getMessage());
    27			}
    28		}
    29	
    30		static class HelloHandler implements HttpHandler {
    31	
    32			@Override
    33			public void handle(HttpExchange exchange) throws IOException {
    34				String response = "Hello,Web Application!";
    35	
    36				exchange.sendResponseHeaders(200, response.getBytes().length);
    37	
    38				OutputStream os = exchange.getResponseBody();
    39				os.write(response.getBytes());
    40				os.close();
    41			}
    42	
    43		}
    44	}

実行結果

image.png

元のソースコードに忠実に沿っているので、レスポンスヘッダの設定などは行なっておりません。

36行目 exchange.sendResponseHeaders(200, response.getBytes().length)の第二引数について

0より大きい場合は、応答本体の固定長を指定し、その正確なバイト数をgetResponseBody()から取得されたストリームに書き込む必要がある。(1

目的としては、「データサイズの情報は、正しくレスポンスデータが送信されたか確認するために使用されます。(2」とのことです。

出典

1 )

2 )

参考にしたサイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?