java - 将控制从被调用者 servlet 发送回调用者 jsp

标签 java jsp servlets redirect forward

我有一个要求,就像用户尝试在不登录应用程序的情况下访问应用程序中的任何网址一样

loggedin=false;
if(!loggedin)
{
forward request to login jsp page
}
else
{
execute the jsp
}

现在登录jsp将获取登录凭据并将其发送到 Controller servlet,如果登录凭据正确, Controller servlet必须将请求发送回用户访问的url。 我尝试过使用重定向/转发,但这些并不能完全满足需求。

我可以提出一些建议来实现这一目标

最佳答案

Spring Security 甚至 Java EE Declarative Security 中都有现成的解决方案。

无论如何,如果您想实现该行为,只需将原始 URL 的值存储在 Cookie 中即可。然后,当用户正确登录时,您可以重定向到保存的 URL

    boolean loggedin=false;
    if(!loggedin){
        Cookie c = new Cookie("URC", request.getPathInfo());
        c.setHttpOnly(true);
        c.setPath(request.getContextPath());
        c.setMaxAge(-1);
        response.addCookie(c);
        //forward request to login jsp page
    }else{
        Cookie cookie = getUrlRedirectCookie(request);
        if(cookie!=null){
            //redirect to cookie.getValue()
        }else{
            //execute the jsp
        }
    }
}

private Cookie getUrlRedirectCookie(HttpServletRequest request){
    Cookie[] cookies = request.getCookies();
    if(cookies!=null && cookies.length>0){
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if(cookie.getName().equals("URC")){
                return cookie;
            }
        }
    }
    return null;
}

关于java - 将控制从被调用者 servlet 发送回调用者 jsp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28146757/

相关文章:

java - Tomcat启动后调用构造函数

java - 从 html 表行调用 servlet 并在该行中获取响应

java - 请求后如何持久化请求数据

java - 如何使用 Java Servlet 维护 session

java - 在不损失质量的情况下调整图像大小

java - Eclipse (Luna) 始终显示空白小部件

java - ClassPathXmlApplicationContext : Error creating bean with name 'X' ; nested exception is java. lang.NoSuchMethodError : javax. persistence.Table.indexes()

jsp - 性能和信息 JSP 编译和运行时(websphere、tomcat)

jquery - 响应式数据表(createdRow)

java - JSP Servlet请求的资源()不可用