Skip to content

Commit 31da9f7

Browse files
committed
Cải tiến tối ưu lại function gọi bên controller
1 parent b06e684 commit 31da9f7

7 files changed

Lines changed: 138 additions & 40 deletions

File tree

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,15 @@
11
package controller;
22

3-
import jakarta.servlet.ServletException;
4-
import jakarta.servlet.http.HttpServletRequest;
5-
import jakarta.servlet.http.HttpServletResponse;
6-
import java.io.IOException;
73
import util.ViewUtils;
84

95
public class HomeController {
106

11-
public static void index(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
12-
// req.getRequestDispatcher("/index.jsp").forward(req, resp);
7+
public static void index() {
138
ViewUtils.put("message", "Welcome to the Home Page!");
14-
ViewUtils.render(req, resp, "auth/login");
9+
ViewUtils.render("auth/login");
1510
}
1611

17-
public static void index1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
18-
req.getRequestDispatcher("/index.jsp").forward(req, resp);
19-
}
12+
// public static void index1(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
13+
// req.getRequestDispatcher("/index.jsp").forward(req, resp);
14+
// }
2015
}

BaseJava/src/main/java/router/Router.java

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import jakarta.servlet.http.HttpServletRequest;
88
import jakarta.servlet.http.HttpServletResponse;
99
import java.io.IOException;
10+
import util.WebContext;
1011

