简体   繁体   中英

Init method gets called twice java servlet

I want to call the init method when the application starts.

    <servlet>
      <servlet-name>servletTest</servlet-name>
      <servlet-class>com.gateway.Gateway</servlet-class>
      <load-on-startup>1</load-on-startup>
   </servlet>

above is my code to do so. But strangely init method gets called twice. Below is my servlet code. Any help would be appreciated.

    @WebServlet("/Gateway")
public class Gateway extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public Gateway() {
        super();
    }
    public void init(ServletConfig config) throws ServletException {
        System.out.println("Init called");
    }
    public void destroy() {
        System.out.println("Destroy called");
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Received a Request");
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }
}

You are actually creating two instances (objects) of the Gateway Servlet class one through web.xml and one through @WebServlet , so init() is being invoked twice (one from each instance). By default, a servlet class should have a single instance (unless you wanted to run differently).

So to solve the issue, you have got two options:

(1) Remove the web.xml and add loadOnStartup=1 to your @WebServlet as show below: @WebServlet(urlPatterns="/Gateway", loadOnStartup=1)

(2) Remove @WebServlet(urlPatterns="/Gateway") in your Gateway class and configure the servlet in web.xml as shown below:

 <servlet>
      <servlet-name>Gateway</servlet-name>
      <servlet-class>com.gateway.Gateway</servlet-class>
      <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
      <servlet-name>Gateway</servlet-name>
      <url-pattern>/Gateway</url-pattern>
  </servlet-mapping>

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