Servlet instantiate an object

Hi all,
I wanted to know how a servlet will instantiate an object.Specifically,I want a servlet to instantiate a class/object with some JDBC code in it.
Kindly give an overview of this,any code samples would be really very beneficial.
Hoping to hear from you ASAP.
Thanks
AS

Like any other Java object. What follows is
semi-sorta-pseudo code:
public void doPost(signature next)
// Or whatever your JDBC class name is
DatabaseManager manager = null;
try
// Pass it whatever it needs to create the
eate the database connection
manager = new DatabaseManager();
// Now call whatever manager methods you
thods you want,
// passing whatever they need.
catch (Exception e)
// Might want to log, too
e.printStackTrace();
finally
// Close it out
manager.close();
}MODContinuing on the same thing.In my init method I have the following code
public void init() {
try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("Driver loaded successfully");
   }//close try
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}//close catch
}//close init() method Do I have to change the Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); and put it into a new class file or leave it as it is and proceed with the doPost method.
Hoping to hear from you.
Thanks in advance
AS

Similar Messages

  • How can the servlet engine create objects of interfaces?help

    hello,
    I have this basic fundamental query...when using servlets i noticed that so many methods in the HttpServlet class take as arguments objects of the type "Interface"..where as basic principle in java is u cant instantiate interfaces...interfaces r mere templates which u implement by ur own custom classes.
    For example the doGet method recieves from the servlet engine(servlet container) two arguments which r HttpServletResponse object and HttpServletRequest object..and u use these further to make use of the methods of the inmterfaces..which again is a mystery to me...why?
    here is why:-
    since HttpServletResponse and HttpServletRequest r interfaces..they cant be instantiated...and now that the sevlet engine provides objects of these interfaces...how come u r able to to use the methods of these interfaces...for r they not empty methods?..
    example how r u able to make the sendRedirect() method of HttpServletResponse interface work...is this method not an empty method?
    there r several interfaces...whose objects r being used and passed in this similar fashion....(for example there r many methods that return an enumeration...which is used as if it were an ordinary class that can be instantiated..and whose methods r non empty emthods)
    please help me resolve this mystery
    sheeba

    Don't call me "u". The word is "you". Likewise "are" and not "r".
    The servlet engine creates objects of concrete classes that implement those interfaces. If you want to find the names of those classes in your particular server, you could use for examplereq.getClass().getName()

  • How to instantiate an object in a JSP page???

    I want from a JSP page instantiate an object from a client class, for example, and call its methods; one of these methods return me a RecordSet.
    But I don't having success on it. What am I doing wrong??? What would I do??? Have anybody a code sample????
    Regards.

    Hi,
    There's the code that I'm using, they are divided in 3 parts, and I really don't know what is causing this error.
    ********** CLASS conn ******************
    * IT'S THE CLASS THAT DO THE CONNECTION
    * AND EXECUTE THE SQL QUERIES
    import java.sql.*;
    import java.io.*;
    public class conn {
      public static Connection conn;
      public static Statement stmt;
      public static void openConn() throws SQLException {
        DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
        conn = DriverManager.getConnection("jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.24.8)(PORT = 1521)))(CONNECT_DATA =(SERVICE_NAME = ora_aula)))", "grupo6", "grupo6");
        stmt = conn.createStatement();
      public boolean getConectionState() throws SQLException {
        if (conn.isClosed())
          return false;  
        else
          return true;
      public static void closeConn() throws SQLException {
        stmt.close();
        conn.close();
      public static void postSql(String command) throws SQLException {
        stmt.executeQuery(command);
        stmt.executeQuery("COMMIT");
      public ResultSet returnSql(String command) throws SQLException {
        return stmt.executeQuery(command);
    ********** CLASS materia ***************
    * IT'S THE CLASS THAT INSTANTIATE THE
    * conn CLASS AND PASS TO IT THE SQL
    * THAT WILL BE EXECUTED AND RETURN THE
    * RECORDSET
    import java.sql.*;
    public class materia{
       public Integer materia_code;
       public String  materia_description;
       private conn myConn = new conn();
       private ResultSet materia_data;  
       ResultSet showData(comandosql){
         try {
           myConn.openConn();
           ResultSet data = myConn.retornaSql(sql);
           myConn.closeConn();
           return data;
         catch (SQLException sqlexc) {
           System.out.print(sqlexc);
           return null;
    ********** jsp PAGE******************
    * IT'S THE PAGE THAT INSTANTIATE THE
    * materia CLASS AND EXECUTE THE
    * STATEMENT, AND WHERE THE ERROR
    * IS OCURRING
    <%@ page import="java.sql.*" %>
    <%@ page import="materia" %>
    <HTML>
    <TITLE> Products</TITLE>
    <%
        out.println("<B> TEST </B>");
        ResultSet rs;
        materia mat = new materia();
       rs = mat.showData("SELECT * FROM PRODUCTS");
    // THE ERROR OCURR IN THE STATEMENT ABOVE
    // WHAT AM I DOING OF WRONG????
    // ... REST OF CODE
    %> 
    </HTML>Thanks for your help.
    Regards.
    Clayton

  • Is it recommended to instantiate Model object from Backing Bean

    Wondering what are the best practices in developing JSF,Spring, Hibernate application.
    Appfuse/Equinox example instantiate Model Object i.e. POJO in the Backing bean. Here is the snippet
    UserForm.java (Backing Bean)
    public class UserForm {
    public User user = new User();
    public UserManager mgr;
    // Getter & Setter methods for user & mgr
    //Persistence
    public String save() {
    mgr.saveUser(getUser());
    addMessage("user.saved", getUser().getFullName());
    return "success";
    I undertand the purpose of having UserManager defined in backing bean but wondering why do we need to have Model (i.e. User) defined in backing bean . Is this a best practice?
    Is it recommended to populate model object with data in the backing bean and then call for business methods like mgr.saveUser(getUser());
    Regards
    Bansi

    Here is some more info
    UserForm is a JSF managed bean,
    User is a hibernate mapped POJO, and
    UserManager is manager class in Spring
    I am wondering about perfomance issues i.e. making DB calls from backing bean getters or setters. DB calls can mean a performance hit, and JSF will call the getters and setters multiple times per page request (which means you'll be doing multiple DB calls).

  • Using static methods to instantiate an object

    Hi,
    I have a class A which has a static method which instantiates it. If I were to instantiate the class A twice with it's static method within class B then you would think class B would have two instances of class A, right?
    Example:
    class A
       static int i = 0;
       public A(int _i)
           i = _i;
       public static A newA(int _i)
            return new A(_i);
    class B
        public B()
            A.newA(5);
            A.newA(3);
            System.out.println(A.i);
        public static void main(String[] args)
            B b = new B();
    }Is there really two instances of class A or just one? I think it would be the same one because if you check the int i it would be 3 and not 5. Maybe static instantiated objects have the same reference within the JVM as long as you don't reference them yourself?
    -Bruce

    It
    seems like you are the only one having trouble
    understanding the question.Well I was only trying to help. If you don't want any help, its up to you, but if that's the case then I fail to see why you bothered posting in the first place...?
    Allow me to point out the confusing points in your posts:
    you would think class B would have two
    instances of class A, right?The above makes no sense. What do you mean by one class "having" instances of another class? Perhaps you mean that class B holds two static references to instances of Class A, but in your code that is not the case. Can you explain what you mean by this?
    Is there really two instances of class
    A or just one?You have created two instances.
    >I think it would be the same one because if you
    check the int i it would be 3 and not 5.
    I fail to see what that has to do with the number of instances that have been created...?
    Maybe static instantiated objects have the
    same reference within the JVM as long as you
    don't reference them yourself????? What is a "static instantiated object"? If you mean that it was created via some call to a static method, then how is it different to creating an object inside the main method, or any other method that was called by main? (i.e. any method)
    What do you mean by "the same reference within the JVM"? The same as what?
    What happened to the first call "A.newA(5)"?
    I think it was overidden by the second call
    "A.newA(3)".As i already asked, what do you mean by this?
    If you change the line for the constructor
    in A to i = i * i you will get "9" as the
    output, if you delete the call "A.newA(3)"
    you will get "25" as the output. Yes. What part of this is cauing a problem?

  • Retrieving Session bean object in a Servlet from FacesContext Object

    Hi,
    I added code in a servlet to retrieve Session bean object from the Faces Context object. I don't know what the problem was, but when I am accessing the application from two different machines and I am trying to retrieve the value from the session object in the servelet it is giving the value what I set into the session bean on one machine browser into another machine browser. Just I want to know the code which I had included in the servlet is correct or not.
    This is the code I am using in my servelt:
    1) To get the Faces context object
    protected FacesContext getFacesContext(HttpServletRequest request, HttpServletResponse response) {
         FacesContext facesContext = FacesContext.getCurrentInstance();
         if (facesContext == null) {
              //System.out.println("Current context was null...creating one now");
              FacesContextFactory contextFactory =
                   (FacesContextFactory)FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
              LifecycleFactory lifecycleFactory =
                   (LifecycleFactory)FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
              Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
              facesContext =
                   contextFactory.getFacesContext(request.getSession().getServletContext(), request, response, lifecycle);
              //Set using our inner class
              InnerFacesContext.setFacesContextAsCurrentInstance(facesContext);
              //set a new viewRoot, otherwise context.getViewRoot returns null
              UIViewRoot view = facesContext.getApplication().getViewHandler().createView(facesContext, "ContextName");
              facesContext.setViewRoot(view);
         return facesContext;
    2) Code to get the session bean:
    Utils utilsBean = (Utils) getFacesContext(request, response).getApplication().getVariableResolver().resolveVariable (getFacesContext(request, response), "utils");
    Edited by: Ramesh_Pappala on Nov 8, 2007 9:25 AM

    Ramesh_Pappala wrote:
    Hi Raymond,
    Thank you for the reply and can you please send the code No, I cannot do that.
    what you are talking about to get the bean from session through servelet session map so that I can use that one check whether it is working fine in my application or not.
    Thanks.

  • Servlet - Multithreaded unique object confusion.

    Hye there experts.
    A Servlet is a multi-threaded unique object - no doubt about this.
    My question is straight, that I am trying to understand
    When a variable is created inside any unique multi threaded object (like Servlet),
    and when it serves number of user requests(say 10) ,
    how will it create same variable name 10 times !!!
    to be more cleare....
    If I write code like below in my doGet(...) method of sevlet,
    MyClass myobj = new MyClass()
    How the Unique servlet object will understand 10 user requests with same variable name as myobj.
    I think this applies to Java behavior of unique object that is multi-threaded, as Servlet is nothing special
    than a simple Java object at the basic level.
    Kindly clarify friends, welcome any references from specs.
    Many Thanks in advance folks !!! Have a wonderful time !

    you cracked the puzzle...nice ! thanks for addressing this query all of you guys.
    Thinking at the memory level I thought variables will be declared inside object's memory and thus, I was
    a conflict to me that how number of instances with same name is possible when many threads execute it.
    So, answer to me is like you said, instances are managed at the Thread's memory scope and not inside object's
    thus, though n threads are executing, they will have their own instance of same object, no issues with
    same name ofcourse in this case.
    so, at what level thread deals this seperate copy of its own variables ? at method scope or sevlet scope ?
    looking further into memory, where are these references and scope details are maintained ?
    any other memory area inside JVM will have this Metadata of live objects ?
    stepping ahead, if I declare this variable as volatile,
    multithreading will be serious issue with dirty reads under this case, right ?
    great job again folks, welcome comments..even if I deserve any yelling at my questions, not too much pls :-)

  • How to instantiate an object from another's class?

    Hi... first post here
    I have the following problem:
    I have a first object, lets call it obj1, of class X (where X could be, for example, 'Class1' or in another moment 'Class2', etc.)
    Now, I have another object, obj2, which I wish to instantiate it with the same class as obj1. The problem is I don't always know which class does obj1 belongs, so programming with an if-else statement and the getClass().getName() method is not a solution, since I cannot program for all the possible cases.
    I know that with obj1.getClass() I get obj1's class and that with obj1.getClass().getName() I get a String with obj1's class name.
    I guess that making obj2 of class Object I can get it, but my question is:
    How do I do to create the instance of obj2 so its class in that moment is the same as the class of obj1? (And by the way, how can I use a specific constructor of obj1 for obj2?)
    I repeat that the if-else method won't do since the class for obj1 won't always be in a known set of classes.
    Thanks for any help or tip you can give me
    Javier
    from Mexico

    You would use the Class.forName() static method to get a Class object of the class you are looking for. Then you would use its newInstance() to create an instance of that class using a no-arguments constructor. If you need some other constructor (and how would you know that?) then Class has a getConstructor(...) method and a getConstructors() method that return one or more Constructor objects you could use. Follow the API documentation from there.

  • Triggering Servlet using URLconnection object - Security Issue

    Hi,
    I am calling a servlet from my Java Program using Url and URl Connection object.
    The UrlConnection.Openconncetion(URl) will trigger my servlet. I want to send the input parameters using Post method.
    I want to use post method becuase if i use get method, any one who know my servlet name can hardcode the input parameter and get the confidential data by using browser.
    How i can use post method to do that?
    pleaasse help me.
    thanx
    muthu

    String JSPUrl = "http://somedomain.com";
    URL url = new URL( JSPUrl );
    URLConnection conn = url.openConnection();
    //Set up Post Query String
    String postquery = "param1=" + URLEncoder.encode("This is parameter 1" ) +
    "&param2=" + URLEndocer.encode("This is parameter 2" );
    conn.setDoInput( true );
    conn.setDoOutput( true );
    conn.setUseCaches( false );
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    // send the data
    DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
    dos.writeBytes( postquery );
    dos.flush();
    dos.close();
    //Read from the connection
    BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream() ) );
    .....

  • Servlet Calls another Servlet, Returns an Object

    Is it possible to call another servlet (which is loaded through
              Load-on-startup) from another servlet. The return should be an Object.
              I know I am kind of asking for a procedural way of programming.
              Example : Servlet "IamReady" is loaded and gets a request with binary
              data. It replies with a Binary Object.
              Servlet "serviceCall" calls IamReady to get the resoponse.
              I know that there are forward (using requestDispatcher) and "include"
              directives to have another servlet service calling servlet.
              Also, if I define a method in the (generic servlet) does each call to
              methos is executed in different thread (like doPost and doGet).
              Thanks.
              Chris
              

    "Michael Reiche" <[email protected]> wrote in message news:<[email protected]>...
              Thank you Michael,
              > It is possible to call a servlet from a servlet.
              >
              > You can 'return' an object by putting it in the httpRequest.
              You mean httpResponse.
              >
              > The call is NOT executed in a separate thread.
              >
              > From this post (and the other post about a connection pool) - I wonder if
              > you really need to be using servlets. I couldn't think of a good reason why
              > the connection pool needs to be a servlet.
              Are you suggesting I should just have a class. Reason I have it as
              servlet, b'caz I do a load-on-startup and do initialiazation etc. in
              the init method. May be if you suggest how I can do it otherwise, I
              would like to implement it that way.
              Thanks again.
              >
              > Mike
              >
              > "MOL" <[email protected]> wrote in message
              > news:[email protected]...
              > > Is it possible to call another servlet (which is loaded through
              > > Load-on-startup) from another servlet. The return should be an Object.
              > > I know I am kind of asking for a procedural way of programming.
              > >
              > > Example : Servlet "IamReady" is loaded and gets a request with binary
              > > data. It replies with a Binary Object.
              > >
              > > Servlet "serviceCall" calls IamReady to get the resoponse.
              > >
              > > I know that there are forward (using requestDispatcher) and "include"
              > > directives to have another servlet service calling servlet.
              > >
              > > Also, if I define a method in the (generic servlet) does each call to
              > > methos is executed in different thread (like doPost and doGet).
              > >
              > > Thanks.
              > >
              > > Chris
              

  • Cannot instantiate java object from c funtion

    Hi guys,
    I need some help on the following problem :
    i want to call java method from c funtion using jni. My java method should instantiate another class on java side. Here's an example.
    public class KMS {
        public int problemMethod() {
               System.out.println("We are in 1"); // This is written on the screen
               Parser parser = new Parser();
              System.out.println("We are in 2"); // This is not, but no problem on java side
             return 1;
    public class Parser {
       // This class parse an XML document
    }And Here's my c code :
    void main(int argc, char *argv[])
         // create JVM with success
    jclass cls =(jclass) env->NewGlobalRef (env->FindClass ("KMS"));
         if (cls == 0)
                              printf("cannot find cls \n");
         jmethodID mid = (env)->GetMethodID(cls, "<init>", "()V");
         if (mid == 0)
              printf("cannot find initialization\n");
         jobject jobj = (env)->NewObject(cls, mid);
         if (jobj == 0)
              printf("cannot find object\n");
         jmethodID mymid = (env)->GetMethodID(cls, "problemMethod", "()I");
         if(mymid == 0)
              printf("cannot find problemMethod\n");
         jint result = (env)->CallIntMethod(jobj, mymid);
         printf("result %d\n", result);
    }I get the following when I run c program :
    We are in 1
    I get no error msg, and the return value is 0. It seems that the JVM cannot instantiate class Parser. But the problem is when I run java code only, from a java main, it works fine. Do I need to implement another things in c side in order to be able to instanciate class Parser.
    Thanks a lot for your help,
    javaFriendly

    1. You have left out some important facts (like where
    is your java code establishing the native method?
    The native method and java codes can communicate. I can see the first System.out.println result when calling native method. My problem is for the second one. Class Parser cannot be instantiate. (But the java code is correct, I try it when I use only java).
    2. Since your native code returns nothing, why would
    you expect ANY particular value to be returned?
    I was talking about return in java side. My java code should return me 1, but in native method a see a 0. This shows that there's an error when calling java.
    3. I would not count on the printf statements. You
    probably - sometime - should see some output, but if
    you don't do a "flush" after ech one, then there is a
    good chance it will not appear where you expect it.Can you tell me how to use "flush" in order to see all results,
    Best regards
    Java friendly

  • How do I instantiate an object in FLEX or AIR?

    Hi,
    There must be something that I don't know that makes instantiation of an object different when doing it from <mx:WindowedApplication></mx:WindowedApplication> class and in the normal XXXX.as class.
    For example I couldn't connect to SQLite. I put all the connection code into the function. Then I put this function into the both mentioned places. When putting the same function into the Application class it worked but putting it to the XXXX.as class it didn't work.
    What is it, that I don't know about that prevents executing this function correctly. Code of the function works correctly. Maybe there are some hidden variables, paths etc.
    Yesterday, a similar problem appeared with 3rd party code that I've added to my application. And the same happened, it works in the Application class but doesn't work in XXXX.as class.
    Please help,
    Christoferek

    Hi Christoferek,
    you probably know this already, but the basic rule for instantiation is something like
    import mx.controls.List;
    protected function my_function():void
      var my_list: List
      my_list = new List();
      my_list.id = "my_list";
    Setting the id is prtty much essential if you are going to refer to the new object somewhere later (if it's just some static text, you may not want to bother).
    the above should work whether you're in an MXML file or AS - you just need to get the import right each time you use it.
    But maybe what you are meaning is not the instantiation part, but that the new object does not function as expected?
    Richard

  • Instantiate Java objects from C++ and the ability for callbacks

    I've been reading up on JNI and I've been able to
    1) load a C++ DLL and call C++ functions from Java and
    2) call Java functions from a C++ DLL.
    However, I haven't been able to find a way to pass a C++ interface class to a Java method (from a C++ DLL), where the Java method will call functions in that interface. (That is; I need to initiate the C++ DLL before any Java code is called.) I'll illustrate below if I'm unclear.
    // Java
    public class javaClass
         public void doStuff(WrapperInterface wi)
              wi.foobar();
    // C++
    class WrapperInterface
         virtual void foobar() = 0;
    class cppClass : public WrapperInterface
         virtual void foobar()
              printf("helloworld");
    int main()
         // initiate JVM, environment etc
         javaClass javaInstance;
         WrapperInterface* cppInstance = new cppClass();
         javaInstance.doStuff(cppInstance);
    }How can I accomplish this?
    I can't seem to instantiate a class in C++, that have been compiled as C++ with the javah command, so I can't instantiate it and set its initial values. (The functions are not declared as static in my Java class at least...) I can on the other hand instantiate it as a Java class. However, nothing happens when I call (from C++) the functions of the instantiated Java class.
    Also, it seems according to my tests and the documentation that I could find that you are required to use a System.LoadLibrary() from Java. Will not that make the DLL it loads load again, thus creating two instantiations of that DLL?
    As a final thought, if this is not possible with SUN's JNI, will it be possible to do with other native interfaces for Java?

    You can pass a pointer back to java by using a java long data type. You can pass that to other java native (JNI) methods and write code that casts the long back to the C++ class and then calls a class method for that class.

  • How to instantiate object in JSP/STRUTS page?

    I worked through the STRUTS tutorial (http://rzserv2.fhnon.de/~lg002556/struts/Doku.html) but I get errors when I try to instantiate an object of a class that is in my WEB-INF/classes directory:
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 14 in the jsp file: /BookSerialize.jsp
    Generated servlet error:
    [javac] Compiling 1 source file
    D:\Programme\jakarta-tomcat-4.1.12\work\Standalone\localhost\strutsdemo\BookSerialize_jsp.java:86: cannot resolve symbol
    symbol : class Book
    location: class org.apache.jsp.BookSerialize_jsp
    Book book = new Book();
    ^
    The Book.class (and other classes) is in the WEB-INF/classes directory. The BookSerialize.jsp is here:
    <%@ page language="java" import="java.beans.XMLEncoder, java.beans.XMLDecoder, java.io.*"%>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
    <html:html locale="true">
    <head>
    <html:base/>
    <title><bean:message key="index.title"/></title>
    </head>
    <body bgcolor="white">
    <h2>Book Serialization</h2>
    <%
    Book book = new Book();
    book.setTitle("A great Book about Struts");
    book.setPages(100);
    out.println("<member>First Title: " + book.getTitle() + "</member>");
    try {
    XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("/Sample.xml")));
    encoder.writeObject(book);
    encoder.close();
    } catch(Exception ex) {
    out.println(ex);
    book.setTitle("A great Book about Struts, Second Edition");
    out.println("<member>Second Title: " + book.getTitle() + "</member>");
    try {
    XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(new FileInputStream("/Sample.xml")));
    book = (Book) decoder.readObject();
    decoder.close();
    } catch(Exception ex) {
    out.println("<h1>" + ex + "</h1>");
    out.println("<member>Third Title: " + book.getTitle() + "</member>");
    %>
    </body>
    </html:html>
    I also get the same error when deploying and (trying to) run on the J2EE 1.3.1 server.
    So far, I just used JSP pages working with beans (usebean tag). Is it possible at all to just do a
    MyClass myObject = new MyClass();
    within a JSP page, if MyClass.class is in the WEB-INF/classes of the web application?
    Is there any kind of import missing? Book.class is in the default package, so i can't state it in the page directive/import parameter of the JSP page...
    any advice?

    I think, I got it: you have to use package names for your classes and avoid the default package. After I used a package name, it was possible to instantiate the object ....

  • Applet-servlet communication, object serialization, problem

    hi,
    I encountered a problem with tomcat 5.5. Grazing the whole web i didn't find any solution (some guys are having the same problem but they also got no useful hint up to now). The problem is as follows:
    I try to build an applet-servlet communication using serialized objects. In my test scenario i write a serialized standard java object (e.g. a String object) onto the ObjectOutputStream of the applet/test-application (it doesn't matters wheter to use the first or the latter one for test cases) and the doPost method of the servlet reads the object from the ObjectInputStream. That works fine. But if i use customized objects (which should also work fine) the same code produces an classnotfound exception. When i try to read and cast the object:
    TestMessage e = (TestMessage)objin.readObject();
    java.lang.ClassNotFoundException: TestMessage
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1205)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    ...That seems strange to me, because if i instantiate an object of the same customized class (TestMessage) in the servlet code, the webappclassloader doesn't have any problems loading and handling the class and the code works fine!
    The class is located in the web-inf/classes directory of the application. I've already tried to put the class (with and without the package structure) into the common/classes and server/classes directory, but the exception stays the same (I've also tried to build a jar and put it in the appropriate lib directories).
    I've also tried to catch a Throwable object in order to get information on the cause. But i get a "null" value (the docu says, that this will may be caused by an unknown error).
    I've also inspected the log files intensively. But they gave me no hint. Until now I've spend a lot of time on searching and messing around but i always get this classnotfound exception.
    I hope this is the right place to post this problem and i hope that there is anyone out there who can give me some hint on solving this problem.
    Kindly regards,
    Daniel

    hi, thanks for the reply,
    all my classes are in the web-inf/classes of the web-app and have an appropriate package structure. thus the TestMessage class is inside a package.
    i tried some names for the testclass but it didn't matter. the exception stays the same. I also tried to put the jar in the common/lib but the problem stays.
    Well the problem with loaded classes: As i mentioned in the post above i can instantiate an object of TestMessage in the code without any problems (so the classloader of my webapp should know the class!!)
    only when reading from the objectinputstream the classloader doesn't seem to know the class?? maybe theres a parent classloader resposible for that and doesn't know the class?
    strange behaviour...
    p.s. sending the same object from the servlet to the client works well
    regards
    daniel
    Message was edited by:
    theazazel

Maybe you are looking for