• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 504
  • Last Modified:

How to use an external java class in JSP

Hi All,

How I can call the following java class in JSP then store command output in a variable and then diplay it as HTML table format?

---------------------------------------------------------------------------------------
C:\ >  java runcmd "dir"

 Volume in drive D is CD
 Volume Serial Number is DC6C-7455

Directory of D:\MY DATA FOLDER\SoftDvlpmnt\Java\classes

03/29/2005  04:20p      <DIR>          .
03/29/2005  04:20p      <DIR>          ..
03/29/2005  12:44p                 432 HelloWorldApp.class
03/29/2005  12:11p                 289 HelloWorldApp.java
               7 File(s)          8,070 bytes
               2 Dir(s)   479,826,944 bytes free
-----------------------------------------------------------------------------------------

Thanks.
0
myrizvi
Asked:
myrizvi
  • 8
  • 5
  • 4
  • +2
3 Solutions
 
orhanbabaCommented:
put your class in  your root directory "WEB-INF\classes"
0
 
KuldeepchaturvediCommented:
you can use it in to ways.. either you can make it a bean and use it in jsp..

or you can use it as a normal java class ( just like the way you use a String object in jsp)..
the class needs to be in the class path, thats it
0
 
myrizviAuthor Commented:
Thanks.

Thats OK, I will put this class there BUT what I should write in JSP to :

1) Include this class
2) Execute the "runcmd" function with a parameter.  like   runcmd "dir"
3) Store the output of RUNCMD into a string variable.


Thanks again.



0
[Webinar] Improve your customer journey

A positive customer journey is important in attracting and retaining business. To improve this experience, you can use Google Maps APIs to increase checkout conversions, boost user engagement, and optimize order fulfillment. Learn how in this webinar presented by Dito.

 
KuldeepchaturvediCommented:
runcmd is a class not a function ( thats what it looks like from the command line that you showed at the top..

so you should be able to do a
runcmd.main("dir"); in your jsp to make it run..
the problem is that this method will return its output to the console..

This means that you will have to modify the runcmd class to return the string instead of printing it on the console..
0
 
myrizviAuthor Commented:
Thanks for your continued support.

Now the runwincmd.class in "\Tomcat 4.1\webapps\WEB-INF\classes"  folder.
 
What I typed in test2.jsp :
--------------------------------------------------------------
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="java" import="java.io.*, java.util.*" %>

<%
runwincmd.main("dir");
%>
--------------------------------------------------------------


WHEN I run it from the browser I get :



type Exception report

message

description The server encountered an internal error () that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: 4 in the jsp file: /test2.jsp

Generated servlet error:
    [javac] Compiling 1 source file

D:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\helloworld\test2_jsp.java:47: cannot resolve symbol
symbol  : variable runwincmd
location: class org.apache.jsp.test2_jsp
runwincmd.main("dir");
^
1 error
---------------------------------------------------------------------------------------------------------------

0
 
koppchaCommented:
If your purpose is to runa command on the underlying operating system and print on the JSP.The use Runtime.exec() method to run the command you can collect the output and print it on JSP
This is the sample code .

ArrayList results = new ArrayList();
Process process = runTime.exec (command);//command  is an array of strings basically the whole
                                                                 //command
InputStream inputStream = process.getInputStream();
InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
 while ( (line = bufferedReader.readLine()) != null ){
results.add(line); //finally results contain the output
}
exitVal = process.waitFor();
System.out.println ("Process exitValue:  " + exitVal );
}
catch (Throwable t)
{
t.printStackTrace();
}
0
 
KuldeepchaturvediCommented:
Hmm....
change your jsp to

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="java" import="java.io.*, java.util.*" %>
<%
runwuncmd test = new runwincmd();
test.main("dir");
%>
see if this works.. if not then the jsp is not finding the class that you are looking for...
what koppcha is suggesting above is to basically expand your class and the put the code in the jsp directly.. that will also work but its not the reuse of the class
0
 
koppchaCommented:
Revised version of my eariler solution
ArrayList results = new ArrayList();
try
{
Runtime runTime = Runtime.getRuntime();
}
Process process = runTime.exec (command);//command  is an array of strings basically the whole
                                                                 //command
InputStream inputStream = process.getInputStream();
InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
 while ( (line = bufferedReader.readLine()) != null ){
results.add(line); //finally results contain the output
}
int exitVal = process.waitFor();
System.out.println ("Process exitValue:  " + exitVal );
}
catch (Throwable t)
{
t.printStackTrace();
}
0
 
myrizviAuthor Commented:
Hi Koppcha,

The above code is giving a blank WEB page. I tries "dir" as a command.

Dont know what is wrong.

Hi Kuldeepchaturvedi ,

