有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java过滤器中的servlet问题

我在这里创建了我的简单事务管理应用程序,我使用了一个过滤器。它适用于除首次登录之外的所有场景

重新启动服务器后,如果尝试访问应用程序的主页面,它将直接重定向到登录页面

当我提交登录时,它会转到主应用程序页面。直到这一点过滤器工作正常,但从应用程序主页面,如果我试图访问登录页面,它应该重新加载主应用程序页面,但它将登录页面。这里只是出了问题

如果我再次刷新页面,它将正确加载主应用程序页面

这是我的过滤代码:

public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    String loginPage = "login.html";
    HttpServletRequest httpRequest=(HttpServletRequest) req;
    HttpSession session=httpRequest.getSession(false);
    HttpServletResponse httpResponse=(HttpServletResponse) response;

    String username = session != null ? (String)   session.getAttribute("username") : null;

    if(!canAllowThisRequest(httpRequest)){
        if((session == null || username==null) && !httpRequest.getRequestURL().toString().contains(loginPage))
        {
            System.out.println("Requested Resource: " + httpRequest.getRequestURL().toString() + ", Redirecting to: " + loginPage);
            httpResponse.sendRedirect(loginPage);
            return;

        }
        else if(httpRequest.getRequestURL().toString().contains(loginPage) && username != null){
            System.out.println("Requested Resource: " + httpRequest.getRequestURL().toString() + ", Redirecting to: " + loginPage);
            httpResponse.sendRedirect("transactiondetail.html");
            return;
        }
        System.out.println("Requested Resource(Inner): " + httpRequest.getRequestURL().toString() + ", UserName :" + username);
        chain.doFilter(req, response);
    }
    else{
        System.out.println("Requested Resource(Outer): " + httpRequest.getRequestURL().toString());
        chain.doFilter(req, response);
    }
    //chain.doFilter(req, response);
}

public boolean canAllowThisRequest(HttpServletRequest httpRequest){
    String[] allowedResourcesWithoutSession = {"/js/jquery.min.js", "/js/jquery.validate.js", "/js/loginOperations.js", "LoginAuthentication"};

    String requestURL =  httpRequest.getRequestURL().toString();

    for(int i = 0; i < allowedResourcesWithoutSession.length; i++){
        if(requestURL.contains(allowedResourcesWithoutSession[i])){
            return true;
        }
    }

    return false;
}

过滤器映射:

<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

谢谢 -萨钦


共 (0) 个答案