Servlet 中的每个请求都会一次又一次地调用 init
方法。
这是代码:
public class PersonInfoController extends HttpServlet {
private static final long serialVersionUID = 1L;
public PersonInfoController() {
super();
}
public void init() throws ServletException {
Connection connection = Database.getConnection();
System.out.println("init method");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<PersonInfoServiceI> myList = new ArrayList();
PersonInfoServiceI instance = new PersonInfoServiceImpl();
myList = instance.getdata();
String jsonstring = new Gson().toJson(myList);
request.setAttribute("List", jsonstring);
RequestDispatcher rd = request.getRequestDispatcher("showdata.jsp");
rd.forward(request, response);
}
public void destroy() {
System.out.println("the destory");
}
}
最佳答案
根据您的代码,当 servlet 在第一次请求时加载时,init() 应该只调用一次。然后在其销毁后,将根据新请求再次调用 init() 。在这之间,只会调用您的服务方法。你的代码很好,没有逻辑错误。 您是否在 servlet 外部调用 init 方法? 您可以附上您的部署描述符吗?
关于java - init 方法在 servlet 中一次又一次地调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30535165/