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
| class FilterDispatcher implements Filter {
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {}
public void destroy() {}
// 核心过滤方法
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String uri = req.getRequestURI();
// 1 action 请求
// 可能的 uri 形式为 / 站点名 /resourceName/ 可选路径 /Product_input.action
if (uri.endsWith(".action")) {
int lastIndex = uri.lastIndexOf("/");
//1.1 处理 action 结尾的请求
String action = uri.substring(lastIndex + 1);
if (action.equals("Product_input.action")) {
//1.1.1 请求商品输入不做处理
} else if (action.equals("Product_save.action")) {
Product product = new Product();
//1.1.2 保存商品信息
product.setProductName(request.getParameter("productName"));
product.setDescription(request.getParameter("description"));
product.setPrice(request.getParameter("price"));
product.save();
request.setAttribute("product", product);
}
//1.2 转向视图
String dispatchUrl = null;
if (action.equals("Product_input.action")) {
dispatchUrl = "/jsp/ProductForm.jsp";
} else if (action.equals("Product_save.action")) {
dispatchUrl = "/jsp/ProductDetails.jsp";
}
if (dispatchUrl != null) {
RequestDispatcher rd = request
.getRequestDispatcher(dispatchUrl);
rd.forward(request, response);
}
} else if (uri.indexOf("/css/") != -1
&& req.getHeader("referer") == null) {
//2 拒绝对样式表的直接访问
res.sendError(HttpServletResponse.SC_FORBIDDEN);
} else {
//3 请求其他资源,通过过滤器
filterChain.doFilter(request, response);
}
}
}
|