如何为 tomcat Web 应用程序实现控制台命令行?

如何为 tomcat Web 应用程序实现控制台命令行?

问题描述:

我有一个网络应用程序

  • 由 tomcat 7.1 托管
  • 使用 spring 3.1 mvc 框架.

我想为tomcat控制台窗口实现一个命令行功能,读取命令并执行一些操作或输出一些信息到控制台.我该怎么做?

I want to implement a command line function for tomcat console window, to read commands and perform some action or output some information to console. How can I do it?

示例:输入show memory",然后向控制台显示JVM内存信息.

Example: type "show memory", then display JVM memory information to console.

我可以仅通过 System.in 来完成吗?会不会有线程安全问题?

Can I do it just by System.in? Will there be any thread-safe problem?

如果您在 Tomcat 中作为 Web 应用程序运行,您将无法访问 System.in 或控制台:Tomcat 通常在背景,与所有控制台分离.它不会为您提供对控制台的有意义的访问.

If you're running as a web application in Tomcat, you won't get any access to System.in or the console: Tomcat is typically started in the background, detached from all consoles. And it won't provide you witn meaningful access to the console.

要走的路是提供@rlegendi 在评论中建议的 REST API(任何其他 API 也可以),并编写一个单独的命令行应用程序与您的 API 接口.或者使用管理器"界面 - 如果我从古代没记错的话,tomcat 的管理器应用程序也有一些可以从外部脚本访问的可用方法.

The way to go is to either provide a REST API as suggested by @rlegendi in the comments (any other API would work as well) and write a separate command line application that interfaces with your API. Alternatively utilize the "manager" interface - if I remember correctly from ancient past, tomcat's manager application also has some usable methods to access from external scripts.

确保对这些调用进行身份验证 - 至少验证它们来自本地主机,以便您在 API 中模拟某种安全性.不要相信来自世界各地的随机电话.

Make sure to make those calls authenticated - at least validate that they're coming from localhost so that you simulate some kind of security in the API. Don't trust random calls coming in from the world.