1112
public class Router {
1213

@@ -34,19 +35,20 @@ public static void controller(Class<?> controller, Runnable routeDefinitions) {
3435
currentController = previousController; // Khôi phục controller trước đó
3536
}
3637

37-
public static void route(HttpServletRequest request, HttpServletResponse response) throws IOException {
38+
public static void route() throws IOException {
39+
HttpServletRequest request = WebContext.getCurrentRequest();
40+
HttpServletResponse response = WebContext.getCurrentResponse();
3841
String contextPath = request.getContextPath();
3942
String requestURI = request.getRequestURI();
4043
String pathInfo = requestURI.substring(contextPath.length());
41-
4244
String httpMethod = request.getMethod();
4345
String key = httpMethod + " " + (pathInfo != null ? pathInfo : "/");
4446
Route route = routes.get(key);
4547

4648
if (route != null) {
4749
try {
48-
Method actionMethod = route.getController().getMethod(route.getMethodName(), HttpServletRequest.class, HttpServletResponse.class);
49-
actionMethod.invoke(route.getController().newInstance(), request, response);
50+
Method actionMethod = route.getController().getMethod(route.getMethodName());
51+
actionMethod.invoke(route.getController().newInstance());
5052
} catch (Exception e) {
5153
e.printStackTrace();
5254
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal server error");

BaseJava/src/main/java/router/RouterFilter.java

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import jakarta.servlet.http.HttpServletRequest;
1212
import jakarta.servlet.http.HttpServletResponse;
1313
import java.io.IOException;
14+
import util.WebContext;
1415

1516
// WebFilter annotation chỉ định filter này áp dụng cho mọi URL pattern
1617
@WebFilter("/*")
@@ -29,20 +30,18 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha
2930
HttpServletRequest httpRequest = (HttpServletRequest) request;
3031
HttpServletResponse httpResponse = (HttpServletResponse) response;
3132

32-
// Lấy context path của ứng dụng (phần URL trước servlet path)
33-
String contextPath = httpRequest.getContextPath();
34-
// Lấy URI được yêu cầu hoàn chỉnh
35-
String requestURI = httpRequest.getRequestURI();
36-
// Xác định đường dẫn thực tế được yêu cầu, bỏ qua context path
37-
String path = requestURI.substring(contextPath.length());
33+
WebContext.setCurrentRequest(httpRequest);
34+
WebContext.setCurrentResponse(httpResponse);
3835

39-
// Kiểm tra nếu đường dẫn không bắt đầu bằng "/assets" (thường là các tài nguyên tĩnh)
40-
if (!path.startsWith("/assets")) {
41-
// Nếu không phải tài nguyên tĩnh, xử lý đường dẫn bằng cách sử dụng router đã định nghĩa
42-
Router.route(httpRequest, httpResponse);
43-
} else {
44-
// Nếu là tài nguyên tĩnh, cho phép request tiếp tục đi qua các filter tiếp theo (nếu có)
45-
chain.doFilter(request, response);
36+
try {
37+
String path = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length());
38+
if (!path.startsWith("/assets")) {
39+
Router.route();
40+
} else {
41+
chain.doFilter(request, response);
42+
}
43+
} finally {
44+
WebContext.clear();
4645
}
4746
}
4847
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/*
2+
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
3+
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
4+
*/
5+
package util;
6+
7+
/**
8+
*
9+
* @author Hoai Nam
10+
*/
11+
import jakarta.servlet.ServletException;
12+
import jakarta.servlet.http.HttpServletRequest;
13+
import jakarta.servlet.http.HttpServletResponse;
14+
15+
import java.io.IOException;
16+
17+
public class ExceptionHandler {
18+
19+
public static void handleException(HttpServletRequest request, HttpServletResponse response, Throwable e) {
20+
try {
21+
if (e instanceof ServletException) {
22+
response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
23+
} else if (e instanceof IOException) {
24+
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
25+
} else {
26+
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An unexpected error occurred.");
27+
}
28+
} catch (IOException ioException) {
29+
ioException.printStackTrace();
30+
}
31+
}
32+
}

BaseJava/src/main/java/util/ViewUtils.java

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,25 +4,22 @@
44
import jakarta.servlet.http.HttpServletRequest;
55
import jakarta.servlet.http.HttpServletResponse;
66
import java.io.IOException;
7-
import java.util.HashMap;
8-
import java.util.Map;
7+
import util.WebContext;
98

109
public class ViewUtils {
1110

12-
private static ThreadLocal<Map<String, Object>> modelHolder = ThreadLocal.withInitial(HashMap::new);
13-
1411
public static void put(String key, Object value) {
15-
modelHolder.get().put(key, value);
12+
HttpServletRequest request = WebContext.getCurrentRequest();
13+
request.setAttribute(key, value);
1614
}
1715

18-
public static void render(HttpServletRequest request, HttpServletResponse response, String viewName) throws ServletException, IOException {
19-
Map<String, Object> model = modelHolder.get();
20-
if (model != null) {
21-
for (Map.Entry<String, Object> entry : model.entrySet()) {
22-
request.setAttribute(entry.getKey(), entry.getValue());
23-
}
16+
public static void render(String viewName) {
17+
try {
18+
HttpServletRequest request = WebContext.getCurrentRequest();
19+
HttpServletResponse response = WebContext.getCurrentResponse();
20+
request.getRequestDispatcher("/WEB-INF/views/" + viewName + ".jsp").forward(request, response);
21+
} catch (ServletException | IOException e) {
22+
ExceptionHandler.handleException(WebContext.getCurrentRequest(), WebContext.getCurrentResponse(), e);
2423
}
25-
request.getRequestDispatcher("/WEB-INF/views/" + viewName + ".jsp").forward(request, response);
26-
modelHolder.remove(); // Clear the model after rendering to prevent leak
2724
}
2825
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
3+
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
4+
*/
5+
package util;
6+
7+
/**
8+
*
9+
* @author Hoai Nam
10+
*/
11+
import jakarta.servlet.http.HttpServletRequest;
12+
import jakarta.servlet.http.HttpServletResponse;
13+
14+
public class WebContext {
15+
16+
private static ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<>();
17+
private static ThreadLocal<HttpServletResponse> responseHolder = new ThreadLocal<>();
18+
19+
public static void setCurrentRequest(HttpServletRequest request) {
20+
requestHolder.set(request);
21+
}
22+
23+
public static HttpServletRequest getCurrentRequest() {
24+
return requestHolder.get();
25+
}
26+
27+
public static void setCurrentResponse(HttpServletResponse response) {
28+
responseHolder.set(response);
29+
}
30+
31+
public static HttpServletResponse getCurrentResponse() {
32+
return responseHolder.get();
33+
}
34+
35+
public static void clear() {
36+
requestHolder.remove();
37+
responseHolder.remove();
38+
}
39+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
3+
* Click nbfs://nbhost/SystemFileSystem/Templates/JSP_Servlet/Filter.java to edit this template
4+
*/
5+
package util;
6+
7+
import util.ExceptionHandler;
8+
import util.WebContext;
9+
import jakarta.servlet.*;
10+
import jakarta.servlet.annotation.WebFilter;
11+
import jakarta.servlet.http.HttpServletRequest;
12+
import jakarta.servlet.http.HttpServletResponse;
13+
14+
import java.io.IOException;
15+
16+
/**
17+
*
18+
* @author Hoai Nam
19+
*/
20+
@WebFilter(filterName = "WebContextFilter", urlPatterns = {"/*"})
21+
public class WebContextFilter implements Filter {
22+
23+
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
24+
WebContext.setCurrentRequest((HttpServletRequest) request);
25+
WebContext.setCurrentResponse((HttpServletResponse) response);
26+
try {
27+
chain.doFilter(request, response);
28+
} catch (Exception e) {
29+
ExceptionHandler.handleException((HttpServletRequest) request, (HttpServletResponse) response, e);
30+
} finally {
31+
WebContext.clear();
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)