简体   繁体   中英

How to access servlet variable from java class

I have a servlet like

public class MainServlet extends HttpServlet {
public List<Card> cardList = new ArrayList<Card>();
public int numberOfCard = 0;
 .................
 .................
} 

Now I want to access this global variable from normal java class with in same package, How can I do it?

I think this is not a good pattern to use.

Please keep in mind that the Servlet container has only one instance of this servlet shared among calls. This means that having a global variable in a servlet has concurrency issues.

If you want to make something better you could define another singleton class that handle a common storage, so that you can write and read values directly in it. However you did not specify if the "normal java class" is running in the same thread or it is launched by another process/thread. Also in this last case you could have concurrency issues, so it could be nice to use not a simple list, but one of the Concurrency enabled ones defined in java.util.concurrent package.

Regards

Paolo

we cannot create object for servlet like a normal class,because servlet are running inside the server so that servlet object is created by the servlet container. If we want to use the variables in some other class which are declared in servlet means you need to create the object of servlet and you can use those variables.

you should not use instance variables in servlet,because those variables shared by all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM