public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httprequest = (HttpServletRequest)request;
HttpServletResponse httpresponse = (HttpServletResponse)response;
//HttpSession session = httprequest.getSession();
//可以不保存在session中, 并且前面我保存在request,这里session也可以获取
if(httprequest.getAttribute("username")!=null){
chain.doFilter(request, response); //只有登录名不为空时放行,防止直接登录 成功的页面
}else{
httpresponse.sendRedirect("login.jsp");
}
}
<filter> <filter-name>LoginFilter</filter-name> <filter-class>filter.LoginFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginFilter</filter-name> <url-pattern>/success.jsp</url-pattern> </filter-mapping>
注意这个/success.jsp 是我们本想登录的页面,就是在你登录想登陆的页面前,只要配置一个上述的Filter.就可以