How to run OS commands (Windows OS) from Java Web Applications (J2EE)


If you want to call OS specific commands inside a Java J2EE web application, you can use the following code.

By using this code, you can also get the output from the command console and use it for displaying or other purposes.

Here you can find the BatchFileExecuter class

package com.tunatore.batchoperations;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author tunatore
 */
public class BatchFileExecuter extends HttpServlet {
    protected void handleRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, InterruptedException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
BufferedReader bufferedReader = null;
Process process = null;
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet BatchFileExecuter</title>");
out.println("</head>");
out.println("<body><center><h1>Content</h1><table border=\"1\">");
//this is the directory which will be used as home directory for the command executing
File directory = new File("C:\\Program Files\\Java\\jdk1.6.0_27\\");
process = Runtime.getRuntime().exec("cmd /c dir", null ,directory);
//reading the InputStream using Buffered Reader
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String currentLine; //reading line by line the output from the command console
while ((currentLine = bufferedReader.readLine()) != null) {
//this piece of code is used for formating the InputStream getting from the command console
  out.println("<tr><td>"
  + currentLine.replace("<", "&lt;").replace(">", "&gt;")
+ "</td></tr>");
}
out.println("</table></center></body>");
out.println("</html>");
} finally {
bufferedReader.close();
//process.destroy();
out.close();
  }
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
try {
handleRequest(request, response);
} catch (InterruptedException ex) {
   Logger.getLogger(BatchFileExecuter.class.getName()).log(Level.SEVERE, null, ex);
}
}
 @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
try {
handleRequest(request, response);
} catch (InterruptedException ex) {
            Logger.getLogger(BatchFileExecuter.class.getName()).log(Level.SEVERE, null, ex);
}
}
}


You can call this class from a JSP file called index.jsp

<%--
    Document   : index
    Created on : 07-11-2011, 15:30:42
    Author     : tunatore
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JavaExecuteBatchWebProject</title>
    </head>
    <body>
        <h1>JavaExecuteBatchWebProject</h1>
        <i>(`cmd /c dir`)</i> command will be executed on the Server Machine </br></br>
        <i>C:\\Program Files\\Java\\jdk1.6.0_27\\</i> will be used for applying the command dir</br></br>
        The output of the command will be published on the browser  </br></br>
<a href="/JavaExecuteBatchWebProject/BatchFileExecuter">Run command on Windows OS</a>
   </body>
</html>

And lastly your web.xml file should like the following;

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <servlet>
        <servlet-name>BatchFileExecuter</servlet-name>
        <servlet-class>com.tunatore.batchoperations.BatchFileExecuter</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>BatchFileExecuter</servlet-name>
        <url-pattern>/BatchFileExecuter</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

Here you can see the outputs;

First index.jsp output

Second screen’s output

Download All Source

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s