I tried a lot but JSP is still not able to find the that CLASS.


Thanks to all of you.
0
 
koppchaCommented:
>The above code is giving a blank WEB page. I tries "dir" as a command
  It is supposed to take dir as a command .Is this what you did ?
<%
String cmd[] = new String[3];
cmd[0] = "cmd.exe";
cmd[1]="\c";
cmd[2]="dir *.txt ";
ArrayList results = new ArrayList();
try
{
Runtime runTime = Runtime.getRuntime();
}
Process process = runTime.exec (cmd);      
InputStream inputStream = process.getInputStream();
InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
 while ( (line = bufferedReader.readLine()) != null ){
results.add(line); //finally results contain the output
}
int exitVal = process.waitFor();
System.out.println ("Process exitValue:  " + exitVal );
}
catch (Throwable t)
{
t.printStackTrace();
}
Iterator resultIterator = new results.Iterator();
while(resultIterator.hasNext()){
String line = (String)resultIterator.next();
%>
Directory:<%= line %>
<%
}
%>

Let me know what happened?


0
 
KuldeepchaturvediCommented:
you will have to print the results on the screen which is sitting in the Arraylist as of now..

int exitVal = process.waitFor();
System.out.println ("Process exitValue:  " + exitVal );
for(int i=0;i<results.size();i++
out.println(results.get(i));
0
 
KuldeepchaturvediCommented:
ooops... bad timing....:-)
0
 
vijaydograCommented:
What you can do is we can modify a bit of Koppcha program
Instead of having
ArrayList results = new ArrayList();
we can have
StringBuffer sb = new StringBuffer();
 and in place of
results.add(line); //finally results contain the output
we can have
sb.append("\n"+line);
so that you can output it in the jsp using

out.println("Output : "+sb.toString());
or <%=sb.toString()%>
0
 
myrizviAuthor Commented:
Hi koppcha,

When I tried your code after some correction:

-------------------------------------------------------------------
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="java" import="java.io.*, java.util.*" %>

<%
String cmd[] = new String[3];
cmd[0] = "cmd.exe";
cmd[1]="/c";
cmd[2]="dir *.txt ";
ArrayList results = new ArrayList();
try
{
Runtime runTime = Runtime.getRuntime();
Process process = runTime.exec (cmd);      
InputStream inputStream = process.getInputStream();
InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = null;
while ( (line = bufferedReader.readLine()) != null ){
      results.add(line); //finally results contain the output
}
int exitVal = process.waitFor();
System.out.println ("Process exitValue:  " + exitVal );
}
catch (Throwable t)
{
      t.printStackTrace();
}
Iterator resultIterator = new results.Iterator();
while(resultIterator.hasNext()){
String line = (String)resultIterator.next();
%>
Directory:<%= line %>
<%
}
%>

------------------------------------------------------------------

This is the error :

-----------------------------------------------------------------

exception

org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: 4 in the jsp file: /test4.jsp

Generated servlet error:
    [javac] Compiling 1 source file

D:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\helloworld\test4_jsp.java:70: package results does not exist
Iterator resultIterator = new results.Iterator();
                                     ^
1 error

---------------------------------------------------------------------------------


0
 
myrizviAuthor Commented:
I am increasing the point value because you guys deserve it.

Thanks to all of you.

I am willing  to get this problem solved.
0
 
vijaydograCommented:
Just modify the code:


<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="java" import="java.io.*, java.util.*" %>

<%
String cmd[] = new String[3];
cmd[0] = "cmd.exe";
cmd[1]="/c";
cmd[2]="dir *.txt ";
StringBuffer sb = new StringBuffer();
try
{
 Runtime runTime = Runtime.getRuntime();
 Process process = runTime.exec (cmd);      
 InputStream inputStream = process.getInputStream();
 InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
 BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
 String line = null;
 while ( (line = bufferedReader.readLine()) != null )
 {
     sb.append(line); //finally results contain the output
 }
 int exitVal = process.waitFor();
 System.out.println ("Process exitValue:  " + exitVal );
}
catch (Throwable t)
{
      t.printStackTrace();
}

%>
Directory:<%=sb.toString()%>
 

Should work now
0
 
myrizviAuthor Commented:
Hi vijaydogra,

I tried you code as well:

-------------------------  CODE START ---------------------------------

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="java" import="java.io.*, java.util.*" %>

<%
try
{
  String cmd[] = new String[3];
  cmd[0] = "cmd.exe";
  cmd[1]="/c";
  cmd[2]="dir";
  StringBuffer sb = new StringBuffer();

  Runtime runTime = Runtime.getRuntime();
  Process process = runTime.exec(cmd);      
  InputStream inputStream = process.getInputStream();
  InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  String line = null;
  while ( (line = bufferedReader.readLine()) != null ){
        sb.append("\n"+line); //finally results contain the output
  }
  int exitVal = process.waitFor();
  System.out.println ("Process exitValue:  " + exitVal );
}catch (Throwable t)
{
  t.printStackTrace();
}
out.println("Output : " + sb.toString());
%>

