-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServletManager.java
More file actions
52 lines (42 loc) · 1.66 KB
/
Copy pathServletManager.java
File metadata and controls
52 lines (42 loc) · 1.66 KB
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
package was.httpserver;
import was.httpserver.servlet.InternalErrorServlet;
import was.httpserver.servlet.NotFoundServlet;
import was.httpserver.servlet.PageNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class ServletManager {
private final Map<String, HttpServlet> servletMap = new HashMap<>();
private HttpServlet defaultServlet;
private HttpServlet notFoundServlet = new NotFoundServlet();
private HttpServlet inernalErrorServlet = new InternalErrorServlet();
public ServletManager() {
}
public void add(String path, HttpServlet servlet) {
servletMap.put(path, servlet);
}
public void setDefaultServlet(HttpServlet defaultServlet) {
this.defaultServlet = defaultServlet;
}
public void setNotFoundServlet(HttpServlet notFoundServlet) {
this.notFoundServlet = notFoundServlet;
}
public void setInernalErrorServlet(HttpServlet inernalErrorServlet) {
this.inernalErrorServlet = inernalErrorServlet;
}
public void excute(HttpRequest request, HttpResponse response) throws IOException {
try{
HttpServlet servlet = servletMap.getOrDefault(request.getPath(), defaultServlet);
if(servlet == null){
throw new PageNotFoundException("request url = " + request.getPath());
}
servlet.service(request, response);
}catch (PageNotFoundException e){
e.printStackTrace();
notFoundServlet.service(request, response);
}catch (Exception e){
e.printStackTrace();
inernalErrorServlet.service(request,response);
}
}
}