有 Java 编程相关的问题?

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

servlets Java web应用程序对象调度

HttpSession对象是否可用于运行在同一java企业应用服务器中的所有应用程序

对于我的工作,我有一个进行身份验证的登录应用程序,然后它将被转发到另一个应用程序。在第二个应用程序中,添加了过滤器以防止直接访问URL

ServletContext-仅获取当前Web应用程序的上下文

处理这种情况的正确方法是什么


共 (3) 个答案

  1. # 1 楼答案

    没有HttpSession对象不可用于同一服务器中的所有应用程序。 为了验证

    创建2个应用程序, 在一个应用程序中使用seision。setAttribute(“你好”、“你好”); 现在运行第二个应用程序

    if(session.getAttribute("hello")==null)
    {
    //some codes to check
    }
    else
    
    {
    //some codes to check
    }
    

    您将看到部分是否将被执行

  2. # 2 楼答案

    HttpSession对象的作用域在应用程序(或servlet上下文)级别

    摘自Java™ Servlet Specification

    HttpSession objects must be scoped at the application (or servlet context) level. The underlying mechanism, such as the cookie used to establish the session, can be the same for different contexts, but the object referenced, including the attributes in that object, must never be shared between contexts by the container.

    To illustrate this requirement with an example: if a servlet uses the RequestDispatcher to call a servlet in another Web application, any sessions created for and visible to the servlet being called must be different from those visible to the calling servlet.

    处理此场景的方法:

    您可以使用servletContext.getContext("/otherWebappContext")方法从一个servlet上下文访问另一个servlet上下文的可用资源,如下所示:

    request.setAttribute("userToken", <token>);
    RequestDispatcher requestDispatcher = getServletContext().getContext(
                    "/otherWebappContext").getRequestDispatcher("/resource");
    requestDispatcher.forward(request, response);
    

    但是为被调用的servlet创建的任何会话都不同于调用servlet的会话。一旦请求被转发到第二个应用程序,它就可以使用通过请求属性接收的数据创建一个新会话

    但出于安全原因,servlet容器通常会阻止这些跨上下文操作。因此,您需要更改默认行为。例如,在Tomcat 6中,需要将Tomcat_HOME/conf/context中的<Context>元素的crossContext属性设置为“true”。xml文件如下所示:

    <?xml version='1.0' encoding='utf-8'?>
    <Context crossContext="true">
    
        <!  Default set of monitored resources  >
        <WatchedResource>WEB-INF/web.xml</WatchedResource>
    </Context>
    
  3. # 3 楼答案

    应用程序之间不共享任何HttpSession对象。容器中不同应用程序之间共享信息的标准方法是使用ServletContext。ServletContext的唯一限制是,如果一个web应用程序分布在多个JVM之间,这将不起作用,因为上下文信息在一个JVM中