1

can we declare a object of a class as an instance variable in a servlet

public class BookServ extends HttpServlet {
    private static final long serialVersionUID = 1L;

    // declared object
    User user=new User();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         ...
    }
}
SirFartALot
  • 1,215
  • 5
  • 25

1 Answers1

1

Sure you can.

A User field makes not much sense, since your container would normally instantiate exactly ONE servlet instance with exactly ONE contained User instance. But this Servlet instance is allowed to run multiply in parallel on several threads, so several threads may access the single User instance concurrently.

You might want to store state within the servlet, which are initialized in the init() method of the servlet:

    public class BookServ extends HttpServlet {
        private static final long serialVersionUID = 1L;

        private String servletUID = null;

        public void init() throws ServletException {
            servletUID = ... generate a random String as UID ...
        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {    
              ...
        }
    }

Nevertheless you should be aware that there are several contexts, which should be used to store servlet data (request.getServletContext()), session data (request.getSession() or request data (request.setAttribute()/request.getAttribute()) to. So normally there is little need for fields within servlets.

Also check How do servlets work? Instantiation, sessions, shared variables and multithreading

SirFartALot
  • 1,215
  • 5
  • 25
  • the User is a normal java class ,here i should get data from that User class through the servlet bookServ ,myquestion is can i use the same object user for all doget,dopost and dodelete methods or should i declare the object in all the methods. –  Jun 27 '19 at 08:55
  • 2
    Only one Servlet instance is created. Therefore it is highly NOT recommended to save data in servlet fields. I guess for the `User` instance the best place to save it is `SessionContext`. – Dmitriy Popov Jun 27 '19 at 08:58
  • 2
    @Dmitriy Popov: you're definitly right: don't save data in servlet fields, but regarding the "one Servlet instance" it depends: https://stackoverflow.com/questions/12509830/does-each-request-access-the-same-servlet-object – SirFartALot Jun 27 '19 at 09:17