1. A simple web container is actually a server for a simple socket class, which is then accessed by the browser to output the requested content to the page.
2. Example: 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" +
"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 ();
}
}
}
A simple web container