tw.com.javaworld.CH11.SessionChecker (Java2HTML)

| SessionChecker.java |

    1 package tw.com.javaworld.CH11;
    2
    3 import java.io.*;
    4 import javax.servlet.*;
    5 import javax.servlet.http.*;
    6
    7 public class SessionChecker implements Filter {
    8     private ServletContext context;
    9     private String targetURI;
    10
    11    public void init(FilterConfig config) throws ServletException {
    12        context = config.getServletContext();
    13        targetURI = config.getInitParameter("targetURI");
    14    }
    15
    16    public void doFilter(
    17        ServletRequest request,
    18        ServletResponse response,
    19        FilterChain chain)throws IOException, ServletException {
    20
    21        HttpServletRequest httpRequest = (HttpServletRequest) request;
    22        HttpServletResponse httpResponse = (HttpServletResponse) response;
    23        HttpSession session = httpRequest.getSession(false);
    24
    25        if (session != null) {
    26            String passed = (String) session.getAttribute("passed");
    27            if (passed.equals("true")) {
    28                chain.doFilter(httpRequest, httpResponse);
    29                return;
    30            } else if (passed.equals("passing")) {
    31                if (new String(httpRequest.getRequestURI())
    32                    .equals("/JSPBook/LoginChecker")) {
    33                    chain.doFilter(httpRequest, httpResponse);
    34                    return;
    35                }
    36            } else { }
    37
    38            session.removeAttribute("passed");
    39        }
    40        StringBuffer requestURL = httpRequest.getRequestURL();
    41        String query = httpRequest.getQueryString();
    42        if (query != null)
    43            requestURL.append(query);
    44        httpRequest.setAttribute("originalURI", new String(requestURL));
    45        httpRequest.getRequestDispatcher(targetURI).forward(httpRequest, httpResponse);
    46    }
    47    public void destroy() {
    48    }
    49}