避免在Servlet之间共享静态变量。

huangapple go评论82阅读模式
英文:

Avoid sharing static vars among servlets

问题

我已经使用Servlet中的静态变量实现了一个完整的网站,就像这样:

public class UserData extends HttpServlet {

    public static String fisrtName;
    public static String lastName;
    public static String id;
    
    ...

我在使用Servlet方面是完全新手,所以如果问题看起来太傻,请原谅。

无论如何,我的问题现在是,当一个用户连接时,其他可能连接的用户会直接获得第一个用户提供的所有数据。

我需要一种方式来表示所有这些静态变量不应该在连接之间共享。

请告诉我最简单的方法,因为项目几乎已经完成,到目前为止我还没有意识到这个巨大的陷阱。

谢谢。

英文:

I have implemented a whole website using static variables in servlets. Like this

public class UserData extends HttpServlet {

    public static String fisrtName;
    public static String lastName;
    public static String id;
    
    ...

I am absolutely new in using servlets, so sorry if the question seems too silly.

Anyway, my problem now is that when a user is connected, others that might connect get directly with all data given by the first one.

I would need some way to say that all those static variables must not be shared among connections.

Please tell me the easiest way to do that, since the project is almost finished, and so far I didn't realize this enormous pitfall.

Thanks.

答案1

得分: 1

如@haoyu wang建议,会话是一个好地方,但将所有字段收集到一个类中(作为实例而不是静态变量):

public class UserInfo {
    public String fisrtName;
    public String lastName;
    public String id;
    ...
}

然后将其设置/检索为一个单元,这样您可以更轻松地将用户信息传递给您的Servlet的其他组件:

UserInfo info = session.getAttribute("userinfo");
if (info == null) {
    userinfo = new UserInfo();
    ... 填充字段/验证
    session.setAttribute("userinfo", userinfo);
}

请注意,getValue和putValue已弃用,因此应使用getAttribute / setAttribute代替。

英文:

As @haoyu wang suggests, session is a good place but collect all your fields into one class (as instance not static variables):

public class UserInfo{
    public String fisrtName;
    public String lastName;
    public String id;
    ...
}

Then set/retrieve as one unit so you can pass user information more easily to other components of your servlets:

UserInfo info = session.getAttribute("userinfo");
if (info == null) {
    userinfo = new UserInfo();
    ... fill in fields / validate
    session.setAttribute("userinfo", userinfo);
}

Note that getValue and putValue are deprecated so should use getAttribute / setAttribute instead.

答案2

得分: 0

你应该将这些数据放入会话中,像这样:session.putValue("firstName", name),然后使用session.getValue("firstName")来检索它们。

会话对象不会在不同会话之间共享,不同用户有不同的会话。您不必担心它们会在不同用户之间共享。

英文:

You should put those data in session, like session.putValue("firstName",name) and use session.getValue("firstName") to retrive them.

Session objects will not be shared in different sessions and different user have different sessiion. You don't have to worry them are shared among different user.

huangapple
  • 本文由 发表于 2020年7月29日 21:40:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63154969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定