j2ee中如何拦截jsp页面?

加filter:

public class RightFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        User user = (User) httpServletRequest.getSession(true).getAttribute("user");
        if (!isExcludePages(httpServletRequest.getRequestURI())) {
            if (user == null) {
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/login.jsp");
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private boolean isExcludePages(String url) {
        return url.indexOf("login.dhtml") != -1
                || url.indexOf("logout.dhtml") != -1
                || url.indexOf("login.jsp") != -1
                || url.endsWith(".css")
                || url.endsWith(".js")
                || url.endsWith(".gif")
                || url.endsWith(".jpg")
                || url.endsWith(".png");
    }

    public void destroy() {
    }
}

需要在web.xml里面配置一下:

<filter>
  <filter-name>rightFilter</filter-name> 
  <filter-class>com.xxx.filter.RightFilter</filter-class> 
  </filter>

<filter-mapping>
        <filter-name>rightFilter</filter-name>
        <url-pattern>*.dhtml</url-pattern>
    </filter-mapping>

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。