Share this page 

Launch an external program, capture its output and display it in a JSPTag(s): Servlet/JSP


In this HowTo, the Windows utility NET is executed to get the members of a given group. The JSP captures the output and to display it as Web page.
<H1>Members of the <%=request.getParameter("group")%> group</H1>
<%

String cmdline = "net group " + request.getParameter("group") + " /domain";

out.println("<pre>");
    try {
     String line;
     Process p = Runtime.getRuntime().exec(cmdline);
     BufferedReader input =
       new BufferedReader
         (new InputStreamReader(p.getInputStream()));
     while ((line = input.readLine()) != null) {
       out.println(line);
       }
     input.close();
     }
    catch (Exception err) {
     err.printStackTrace();
     }
out.println("</pre>");
%>

The next example calls a VBSCRIPT to list the Windows groups for a specific user.

the VBS (listmembergroups.vbs)

Option Explicit
Dim objNetwork, strDomain, strUser, objUser, objGroup, strGroupMemberships

Set objUser = GetObject("WinNT://ssqvie/" & WScript.Arguments.item(0))
wscript.echo "<H2>" & objUser.Fullname & "</H2>"
For Each objGroup In objUser.Groups
    wscript.echo objGroup.Name
Next

The JSP (http://myserver.local/myapp/listgroups.jsp?user=scott)

<H1> User <%=request.getParameter("user")%></H1>
<%
String cmdline = "cscript.exe //NoLogo \\\\myscripts_dir\\listmembergroups.vbs " + request.getParameter("user") ;

out.println("<pre>");

String line;
java.util.ArrayList<String> list = new java.util.ArrayList<String>();
try {
     Process p = Runtime.getRuntime().exec(cmdline);
     BufferedReader input =
       new BufferedReader
         (new InputStreamReader(p.getInputStream(), "Cp850"));
     while ((line = input.readLine()) != null) {
       list.add(line);
     }
     input.close();
    }

    catch (Exception err) {
     out.println(err);
    }

    java.util.Collections.sort(list);
    for (String item:list) {
       out.println(item);
    }
out.println("</pre>");
%>

As always, special care must be taken if there is a risk that the called program can write something into stderr (then the process will hang forever).