Issue
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 {
...
}
}
Solution
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
Answered By - SirFartALot