Only one instance of the servlet is created. This is why it is so important not to include fields in your servlet that are used within the get
and post
methods. A class instance variable (field) within a servlet is not thread safe and could be modified by multiple requests resulting in unexpected behavior.
Consider the following example:
ServletTest.java
@WebServlet("/ServletTest")
public class ServletTest extends HttpServlet {
private static final long serialVersionUID = 1L;
private Integer increment = 0;
public ServletTest() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println(increment++);
}
}
test.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ServletTest" method="post">
<button type="submit">Submit</button>
</form>
</body>
</html>
If you run this example and hit the submit button it will print 0 to the console. Subsequent submits of the form will print 1, then 2, etc... This proves the servlet is the same instance.