I want to start a .exe file from jsp button ie, when I click a start button on jsp page, it should start the exe file. I was able to write code in java with getruntime.exec() with main method and when I run the java code am able to start the .exe file and could view the result that the file is started in console. I am not sure how to call this java class into jsp and run the exe file from there. Could some one please help on this.
2 Answers
Firstly you need to be familiar with java servlets. Here's some basic steps:
1. Create a servlet to run the exe program
package mycompany;
public ExeRunnerServlet extends HttpServlet {
protected doGet(HttpServletRequest req, HttpServletResponse res) throws Exception {
String cmdToRunExe = //..
// Implement exe running here..
PrintWriter writer = res.getWriter();
writer.append("Command has been run");
}
}
This servlet only service GET http method. Search online for the code on how to run exe in Java, eg: https://stackoverflow.com/a/10686041/179630.
2. Map the servlet on you WEB-INF/web.xml deployment descriptor
<web-app>
<servlet>
<servlet-class>mycompany.ExeRunnerServlet</servlet-class>
<servlet-name>ExeRunnerServlet</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>ExeRunnerServlet</servlet-name>
<url-pattern>/exerunner</url-pattern>
</servlet-mapping>
</web-app>
This will map the above servlet into http://myhost/mywarname/exerunner
3. Link it from JSP
Finally on your JSP you can create a html link to above servlet that will execute your exe program. Assuming your jsp is located at http://myhost/mywarname/page.jsp :
<a href="exerunner">Run exe command</a>
Few words of warnings
- Creating a single servlet and mapping them manually into web.xml is considered an obsolete approach. Consider newer web framework such as Spring MVC / JSF.
- Calling exe from java is often regarded as a bad approach, especially if process forking is involved. I've seen cases where jvm took 800mb memory and the whole process had to be temporarily duplicated just to invoke exe command. Consider other integration approach such as web services.