发送URL时发回xml响应

时间:2011-12-16 06:27:35

标签: java

我的任务是检查我的程序是否在服务器上正常运行。方案是这样的:一个URL被发送到持续运行的程序,如果它正在运行,它应该以状态OK回复很好。我无法理解如何做到的过程。任何人都可以解释。

1 个答案:

答案 0 :(得分:2)

好的,我假设您想为您的应用程序编写某种运行状况检查页面。所以就这样了。

package test.naishe.so;

public class HealthCheck extends HttpServlet {

    private static final long serialVersionUID = 940861886429788526L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        int response = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

        boolean checkServices = true;
        //optional: assumming you wanted to do health check on various services (eg. DB service) and have a utility class for that
        checkServices = CheckServices.checkAll();

        if(checkServices)
            response = HttpServletResponse.SC_OK;

        String out =
            "<healthCheck>" +
            "<services>" +
                (checkServices?"OK":"ERROR")
            "</services>" +
            "</healthCheck>"
            ;

        resp.setStatus(response);
        resp.getWriter().println(out);

    }
}
在您的web.xml中

添加以下内容:

  <servlet>
    <servlet-name>healthCheck</servlet-name>
    <servlet-class>test.naishe.so.HealthCheck</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>healthCheck</servlet-name>
    <url-pattern>/check_health</url-pattern>
  </servlet-mapping>

您可以从本地计算机上的<base_url>/check_health http://localhost[:port][/app_name]/check_health

访问此页面