如何避免在单例类中跨不同用户共享变量

时间:2015-07-06 07:45:29

标签: java servlets singleton

  public class CompanyServlet extends HttpServlet
    {

private static final long serialVersionUID = 1L;

private static org.apache.log4j.Logger  log = Logger.getLogger(Company.class);

/**
 * This string holds the filename of the file.
 */
String fileName = null;
Details detailsById = null;

    Page page = null;
String date = null;
HttpServletRequest request = null;

/**
 * This holds the bytes of the file to be written .
 */
Workbook wb = null;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    doPost(request, response);
}

public HttpServletRequest getRequest() {
    return request;
}

public void setRequest(HttpServletRequest request) {
    this.request = request;
}


public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

    }

类CompanyServlet是一个单例,因此成员字段请求在用户之间共享。结果是一个用户可以看到另一个用户的数据。如何避免这个问题。

1 个答案:

答案 0 :(得分:2)

不要在servlet中保持状态,如果你需要将它们存储在某个地方,请将它们保存在会话中。