0%

servlet程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package com.swifter;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

public class Main {
public static void main(String[] args) throws Exception {
Server server = new Server();
server.start();
}
}

class Server {

List <Servlet> servlets = new ArrayList();

void start() throws Exception {
File file = new File(new String(this.getClass().getResource("./").getPath()));
System.out.println(file.getPath());
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
String fileName = f.getName();
fileName = fileName.substring(0,fileName.lastIndexOf("."));
if (!fileName.equals("Servlet")) {

System.out.println(this.getClass().getPackage().getName() + "."+fileName);
Class<Servlet> aClass = (Class<Servlet>) Class.forName(this.getClass().getPackage().getName() + "."+fileName);
if (Servlet.class.isAssignableFrom(aClass)) {
servlets.add(aClass.newInstance());
}
}
}
} else {
System.out.println("list is null");
}

HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);

for (Servlet servlet : servlets) {
System.out.println(servlet.path());
httpServer.createContext(servlet.path(), new HttpHandler() {
@Override
public void handle(HttpExchange httpExchange) throws IOException {
servlet.service(httpExchange);
}
});
}
httpServer.start();
}

}

class Hello1Servlet implements Servlet {

@Override
public String path() {
return "/hello1";
}

@Override
public void service(HttpExchange exchange) throws IOException {
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.write("hello world1111".getBytes());
responseBody.close();
}
}

class Hello2Servlet implements Servlet {

@Override
public String path() {
return "/hello2";
}

@Override
public void service(HttpExchange exchange) throws IOException {
exchange.sendResponseHeaders(200, 0);
OutputStream responseBody = exchange.getResponseBody();
responseBody.write("hello world2222".getBytes());
responseBody.close();
}
}

interface Servlet {
public String path();
public void service(HttpExchange exchange) throws IOException;
}

–EOF–