1 import java.io.IOException;
2 import javax.servlet.FilterChain;
3 import javax.servlet.FilterConfig;
4 import javax.servlet.ServletException;
5 import javax.servlet.ServletRequest;
6 import javax.servlet.ServletResponse;
7 import javax.servlet.annotation.WebFilter;
8 import javax.servlet.http.Cookie;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12 /**
13 * Servlet Filter implementation class Filter
14 */
15 @WebFilter("/*")
16 public class Filter implements javax.servlet.Filter {
17
18 /**
19 * Default constructor.
20 */
21 public Filter() {
22 // TODO Auto-generated constructor stub
23 }
24
25 /**
26 * @see Filter#destroy()
27 */
28 public void destroy() {
29 // TODO Auto-generated method stub
30 }
31
32 /**
33 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
34 */
35 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
36 // TODO Auto-generated method stub
37
38 // 将请求转换成HttpServletRequest请求
39 HttpServletRequest httpRequest=(HttpServletRequest)request;
40 // 将响应转换成HttpServletResponse响应
41 HttpServletResponse httpResponse = (HttpServletResponse)response;
42 //截取用户的请求地址
43 String from =httpRequest.getServletPath();
44 System.out.println(from);
45 if(from.equals("/login.html")) {
46 //获取本站在客户端上保留的所有的cookie
47 Cookie[] cookies=httpRequest.getCookies();
48 if(cookies!=null) {
49 //遍历cookie数组
50
51 httpResponse.sendRedirect("cookieSave");
52 }
53 // 将保存在cookie中的用户名和密码保存在request
54 /*httpRequest.setAttribute("username",username);
55 httpRequest.setAttribute("password", password);*/
56
57 // 放行请求
58 chain.doFilter(request, response);
59 }
60 else {
61
62 // 用户请求的地址是servlet,直接放行请求
63
64 chain.doFilter(request, response);
65
66 }
67 }
68
69 /**
70 * @see Filter#init(FilterConfig)
71 */
72 public void init(FilterConfig fConfig) throws ServletException {
73 // TODO Auto-generated method stub
74 //System.err.println("filter init");
75 }
76
77 }