为什么这个@SessionScoped类经常被重新创建?

时间:2017-06-28 03:35:36

标签: java tomcat java-ee tomcat8

我有一个@SessionScoped类,它包含一个私有变量。我注意到,如果我单独离开浏览器选项卡约5-10秒然后刷新,则私有变量为null。所以我在构造函数中放了System.out.println,我发现它被多次创建了!

为什么会这样?

package com.test;

import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;

@SessionScoped
public class TestSessionScoped implements Serializable
{
    @Inject
    private MyOtherClass injectedOther;

    public TestSessionScoped()
    {
        System.out.println( "CREATED TestSessionScoped.class in Session Scope" );
    }

    private int userid = 0;

    //Simplified to test setting the variable
    public void login()
    {
        userid = 1;
    }
}

的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
        version="3.1">
<display-name>DI API</display-name>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
</welcome-file-list>

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.test.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

    <!-- CDI listener (Used by events) -->
    <listener>
        <listener-class>org.jboss.weld.environment.servlet.Listener</listener-class>
    </listener>

    <!-- CDI Bean Manager for injecting events -->
    <resource-env-ref>
        <resource-env-ref-name>BeanManager</resource-env-ref-name>
        <resource-env-ref-type>javax.enterprise.inject.spi.BeanManager</resource-env-ref-type>
    </resource-env-ref>

    <session-config>
        <session-timeout>20</session-timeout>
    </session-config>

</web-app>

0 个答案:

没有答案