Solved

How to execute bat file from a servlet?

Posted on 2001-06-03
6
435 Views
Last Modified: 2013-11-24
hello,

 How do you execute a bat file from a servlet?

-Dsys
0
Comment
Question by:Dsys
  • 3
  • 2
6 Comments
 

Expert Comment

by:kamalindia
ID: 6151264
Use exec method of java.lang.Runtime class

Runtime r;

r=Runtime.getRuntime();

Process p;

p.exec("mybat.bat");

Regards

Raj
0
 

Author Comment

by:Dsys
ID: 6152116
import java.io.*;
import java.util.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ExeStop extends HttpServlet {
     Runtime r;
     r=Runtime.getRuntime();
     Process p;
     p.exec("stopserver.bat");
     //does this have to reside in the same folder?
}

errors:
ExeStop.java:12: <identifier> expected
        r=Runtime.getRuntime();
         ^
ExeStop.java:14: <identifier> expected
        p.exec("stopserver.bat");
              ^
ExeStop.java:12: cannot resolve symbol
symbol  : class r
location: class ExeStop
        r=Runtime.getRuntime();
        ^
ExeStop.java:14: cannot resolve symbol
symbol  : class exec
location: package p
        p.exec("stopserver.bat");
         ^
4 errors

0
 
LVL 3

Accepted Solution

by:
chrisos earned 20 total points
ID: 6152583
Dsys,

The following code will run a file from within a servlet, I think the problem you ran into was a result of not putting your code inside a static initialiser or a method :)

I'm sure you already know how to reject an answer, so my advice is to do it, to get more input on this question!

Kamalindia,

Do not propose an answer unless you know it is an answer for certain, for guidance use the following from the experts handbook:

Please propose an "Answer" only when you are sure it will solve the questioner's problem. It is difficult for experts to find questions in need of answers when members interested in only obtaining points have locked questions.

Regards,

Chrisos

/////////////////////////////////////////////////////

package com.wintermuteis;

import java.io.*;
import java.util.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class ExeStop extends HttpServlet {

     private static Exception error = null;

     public static boolean runBatch() {
          boolean result = false;
          try {
               Runtime r = Runtime.getRuntime();
               String base = System.getProperty("user.dir");
               //As you can see I am prefixing the user's working directory to the target file name
               String target = base+File.separator+"stopserver.bat";
               System.out.println("Target: "+target);
               Process p = r.exec(target);
               result = true;
          }
          catch( IOException ioe ) {
               ioe.printStackTrace();
               error = ioe;
          }
          return result;
     }

     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
          response.setContentType("text/html");
          OutputStream outStream = response.getOutputStream();
          OutputStreamWriter out = new OutputStreamWriter(outStream);

          out.write("<HTML>\n");
          out.write("<HEAD>\n");
          out.write("<TITLE>Test</TITLE>\n");
          out.write("</HEAD>\n");
          out.write("<BODY>\n");
          out.write("<H1>Result:</H1> <BR />\n");
          out.flush();


          String action = request.getParameter("action");
          if( action == null || action.length() == 0 ) {
               action = "none";
          }
          if( action.equals("stopserver") ) {
               if( runBatch() ) {
                    out.write("Server has been shut down\n");
               }
               else {
                    error.printStackTrace(new PrintStream(outStream));
               }
          }
          else if( action.equals("none") ) {
               out.write("No action\n");
          }

          out.write("<BR />\n");
          out.write("</BODY>\n");
          out.write("</HTML>\n");

          out.flush();
          out.close();
          outStream.close();
     }

}
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

Author Comment

by:Dsys
ID: 6154692
I am not very good with java please explain this part for me...

public static boolean runBatch() {
     boolean result = false;

     try {
              Runtime r = Runtime.getRuntime();
              //String base = System.getProperty("user.dir");
          String base = System.getProperty("C:/jsdk2.1");

              //As you can see I am prefixing the user's working directory to the target file name
              String target = base+File.separator+"stopserver.bat";
              System.out.println("Target: "+target);
              Process p = r.exec(target);
              result = true;
         }
         catch( IOException ioe ) {
              ioe.printStackTrace();
              error = ioe;
         }
         return result;
    }

When I run this servlet it does not execute the bat file to stop the app server? Don't I have to specify the file location?
0
 
LVL 3

Expert Comment

by:chrisos
ID: 6155121
Dsys,

The system property "user.dir" gets the working directory for the java virtual machine you are running the code from.

If you want to hard code the the directory just do the following:

String base = "C:\\jsdk2.1"

NOTE: Notice the double back slash, this is because this character is used to indocate an escape code, by doubling it you indicate that it is a literal.

File.separator is a constant that indicates the separateor used in paths to files on the current system:

/ for unix et al.
\ dor dos/windows et al.

Regards,

Chrisos.
0
 

Author Comment

by:Dsys
ID: 6155604
Thank you. I have to come up with a way to restart the app server once I take it down. Servlet wont be able to bring it back up if it cannot listen for it.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JUnit 4 @Before and @BeforeClass differences 3 60
javap bin 2 35
reverse digits of a number using for loop 5 45
throw exception 21 44
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question