carles
carles

Reputation: 174

Avoid sharing static vars among servlets

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.

Upvotes: 0

Views: 51

Answers (2)

DuncG
DuncG

Reputation: 15107

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.

Upvotes: 1

haoyu wang
haoyu wang

Reputation: 1377

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.

Upvotes: 0

Related Questions