?
Solved

How to use an external java class in JSP

Posted on 2005-03-29
21
Medium Priority
?
494 Views
Last Modified: 2010-04-01
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
Comment
Question by:myrizvi
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
  • 4
  • +2
21 Comments
 
LVL 4

Expert Comment

by:orhanbaba
ID: 13652497
put your class in  your root directory "WEB-INF\classes"
0
 
LVL 19

Accepted Solution

by:
Kuldeepchaturvedi earned 800 total points
ID: 13652651
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
 

Author Comment

by:myrizvi
ID: 13652790
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 13652828
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
 

Author Comment

by:myrizvi
ID: 13653017
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
 
LVL 8

Assisted Solution

by:koppcha
koppcha earned 800 total points
ID: 13653122
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
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 13653165
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
 
LVL 8

Expert Comment

by:koppcha
ID: 13653220
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
 

Author Comment

by:myrizvi
ID: 13654469
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
 
LVL 8

Expert Comment

by:koppcha
ID: 13654641
>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
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 13654654
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
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 13654660
ooops... bad timing....:-)
0
 
LVL 1

Assisted Solution

by:vijaydogra
vijaydogra earned 400 total points
ID: 13658239
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
 

Author Comment

by:myrizvi
ID: 13659715
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
 

Author Comment

by:myrizvi
ID: 13659721
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
 
LVL 1

Expert Comment

by:vijaydogra
ID: 13659733
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
 

Author Comment

by:myrizvi
ID: 13659735
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
 
LVL 1

Expert Comment

by:vijaydogra
ID: 13659752
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
 

Author Comment

by:myrizvi
ID: 13659787
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
 

Author Comment

by:myrizvi
ID: 13660914
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
 
LVL 8

Expert Comment

by:koppcha
ID: 13661499
Sorry i didn't see your comments in time.Thanks for the points.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

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

This is a fine trick which I've found useful many times, when you just don't want to accidentally run a batch script or the commands needs administrator rights.
We are witnesses that everyone is saying that our children shouldn't "play" with a technology because it is dangerous. This article is going to prove that they are wrong.
This is my first video review of Microsoft Bookings, I will be doing a part two with a bit more information, but wanted to get this out to you folks.
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses

762 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