如何使用JSP页面中的参数运行Java类? [英] How do I run a java class with arguments from a JSP page?
问题描述
我以前编写了一个从bash文件执行的Java类,现在我需要使用Javascript/HTML按钮从JSP页面执行该类,我想知道该怎么做?
I have previously written a java class that was executed from a bash file, now I need to allow its execution from a JSP page using a Javascript/HTML button, I wonder how do I do that?
首先,我的课看起来像这样:
First, my class looks like this:
public class Sync
{
public static void main(String[] args)
{
//my content here
}
}
此Sync类已通过bash脚本运行,如下所示:
This Sync class has been run from a bash script as follows:
cd /root/tomcat/webapps/project/WEB-INF/classes/
echo "Executing first part..."
/usr/local/java/bin/java classes/CLRSyncCLI 120.0.0.1 up false Y ${IPS[@]}
echo "Executing second part..."
/usr/local/java/bin/java classes/CLRSyncCLI 127.0.0.1 down false Y ${IPS[@]}
请注意:classes是TomCat Web服务器中所有已编译的Java类所在的目录.
note that:classes is the directory where all compiled java classes are within the TomCat web server.
现在在jsp页面中,我需要类似的东西:
now within jsp page I need something like:
<input type="button" value="Execute" name="to" action="run" onClick="path here">
如何通过单击一次按钮两次运行此同步类及其参数,并显示该类已执行并显示一条消息.
How do I run this sync classes with its arguments twice from a single button click, and display that the class has been executed with a message.
推荐答案
首先,我想说的是一个不好的主意.您确实应该按照前面的答案中所述重构Sync
.
First, I'd like to say what you are proposing is a bad idea. You should really refactor Sync
as described in the previous answers.
但是,如果您不愿按原样使用Sync
,则下面的一些代码可能会有所帮助:
However, if you are dead-set on using Sync
as-is, here is some code that might help:
<% if( request.getParameter( "to" ) == null ) { %>
<p>
Click 'Execute' to begin processing.
</p>
<form>
<input type="submit" value="Execute" name="to" />
</form>
<% } else { %>
<p>
Processing...
</p>
<pre>
<%
PrintStream sysout = System.out;
try {
File syncFile = File.createTempFile( "Sync", ".tmp" );
PrintStream syncOs= new PrintStream( syncFile );
System.setOut( syncOs );
String[] myArgs = ...; // set up your args
Sync.main( myArgs );
// ... do whatever else you need to do
syncOs.close();
syncFile.close();
FileReader syncRdr = new FileReader( syncFile );
String line = null;
while( ( line = syncRdr.readLine() ) {
out.println( line );
}
syncRdr.close();
syncFile.delete();
} catch( Exception ex ) {
out.print( ex );
} finally {
System.setOut( sysout );
}
%>
</pre>
<% } %>
这里有一些潜在的陷阱,尤其是在多线程中.但是也许您可以以此为起点?另外,我尚未调试它,因此您可能需要做更多的工作.
There are some potential pitfalls here, especially with multithreading. But maybe you can use this as a starting point? Also, I have not debugged it, so you might need to do more work.
祝你好运
DC
这篇关于如何使用JSP页面中的参数运行Java类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!