我已经使用自定义登录系统编写了一个应用程序。然后为其编写我自己的安全过滤器,该过滤器设置了可以访问的区域。但是我总是被重定向到登录页面,然后重定向到索引页面,登录页面是首页。我发现会话ID与登录后尝试使用受限制的东西时不同。这是我的代码:

public class securtityFilter implements Filter {

public void init(FilterConfig filterConfig) throws ServletException {
    //To change body of implemented methods use File | Settings | File Templates.
}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
            // if there is no userBean, then they have not gone through
            // the login, so kick them to the login page
            if(null==req.getSession().getAttribute("username"))
            {
                ((HttpServletResponse)servletResponse).sendRedirect("../Login.jsp");
                System.out.println("Redirected - No session");

            }
                    // otherwise, let them go to the page/resource they want
                    filterChain.doFilter(servletRequest, servletResponse);
                System.out.println("Gone through Filter");

              //  System.out.println("In Filter Servlet: "+ req.getSession().getId());

            }

public void destroy() {
    //To change body of implemented methods use File | Settings | File Templates.
}
}


这是我的web.xml文件:

  <filter>
     <filter-name>SecurityFilter</filter-name>
     <filter-class>filters.securtityFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SecurityFilter</filter-name>
    <url-pattern>/add/*</url-pattern>
</filter-mapping>

最佳答案

在您的登录servlet中,您有

while (rs.next())
{
  HttpSession session = request.getSession(true);
  String tmp = rs.getString(1);
  System.out.println(tmp);
  session.setAttribute("username", tmp);
  count++;
 }


因此,如果您的会话中没有用户名属性,那是因为未执行此代码块。我假设您正在遍历数据库查询的结果,因此请检查您正在执行的实际查询是否返回任何结果。

08-04 06:01