强行停止servlet

时间:2014-12-25 13:58:10

标签: servlets

除非所有线程都退出服务,否则应该做什么来手动停止Servlet,因为调用destroy不会有帮助。

说,如果我有多个Servlet,我想只停止其中一个。

1 个答案:

答案 0 :(得分:1)

在处理Servlet时,这种行为非常重要。可以在多线程模型之后创建实例,因此不是线程安全的。

在调用service后,容器不允许线程调用destroy方法。

这使您可以关闭Servlet正在使用的所有资源(db,file,memory等)。

@WebServlet
public class OncePerApplicationServlet extends HttpServlet {

private Connection connection;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    if(req.getParameter("closeServlet").equals("true"))
        this.destroy();
    else
        this.service(req, resp); // normal flow
}

// this method will never be called by the container after the destroy method has been invoked
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // 1.
    try {
        connection = DriverManager.getConnection("someDbUrl");
        Statement stm = connection.createStatement();
        stm.execute("select * from someTable");
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

@Override
public void destroy() {
    // the point is that when this method is called you should be able to
    // clean up and close all resources, you can rest assured that there are no "loose"
    // threads that need the connection-instance
    try {
        connection.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
}

以下是API-docs的引用:

  

此接口定义了初始化servlet以进行服务的方法   请求,以及从服务器中删除servlet。这些被称为   生命周期方法按以下顺序调用:

     

构造servlet,然后使用init方法初始化。任何   处理从客户端到服务方法的调用。 servlet是   停止服务,然后用destroy方法销毁   收集并最终确定垃圾。   |

Link to the documentation

祝你好运!