j2ee中如何拦截jsp页面?

时间:2023-03-01 22:04:14

加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>