一个简单的web容器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个简单的web容器相关的知识,希望对你有一定的参考价值。
1.一个简单的web容器其实就是一个简单的socket类的服务端,然后通过浏览器访问,将请求的内容输出到页面。
2.示例:HttpServer.java
package com.diytomcat.http;
import java.net.Socket;
import java.net.UnknownHostException;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
public class HttpServer {
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "WebContent";
private final int port = 8080;
public void accept() throws UnknownHostException, IOException{
ServerSocket serverSocket = new ServerSocket(port, 2, InetAddress.getByName("127.0.0.1"));
while(true){
Socket socket = serverSocket.accept();
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
PrintWriter writer = new PrintWriter(out);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
byte[] bytes = new byte[1024];
FileInputStream fis = null;
try {
File file = new File(HttpServer.WEB_ROOT, "/test.jsp");
if (file.exists()) {
fis = new FileInputStream(file);
int ch = fis.read(bytes, 0, 1024);
while (ch!=-1) {
out.write(bytes, 0, ch);
ch = fis.read(bytes, 0, 1024);
}
}
else {
// file not found
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
out.write(errorMessage.getBytes());
}
}
catch (Exception e) {
// thrown if cannot instantiate a File object
System.out.println(e.toString() );
}
finally {
if (fis!=null)
fis.close();
}
socket.close();
}
}
public void sendStaticResource() throws IOException {
}
public static void main(String[] args){
HttpServer server = new HttpServer();
try {
server.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
}
以上是关于一个简单的web容器的主要内容,如果未能解决你的问题,请参考以下文章
使用docker容器定制镜像(image)并部署简单 web应用