---------------------------------------- CODE END -------------------------------------

---------------------------------------- RESUT START --------------------------------

exception

org.apache.jasper.JasperException: Unable to compile class for JSP

An error occurred at line: 4 in the jsp file: /test5.jsp

Generated servlet error:
    [javac] Compiling 1 source file

D:\Program Files\Apache Group\Tomcat 4.1\work\Standalone\localhost\helloworld\test5_jsp.java:70: cannot resolve symbol
symbol  : variable sb
location: class org.apache.jsp.test5_jsp
out.println("Output : " + sb.toString());
                          ^
1 error

--------------------------------------------------- RESULT END ----------------------------------


DO I NEED TO IMPORT SOME OTHER PACKAGE ?


Thanks.
0
 
vijaydograCommented:
Sorry a bit mistake:

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="java" import="java.io.*, java.util.*" %>

<%
 StringBuffer sb = new StringBuffer();

try
{
  String cmd[] = new String[3];
  cmd[0] = "cmd.exe";
  cmd[1]="/c";
  cmd[2]="dir";
 
  Runtime runTime = Runtime.getRuntime();
  Process process = runTime.exec(cmd);      
  InputStream inputStream = process.getInputStream();
  InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  String line = null;
  while ( (line = bufferedReader.readLine()) != null ){
        sb.append("\n"+line); //finally results contain the output
  }
  int exitVal = process.waitFor();
  System.out.println ("Process exitValue:  " + exitVal );
}catch (Throwable t)
{
  t.printStackTrace();
}
out.println("Output : " + sb.toString());
%>



Try this now
0
 
myrizviAuthor Commented:
Hi Kuldeepchaturvedi,

After your suggested change the OUTPUT IS NOW APPEARING ON SCREEN but without new line :

---------------------------------------------- CODE START ----------------------------------------------

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>
<%@ page language="java" import="java.io.*, java.util.*" %>

<%
try
{
  String cmd[] = new String[3];
  cmd[0] = "cmd.exe";
  cmd[1]="/c";
  cmd[2]="dir b*";
  ArrayList results = new ArrayList();
 
  Runtime runTime = Runtime.getRuntime();
  Process process = runTime.exec(cmd);      
  InputStream inputStream = process.getInputStream();
  InputStreamReader   inputStreamReader = new InputStreamReader (inputStream);
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  String line = null;
  while ( (line = bufferedReader.readLine()) != null ){
        results.add(line); //finally results contain the output
  }
  int exitVal = process.waitFor();
  System.out.println ("Process exitValue:  " + exitVal );
  for(int i=0;i<results.size();i++)
     out.println(results.get(i) + "\n");
}catch (Throwable t)
{
  t.printStackTrace();
}
%>

----------------------------------------------------- CODE END --------------------------------------------------

----------------------------------------------------- RESULT START --------------------------------------------

Volume in drive C has no label. Volume Serial Number is C83B-63FF Directory of C:\WINNT\system32 12/07/1999 03:00p 1,012 basenote.cov 06/18/2004 02:05a 46,352 BASESRV.DLL 06/19/2003 12:05p 20,752 batmeter.dll 12/07/1999 03:00p 6,416 batt.dll 12/07/1999 03:00p 28,420 bios1.rom 12/07/1999 03:00p 8,191 bios4.rom 12/07/1999 03:00p 4,880 bootok.exe 12/07/1999 03:00p 10,784 bootvid.dll 12/07/1999 03:00p 5,392 bootvrfy.exe 12/07/1999 03:00p 22,984 bopomofo.uce 12/07/1999 03:00p 36,112 br549.dll 08/29/2002 07:14a 62,976 browselc.dll 03/24/2004 05:17a 69,904 browser.dll 12/07/2004 05:41p 1,017,856 BROWSEUI.DLL 08/29/2002 07:14a 71,680 browsewm.dll 15 File(s) 1,413,711 bytes 0 Dir(s) 93,990,912 bytes free

---------------------------------------------------- RESULT END ----------------------------------------------------


Thanks a lot.
0
 
myrizviAuthor Commented:
Hi vijaydogra,

Y a now its working but giving output as a one single line like above. I think we have to put newline somewhere.

Thanks anyway.

It was great working with you guys.
0
 
koppchaCommented:
Sorry i didn't see your comments in time.Thanks for the points.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 8
  • 5
  • 4
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now