-
Notifications
You must be signed in to change notification settings - Fork 0
/
FrontController.java
69 lines (61 loc) · 2.1 KB
/
FrontController.java
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
package com.kn.controller;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
import com.kn.dto.Message;
import com.kn.dto.Message.TYPE;
import com.kn.processor.Handler;
import com.kn.processor.HandlerFactory;
/**
* Servlet implementation class FrontController
*/
@WebServlet(urlPatterns = { "*.do" })
public class FrontController extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void init() throws ServletException {
super.init();
String[] packages = new String[] { "com.kn.controller" };
HandlerFactory.initializeHandlers(getClass().getClassLoader(), packages);
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String url = request.getServletPath();
Handler handler = HandlerFactory.getHandler(url);
Message errorMessage = null;
boolean hasError = false;
if (handler != null) {
try {
handler.invokeMethod(request, response);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
hasError = true;
errorMessage = new Message(501, TYPE.ERROR, "Server dancing for: " + url);
e.printStackTrace();
}
} else {
hasError = true;
errorMessage = new Message(404, TYPE.ERROR, "don't know what to do with: " + url);
}
if (hasError) {
Gson gson = new Gson();
response.getWriter().append(gson.toJson(errorMessage)).close();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}