Problem compiling a simple java file

Hi,
When I try to compile the following simple java file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HowdyServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<html>");
out.println("<body>");
out.println("<center><h1>Hi</h1></center>");
out.println("</body>");
out.println("</html>");
at the command prompt as follows
C:\Shared\CBT\Java 2 JSP and Java Servlets\03\servlet1>javac -classpath
"C:\Program Files\Java\j2re1.4.2_03\lib\ext\QTJava.zip" *.java
Or
C:\Shared\CBT\Java 2 JSP and Java Servlets\03\servlet1>javac *.java
Or
C:\Shared\CBT\Java 2 JSP and Java Servlets\03\servlet1>javac HowdyServlet.java
I get the following errors and I cannot compile this java file -
HowdyServlet.java:2: package javax.servlet does not exist
import javax.servlet.*;
^
HowdyServlet.java:3: package javax.servlet.http does not exist
import javax.servlet.http.*;
^
HowdyServlet.java:5: cannot find symbol
symbol: class HttpServlet
public class HowdyServlet extends HttpServlet {
^
HowdyServlet.java:6: cannot find symbol
symbol : class HttpServletRequest
location: class HowdyServlet
public void doGet(HttpServletRequest request,
^
HowdyServlet.java:7: cannot find symbol
symbol : class HttpServletResponse
location: class HowdyServlet
HttpServletResponse response)
^
HowdyServlet.java:8: cannot find symbol
symbol : class ServletException
location: class HowdyServlet
throws IOException, ServletException {
^
6 errors
I have installed the latest JEE 5 SDK on Win XP Home. I have the following variable set as follows,
CLASSPATH = .;C:\Program Files\Java\j2re1.4.2_03\lib\ext\QTJava.zip
PATH = C:\Sun\AppServer\jdk\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;C:\Program Files\Microsoft SQL Server\80\Tools\BINN;C:\Program Files\QuickTime\QTSystem;C:\Sun\AppServer\lib\ant\bin
ANT_HOME = C:\Sun\AppServer\lib\ant
I have spent hours scratching my head but don?t have a clue. I was wondering if you have any idea as why I might be getting these errors.
Thank you for your time.
Green

Hello, did you read the answers?
You have to put j2ee.jar or servlet-api.jar in your classpath. Those JAR files are included in the Java EE package somewhere. Remove the QTJava.zip junk from the classpath.
If you don't know what the classpath is and how to set it, read this:
Setting the class path
How Classes are Found
And I'll repeat what the others say: if you are very new to Java, then Java EE will probably be way over your head. First learn the language and the standard API. If you understand that well, start with Java EE. Or do you already know what servlets are, and that you need a servlet container to run them, and how to deploy them etc.?

Similar Messages

  • How to test the simple .java file in cactus

    dear friends,
    i have use the junit first time .And i am working in weblogic8.1 so i have use cactus .But i face the problem to use it.
    1. how to test the simple .java file in cactus.
    2.how to run the cactus in weblogic 8.1.

    Hi,
    It is because the converter works on byte code and it only supports a subset of the Java language (see the JC specifications). It is kind of like compiling you code on Java 6 and trying to run it on Java 5. The JCDK outlines the required compiler version.
    Cheers,
    Shane

  • What's wrong with this simple java file

    I am learning java input methods. When I tried to compile the below simple java file, there were two errors.
    import java.io.*;
    public class MainClass {
       public static void main(String[] args)  {
        Console console = System.console();
        String user = console.readLine("user: ");
        System.out.println(user);
    }The compiler errors:
    h:\java\MainClass.java:5: cannot resolve symbol
    symbol : class Console
    location: class MainClass
    Console console = System.console();
    ^
    h:\java\MainClass.java:5: cannot resolve symbol
    symbol : method console ()
    location: class java.lang.System
    Console console = System.console();
    ^
    2 errors
    Could anyone take a look and shed some lights on this?

    I have changed to "import java.io.Console;" but this below errors:
    h:\java\MainClass.java:1: cannot resolve symbol
    symbol : class Console
    location: package io
    import java.io.Console;
    ^
    h:\java\MainClass.java:5: cannot resolve symbol
    symbol : class Console
    location: class MainClass
    Console console = System.console();
    ^
    h:\java\MainClass.java:5: cannot resolve symbol
    symbol : method console ()
    location: class java.lang.System
    Console console = System.console();
    ^
    3 errors
    -----------

  • How to compile and run java files on a mac using command line?

    can someone tell me or link me to some article on how to compile and run java files from command line on a mac? I have mac OS X leopard

    What do you mean by "where to put them" ? What do you want to put anywhere ?
    Have you read Peter's comment in brackets ? Perhaps you have a classpath problem ?
    Edited by: Michael_Knight on Aug 31, 2008 4:23 AM

  • How to compile dunamically genrated java files through java program?

    Hi, I have a requirement where i generate java files from WSDL dynamically using wsdl2java jaxbri. I need to compile these files dynamically on the fly and jar it. Everything should happen through java program. Bcos everything is dynamic here, no information is known (like dir, file names ...) until the runtime. Everything is user fed.
    the directories may contain other directories with java files. its recursive
    i tried com.sun.tools.javac.Main.. but either its not scaling to my needs or i donno how to wok with this.
    is there any option to compile the java files as they are created thru JAXBRI (wsdl2java)?
    any help is appreciated..
    -s

    my requirement is :
    i create java files from wsdl2java (axis).. i need to compile all the java files.. directories with in the directories (recursive)...
    as bcos the the java files have inter-dependencies they have to be compiled as a bunch something like (java *.java). I donno how to do this in javac.Main tool
    Once all these files are compiled i need to create a jar out of them
    Any help is appreciated!

  • Error in compilation satge of java files

    Hi all
    Whenever i m trying to compile java files i m getting this error .I have no idea how to go about fixing this issue. Can any one help me out with this.
    Error occurred during initialization of VM
    Could not reserve enough space for object heap

    Well i could go ahead and solve the issue by bringing down the memory allocation at the minimum and maximum level during the compilation stage.
    I got the tip from the forum itself where a similar problem had been reported and there this tip was provided.
    Earlier in my case i was allocating 1GB of memory for compilation but due to some issue that much space was not being detected on the server. When i pruned that down to 512mb the compilation went ahead without any trouble.
    Thanks kelly for geting in involved in geting to know the issue .

  • Problem while executing simple java program

    Hi
    while trying to execute a simple java program,i am getting the following exception...
    please help me in this
    java program :import java.util.*;
    import java.util.logging.*;
    public class Jump implements Runnable{
        Hashtable activeQueues = new Hashtable();
        String dbURL, dbuser, dbpasswd, loggerDir;   
        int idleSleep;
        static Logger logger = Logger.getAnonymousLogger();      
        Thread myThread = null;
        JumpQueueManager manager = null;
        private final static String VERSION = "2.92";
          public Jump(String jdbcURL, String user, String pwd, int idleSleep, String logDir) {
            dbURL = jdbcURL;
            dbuser = user;
            dbpasswd = pwd;
            this.idleSleep = idleSleep;
            manager = new JumpQueueManager(dbURL, dbuser, dbpasswd);
            loggerDir = logDir;
            //preparing logger
            prepareLogger();
          private void prepareLogger(){      
            Handler hndl = new pl.com.sony.utils.SimpleLoggerHandler();
            try{
                String logFilePattern = loggerDir + java.io.File.separator + "jumplog%g.log";
                Handler filehndl = new java.util.logging.FileHandler(logFilePattern, JumpConstants.MAX_LOG_SIZE, JumpConstants.MAX_LOG_FILE_NUM);
                filehndl.setEncoding("UTF-8");
                filehndl.setLevel(Level.INFO);
                logger.addHandler(filehndl);
            catch(Exception e){
            logger.setLevel(Level.ALL);
            logger.setUseParentHandlers(false);
            logger.addHandler(hndl);
            logger.setLevel(Level.FINE);
            logger.info("LOGGING FACILITY IS READY !");
          private void processTask(QueueTask task){
            JumpProcessor proc = JumpProcessorGenerator.getProcessor(task);       
            if(proc==null){
                logger.severe("Unknown task type: " + task.getType());           
                return;
            proc.setJumpThread(myThread);
            proc.setLogger(logger);       
            proc.setJumpRef(this);
            task.setProcStart(new java.util.Date());
            setExecution(task, true);       
            new Thread(proc).start();       
         private void processQueue(){       
            //Endles loop for processing tasks from queue       
            QueueTask task = null;
            while(true){
                    try{
                        //null argument means: take first free, no matters which queue
                        do{
                            task = manager.getTask(activeQueues);
                            if(task!=null)
                                processTask(task);               
                        while(task!=null);
                    catch(Exception e){
                        logger.severe(e.getMessage());
                logger.fine("-------->Sleeping for " + idleSleep + " minutes...hzzzzzz (Active queues:"+ activeQueues.size()+")");
                try{
                    if(!myThread.interrupted())
                        myThread.sleep(60*1000*idleSleep);
                catch(InterruptedException e){
                    logger.fine("-------->Wakeing up !!!");
            }//while       
        public void setMyThread(Thread t){
            myThread = t;
        /** This method is only used to start Jump as a separate thread this is
         *usefull to allow jump to access its own thread to sleep wait and synchronize
         *If you just start ProcessQueue from main method it is not possible to
         *use methods like Thread.sleep becouse object is not owner of current thread.
        public void run() {
            processQueue();
        /** This is just another facade to hide database access from another classes*/
        public void updateOraTaskStatus(QueueTask task, boolean success){
            try{         
                manager.updateOraTaskStatus(task, success);
            catch(Exception e){
                logger.severe("Cannot update status of task table for task:" + task.getID() +  "\nReason: " + e.getMessage());       
        /** This is facade to JumpQueueManager method with same name to hide
         *existance of database and SQLExceptions from processor classes
         *Processor class calls this method to execute stored proc and it doesn't
         *take care about any SQL related issues including exceptions
        public void executeStoredProc(String proc) throws Exception{
            try{
                manager.executeStoredProc(proc);
            catch(Exception e){
                //logger.severe("Cannot execute stored procedure:"+ proc + "\nReason: " + e.getMessage());       
                throw e;
         *This method is only to hide QueueManager object from access from JumpProcessors
         *It handles exceptions and datbase connecting/disconnecting and is called from
         *JumpProceesor thread.
        public  void updateTaskStatus(int taskID, int status){       
            try{
                manager.updateTaskStatus(taskID, status);
            catch(Exception e){
                logger.severe("Cannot update status of task: " + taskID + " to " + status + "\nReason: " + e.getMessage());
        public java.sql.Connection getDBConnection(){
            try{
                return manager.getNewConnection();
            catch(Exception e){
                logger.severe("Cannot acquire new database connection: " + e.getMessage());
                return null;
        protected synchronized void setExecution(QueueTask task, boolean active){
            if(active){
                activeQueues.put(new Integer(task.getQueueNum()), JumpConstants.TH_STAT_BUSY);
            else{
                activeQueues.remove(new Integer(task.getQueueNum()));
        public static void main(String[] args){
                 try{
             System.out.println("The length-->"+args.length);
            System.out.println("It's " + new java.util.Date() + " now, have a good time.");
            if(args.length<5){
                System.out.println("More parameters needed:");
                System.out.println("1 - JDBC strign, 2 - DB User, 3 - DB Password, 4 - sleeping time (minutes), 5 - log file dir");
                return;
            Jump jump = new Jump(args[0], args[1], args[2], Integer.parseInt(args[3]), args[4]);
            Thread t1= new Thread(jump);
            jump.setMyThread(t1);      
            t1.start();}
                 catch(Exception e){
                      e.printStackTrace();
    } The exception i am getting is
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe
    Exception in thread "main" ERROR: JDWP Unable to get JNI 1.2 environment, jvm->GetEnv() return code = -2
    JDWP exit error AGENT_ERROR_NO_JNI_ENV(183):  [../../../src/share/back/util.c:820] Please help me.....
    Thanks in advance.....sathya

    I am not willing to wade through the code, but this portion makes me conjecture your using an Oracle connect string instead of a class name.
    java.lang.NoClassDefFoundError: jdbc:oracle:thin:@localhost:1521:xe

  • Compiling / Running a Java file in JSP

    Hi,
    ok, I have a jsp page, which we will call page 1. Once I go to that page, I all I want it to do is compile a certain file.java, and then run the file.java. The user doesn't actually know that this is going on in the background. Page 1 automatically redirects the user to page 2 (also a jsp page).
    The java program that I created (that was previously compiled and ran) creates a special javascript file. After running the file.java in page #1, the java file creates a javascript file that will be used in page 2 to display a tree node (group of information).
    so, right now, I'm trying to figure out how to write the jsp code that will tell how to compile and run a java file. I was thinking about using javabeans before, but I think you HAVE to actually display the contents of the java file into the jsp (I think). Anyhow, thanks for the help!

    sorry about being ambiguous before. What I mean by
    running a java file was that I already created a java
    file. I don't want to hava my java statements inside
    the jsp file. I just want the jsp file have a command
    in it that would call a java file, tell the java file
    to compile and run. All the jsp file would do
    (hopefully) is just give commands for a seperate java
    file to compile and run. Thanks again for any help!Ok, so this other java file has some entry-point method, like main(), right? So call it...
    <%
    YourJavaClass.main(appropriateArgumentsGoHere);
    %>
    or better yet, it's an object you can use:
    <%
    YourJavaClass x = new YourJavaClass();
    x.callSomeMethodHere(withAppropriateArgumentsHere);
    x.callAnotherMethodMaybe();
    %>
    You don't need the jsp file to "compile" this java file, you'd already have compiled it beforehand, and it's class bytecode needs to be in your classpath (on the server side) of course.

  • Is it possible to compile & run other java files from one file

    hi friends,
    i need to run 2,3 java sourse files(first.java,second.java etc) from one file.i tried the Runtime.getRunTime().exec( cmd) but here cmd must be a executable file
    what is need is to compile and run the files (first.java,second.java) from one other source file
    pls. help me in this matter,
    with warm regards,
    Vishal

    Sure:public class Test {
       public static void main(String[] args) {
          try {
             Runtime r = Runtime.getRuntime();
             r.exec("javac Test2.java");
          } catch (Exception e) {
    public class Test2 {
       public static void main(String[] args) {
          System.out.println("Hello World!");
    }Note that Test and Test2 are in two seperate files.

  • Problem accessing variables from java file to JSP page

    Hello Everyone,
    I have small problem accessing my method variables from my java bean file to a JSP page. can some please take a look and tell me why I can't populate my JSP page, I've been trying all day to get this done!!!
    This is my Java file
    package dev;
    import java.io.*;
    import java.util.*;
    public class RoundDetail2
    public String string_gameID;
    public int string_card1;
    public String readDetail_topLayer;
    public static final String SUITS[] = {" ", "Clubs", "Hearts", "Spades", "Diamonds", "Joker", "FaceDown"};
    public static final String VALUES[] = {"Joker ","Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
    public static final String SuitVALUES[] = {" ","1","2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14"};
    public RoundDetail2() throws FileNotFoundException
    DataInputStream inFile=
                 new DataInputStream(
                    new BufferedInputStream(
                   new FileInputStream("C:/apps/jakarta-tomcat-4.0.6/webapps/ROOT/WEB-INF/classes/dev/Data_452SY2.txt")));
    try { 
                 while((readDetail_topLayer = inFile.readLine()) != null)
              StringTokenizer tokenizer_topLayer = new StringTokenizer(readDetail_topLayer,"\t", true);
                   while  (tokenizer_topLayer.hasMoreTokens())
                        string_gameID = tokenizer_topLayer.nextToken();
         catch(IOException e)
                    System.out.println(e.getMessage());
         Thanks KT

    ......How are you declaring the class in your JSP? ... are you instantiating it as a bean using the useBean tag, or just instantiating it in your code like normal.
    Maybe you could post the relevant JSP code too?
    Hello again,
    Only the last string is populating after the file has be tokenized. What I'll like to accomplish is passing the very first string in the file. I did not get too far in the JSP file setup because the code is still in it's testing stage, but any help will be highly appreciated.
    Here is the JSP code
    <%@page import="dev.*" %>
    <%@page session="true" language="java" import="java.io.*" %>
    <jsp:useBean id="wagerhist" scope="request" class="dev.RoundDetail2" />
    <html>
    <head>
    <title>Round Detail</title>
    <body>
      <table width="530" bordercolor="#000000" valign="top">
        <tr>
              <td align="left"  width="19%">Game ID<%=wagerhist.string_gameID%></td>
              <td align="left"  width="30%">  </td>
              <td align="left"  width="20%">card1</td>
              <td align="left"  width="31%">  </td>
            </tr>
      </table>
    </body>
    </html>

  • Error: code too large for try statement, when compiling a big java file.

    Hi,
    I have a big java file ( around 16000 lines). When compiling it, I got following error message:
    MyMain.java:15233: code too large for try statement
    } catch ( Throwable t ) {
    In MyMain.java, I just repeat following statements about 1000 times.
    try {
    if ( year >= 2002 ) {
    System.out.println( "year: Evaluation version is not valid" );
    } else {
    System.out.println( "year: Evaluation version is still valid" );
    } catch ( Throwable t ) {
    if ( year >= 2002 ) {
    System.out.println( "year: Evaluation version is not valid" );
    } else {
    System.out.println( "year: Evaluation version is still valid" );
    I tried 1.3 and 1.4 javac compiler, there was some error.
    How to make compiler to compile this code?
    Thanks,

    Hi,
    I have a big java file ( around 16000 lines). When
    compiling it, I got following error message:
    MyMain.java:15233: code too large for try statement
    } catch ( Throwable t ) {
    I tried 1.3 and 1.4 javac compiler, there was some
    error.
    How to make compiler to compile this code?
    You don't. Each method has an absolute limit on the number of byte codes. You have reached that limit. The limit is part of the specification and JVMs will refuse to run classes that exceed the limit. So even if you could compile it, it wouldn't run.
    It is quite common for code generators to generate large monolithic blocks of code. Presumably this is how you got to this spot. Modify the code generator to break it into smaller blocks.
    If you did it manually then you did it wrong. And you will have to manually break it into smaller blocks. (And re-examine your design since it is probably wrong.)

  • Compiling a single .java file

    Hi,
    is it possible to compile a single java class without having to rebuild the complete
    application ? If this is not a feature is it going to be available in SP3 ?
    Thanks
    Mark

    Just put your java classes in a Java project under your application and
    then compile only that project.
    /Steen
    Mark wrote:
    Hi,
    is it possible to compile a single java class without having to rebuild the complete
    application ? If this is not a feature is it going to be available in SP3 ?
    Thanks
    Mark

  • Compiling all possible java files

    Hi,
    I have a project in which not all files/packages compiles but a set of packages compiles always.
    Say set of classes which might not compile as 'A' and set of classes which will always compile as 'B'
    On frequent basis i need to get update. And I am only concerned about set 'B' but when i compiles my project using ant
    compilation fails as 'A' compilation fails and because of that it doesn't go further to compile 'B'.
    So how to get eclipse like functionality to compile all possible files?
    what i have is
    ================================
    <javac debug="${debug}" deprecation="${deprication}"
                   optimize="${optimize}" destdir="${build.home}/WEB-INF/classes"
                   listfiles="${listfiles}" target="${jdk.compliance}"
                   verbose="${verbose}" srcdir="${src.home}"
                   memoryMaximumSize="512M" fork="true"
                   source="${src.compliance}">
                   <classpath refid="compile.path"/>
                   <include name="**/*.java"/>
                   <exclude name="HBM/**"/>
                   <compilerarg value="-Xlint:unchecked"/>
    ===================================
    I do not wish to write all the classes specifically that compiles in ant script.
    Thanks in Advance

    Try with failonerror option in your javac.
            <javac debug="${debug}" deprecation="${deprication}" optimize="${optimize}" destdir="${build.home}/WEB-INF/classes" listfiles="${listfiles}" target="${jdk.compliance}" verbose="${verbose}" srcdir="${src.home}" memoryMaximumSize="512M" fork="true" source="${src.compliance}" {color:#0000ff}*failonerror="false"*{color}>
                <classpath refid="compile.path" />
                <include name="*/.java" />
                <exclude name="HBM/**" />
                <compilerarg value="-Xlint:unchecked" />Regards,
    Prashanth.

  • Problem with getNodeValue() - simple Java XPath question

    I am trying to extract the node values from a XML file:
    <root>
      <frame>
         <boxes>
           <box>
              <spec>22</spec>
              <spec>2222</spec>
           </box>
           <box>
              <spec id="BA" value="short"/>
              <spec id="BB" value="thin"/>
              <spec id="BC" value="black"/>
              <spec id="BD" value="full"/>
              <spec id="BE" value="7"/>
              <spec id="BF" value="deactive"/>
           </box>                
         </boxes>
         <circles>
           <circle id="CA" value="blue"/>
           <circle id="CB" value="green"/>
         </circles>
      </frame>
    </root>I use this code:
             XPathFactory factory = XPathFactory.newInstance();
             XPath xpath = factory.newXPath();
             XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec");            
             Object result = xPathExpression.evaluate(doc, XPathConstants.NODESET);
             NodeList nodes = (NodeList) result;
             for (int i = 0; i < nodes.getLength(); i++) {
                 System.out.println(nodes.item(i).getNodeValue());
             }But only:
    null
    null
    null
    null
    null
    null
    null
    null
    get printed. I would have assumed:
    22
    2222
    null
    null
    null
    null
    null
    null
    since the two first spec nodes contains the above numbers. Any ideas?

    change this:
    XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec");to this:
    XPathExpression xPathExpression = xpath.compile("/root/frame/boxes/box/spec/text()");Need to xpath all the way down to the text of the node.
    You could use
    System.out.println(nodes.item(i).getTextContent());with your current xpath but if the spec node has children, these will also be included in the output.

  • Problem in editing a java file in Webdynpro

    Hi All,
    I have created a new dc and checked it in the DTR. Now, when I sync it from DTR, and again try to change the implementation of the view, it does not let me do it. I have to go to DTR>inactive dcs-> and explicitly edit the file. I am able to change the layout of the view but not the code.
    Please guide me to resolve this issue.
    Thanks

    Just check that ou haven't checkd-in the content of gen_wdp folder. If you have revert them.
    Second check: Insert values between //@begin and //@end tags in only. If you enter any where else, the code will be lost.
    Select the java implementation and open the navigator view. You see the file selected in the left bowser. Check that the file is writable by clicking on File->Go to Properties-> Info
    If it is writable change it to non-writable.
    Best Regards,
    Ashwani Kr Sharma

Maybe you are looking for