instantiating objects in servlets

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • davidr69
    New Member
    • Nov 2008
    • 2

    instantiating objects in servlets

    I am completely new to servlets. I have an extensive programming background (C, C++, assembler, PHP, python, javascript, others) and I am trying to get into servlet programming. I have done several jsp's and small java apps, and I have code that works both as a java app and as a jsp:

    Code:
    class foobar {
            int x = 0;
            public void foobar() { }
    }
    
    public class mytest {
            public static void main(String[] args) {
                    foobar blah = new foobar();
            }
    }
    No problem when I compile and run. Even as a jsp, it's not a problem:

    Code:
    <%
    class foobar {
            int x = 0;
            public void foobar() { }
    }
    
    foobar blah = new foobar();
    %>
    That also works perfectly fine. When I try to do it as a servlet, Tomcat complains:

    exception

    javax.servlet.S ervletException : Servlet execution threw an exception

    root cause

    java.lang.NoCla ssDefFoundError : foobar
    mytest.doGet(da tacenter_matrix .java:160)
    javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:690)
    javax.servlet.h ttp.HttpServlet .service(HttpSe rvlet.java:803)

    Code:
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    
    class foobar {
    	int x = 0;
    	public void foobar() { }
    }
    
    public class mytest extends HttpServlet {
    	public void doGet(HttpServletRequest req, HttpServletResponse res)
    					throws ServletException, IOException {
    
    		foobar blah = new foobar();
    	}
    }
    I searched the web all day yesterday and couldn't find why my object won't instantiate within my servlet. The servlet works so long as I don't try to instantiate a foobar object. Any idea?!?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Your servlet does want to instantiate the objects but it can't find the appropriate class(es). Check your documentation for your servlet container: it mentions where you are supposed to store your classes (stored in a jar or just a .class file).

    btw, a constructor doesn't have a return type; remove that 'void' type from your attempt of a constructor.

    kind regards,

    Jos

    Comment

    Working...