Solved

Can't use beans and servlet at the same time

Posted on 2003-10-22
36
313 Views
Last Modified: 2010-04-01
Well, first I'm pretty new to JSP so if I make any really stupid mistakes, forgive me.

At the moment, this is the architecture for my website.  I've got main page where you can click on a picture which takes you to a jsp page.  This jsp page uses a bean to get a bunch of data out of a database and then display it on the screen.  Now, this part works.

 Next, I added a login.html page which uses a servlet to verify a username and password. I added the servlet and mapping stuff to the web.xml file.  The log on page works fine.  But since I changed the web.xml file, the jsp page that uses the bean isn't working.  I don't get any errors but it seems like the beans don't seem to be working.  

Now, the one thing I can think of that I'm doing that it might not like is that fact that none of my classes are in packages.  I've just put them all in the WEB-INF/classes directory?  Does this matter?

Any help would be great!!!

0
Comment
Question by:MegaNasty
  • 20
  • 10
  • +3
36 Comments
 
LVL 3

Expert Comment

by:applekanna
ID: 9596950
you are right all classess ned to be in WEB-INF/classes dir.

Can you post your web.xml ?
0
 

Author Comment

by:MegaNasty
ID: 9597061
Here's the web.xml file

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/dtd/web-app_2_2.dtd">
     
<web-app>
      <servlet>
            <servlet-name>Login</servlet-name>
            <description> handles the logging in </description>
            <servlet-class>LoginServlet</servlet-class>
      </servlet>

      <servlet-mapping>
            <servlet-name>Login</servlet-name>
            <url-pattern>/Login</url-pattern>  
      </servlet-mapping>

</web-app>
0
 
LVL 19

Expert Comment

by:Kuldeepchaturvedi
ID: 9597096
change your web.xml like
<servlet-mapping>
         <servlet-name>Login</servlet-name>
         <url-pattern>servlet/Login</url-pattern>  
    </servlet-mapping>

and then try it out..
now one more thing that you will have to take care is that your HTML should be submitted to
/servlet/LoginServlet instead of /LoginServlet.

If you are using Tomcat 4.1 or greater than it will need you to put your bean inside a package.... this package shd exist in your web-inf/classes.

Regards
0
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

 

Author Comment

by:MegaNasty
ID: 9597111
Awesome.  I'll give that a go and tell you what happens.
0
 

Author Comment

by:MegaNasty
ID: 9597191
Didn't change anything.  Still not getting anything out of the beans...

The login works with my web.xml but the beans don't work when the servlet is including in the xml file.

Anymore suggestions guys?


0
 
LVL 2

Accepted Solution

by:
Karaa earned 44 total points
ID: 9597274
it is better to put ur classes in a package and in ur jsp call this class with that package.
If u don't use servlet then can u access that bean?
0
 

Author Comment

by:MegaNasty
ID: 9597294
I'm really stumped here guys?

I'm trying to work out what I'm doing wrong.

This is an exert from the jsp file.
-------------------------------------------------------------------------------.
.
.
      String passtype = request.getParameter("part");

      PartTitleBean partTitleBean = new PartTitleBean();
      List titles = partTitleBean.getParts();
      PartsBean currentPart;
   %>
.
.
.
     <%
           
           // store titles in session for further use
      session.setAttribute( "partTitles", titles );

      // obtain an Iterator to the set of keys in the List
      Iterator iterator = titles.iterator();

      while ( iterator.hasNext() ) {
           etc....
-------------------------------------------------------------------------------

The problem is that the iterator.hasNext() returns false...


Thought this might help... probably not though
0
 

Author Comment

by:MegaNasty
ID: 9597302
yes, if I don't include the servlet in the web site, the beans work.
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9597591
Is this a problem with the ordering of the tags in your web.xml file?

Beans (EJBs) must be declared as the last part of the web.xml.

See the section "Deployment Descriptor" on the following page to check your ordering:

http://www.microps.com/mps/3254.html
0
 

Author Comment

by:MegaNasty
ID: 9597662
The beans are basically interacting with an Access DB to return some data which is to be displayed with the jsp page.  

I've included my web.xml page above.  Do I need to include anything else in the web.xml file?  Something to do with the beans??
0
 

Author Comment

by:MegaNasty
ID: 9597858
desperation is creeping here cos I can't do anymore til this is fixed
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9598160
Sorry.  It seems that this is (as you said) a JavaBean, not an EJB.  Apologies if my previous comment confused the issue.

Can you add a debug line in the bean (eg. System.out.println("got here...");)

This should then appear in the catalina.out file in the logs directory.

Also, are there any messages in the catalina.out, or other logs that might indicate a problem?
0
 

Author Comment

by:MegaNasty
ID: 9598414
well, I've added all my classes (beans and servlets) to a package :- classes.store

Ok.  This seemed to help a little bit.  Help  I mean, I get a different problem :(

Now, I get an error when it loads the .jsp file.  I'm getting an error saying
"Method getCategory() not found in class PartsBean"  But I'm positive that it is in there.  I've checked and recompile many times to check this problem... but it can't seem to access the getCategory() method.  

The weirdest thing is the only thing I've changed in the PartsBean.java file is the package name when reflecting the directory structure and if it was a problem with this line, then I would get an error saying it couldn't access the bean,right?

HELP ME!!! ARG!
0
 

Author Comment

by:MegaNasty
ID: 9598478
These are the relevant lines (I think)

These lines are from my PartsBean.java file
---------------------------------------------------------------------------------
package classes.store;
.
.
public class PartsBean implements Serializable {
     private String Name, Category, Description;
.
.
public String getCategory()
      {
            return Category;
      }
.
.
.
---------------------------------------------------------------------------------

These lines are in my .jsp file
---------------------------------------------------------------------------------
import = "java.util.*, classes.store.*"
.
.
PartsBean currentPart;

String parttype = currentPart.getCategory();  \\this is were I get the error
.
.
---------------------------------------------------------------------------------
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9598501
Hmm.

Can you post the PartsBean.java file?

I see that before, the problem was with partsBean.getParts(), now it is with partsBean.getCategory() , yes?

Correct this if it's wrong...

You have a PartTitleBean class that contains a List of PartBeans.
You retrieve this using:

>> List titles = partTitleBean.getParts();

and then you iterate through the parts as follows:

PartBean currentPart;

Iterator it = titles.iterator()
{
    currentPart = (PartBean)it.next();

    ...  and somewhere in this loop, you do

    xxx = currentPart.getCategory();

Is that right?
0
 

Author Comment

by:MegaNasty
ID: 9598603
Here it is:-

// PartsBean.java
// A PartBean object contains the data for one Part.

// Java core packages
import java.io.*;
import java.text.*;
import java.util.*;

// third-party packages
import org.w3c.dom.*;

public class PartsBean implements Serializable {
         private String Name, Category, Description;
      private int Stock;
      private double Price;
         
      // set Name
      public void setName(String name)
      {
            Name = name;
      }
      
      // set category
      public void setCategory(String category)
      {
            Category = category;
      }

      // set stock
      public void setStock(int stock)
      {
            Stock = stock;
      }

      // set Price
      public void setPrice(double price)
      {
            Price = price;
      }

        // set Price
      public void setDescription(String description)
      {
            Description = description;
      }

      //return name
      public String getName()
      {
            return Name;
      }      

      //return category
      public String getCategory()
      {
            return Category;
      }      

      //return stock
      public int getStock()
      {
            return Stock;
      }      

      //return name
      public double getPrice()
      {
            return Price;
      }      
   
        //return description
      public String getDescription()
      {
            return Description;
      }
}
0
 

Author Comment

by:MegaNasty
ID: 9598624
Here is the PartTitleBean:-
// Java core packages
import java.io.*;
import java.sql.*;
import java.util.*;

// Java extension packages
import javax.naming.*;
import javax.sql.*;

public class PartTitleBean implements Serializable {
    private Connection con;
    private PreparedStatement s;
    private ResultSet rs;

 
   // construct TitlesBean object
   public PartTitleBean()
   {
      
      // attempt database connection and setup SQL statements
         try {

          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // set this to a MS Access DB you have on your machine
                  String filename = "C:/Maverickcomp.mdb";
            String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
            database+= filename.trim() + ";DriverID=22;READONLY=true}"; // add on to the end

            // now we can get the connection from the DriverManager
             con = DriverManager.getConnection( database ,"","");    
            
        }
       
        catch (Exception err) {
        System.out.println("ERROR: " + err);
        }
   }
   public void test()
   {
   }

   // return a List of PartBeans
   public List getParts()
   {
      List partList = new ArrayList();

      // obtain list of titles
      try {
         ResultSet rs = s.executeQuery();
      
      s = con.prepareStatement("SELECT * FROM Parts");            
         
         // get row data
         while ( rs.next() ) {
            PartsBean part = new PartsBean();
                  
            part.setName(rs.getString("Name"));
            part.setCategory(rs.getString("Category"));
            part.setPrice(rs.getDouble("Price"));
            part.setStock(rs.getInt("Stock"));
            part.setDescription(rs.getString("Description"));
           
            partList.add(part);
         }
      }
     
      catch (SQLException exception ) {
         exception.printStackTrace();
      }
      finally {
          return partList;
      }
   }




   // close statements and terminate database connection
   protected void finalize()
   {
       try {
         con.close();
       }
       
       catch (SQLException exception) {
           exception.printStackTrace();
       }
   }
}
0
 

Author Comment

by:MegaNasty
ID: 9598632
Finally, the jsp file:-


<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<%@
   page language = "java"
   import = "java.util.*"
   session = "true"
%>

<!-- begin document -->
<html xmlns = "http://www.w3.org/1999/xhtml">

<head>
   <title>Part List</title>

   <link rel = "stylesheet" href = "styles.css"
      type = "text/css" />
</head>

<body>
   <jsp:include page = "banner.html" flush = "true"/>

   <%
String passtype = request.getParameter("part");

      PartTitleBean partTitleBean = new PartTitleBean();
      List titles = partTitleBean.getParts();
      PartsBean currentPart;

   %>
   
   <P class = "bigfont"> <%= passtype %> </p>

   <table border="1"align = "center">
      <thead><tr>
          <th>Title</th>
          <th>Price</th>
      </tr></thead>
   
     <%
           
           // store titles in session for further use
      session.setAttribute( "partTitles", titles );

      // obtain an Iterator to the set of keys in the List
      Iterator iterator = titles.iterator();


      while ( iterator.hasNext() ) {
         currentPart = ( PartsBean ) iterator.next();
        
       String parttype = currentPart.getCategory();

       if (passtype.equals(parttype)){
%>
         <tr>
            <td>
               <a href = "selpart.jsp?Part=<%= currentPart.getName() %>">
                     <%= currentPart.getName() + "     " %>
                  </a>

            </td>
            <td>
                  <a href = "selpart.jsp?Part=<%= currentPart.getName() %>">
                     <%=  currentPart.getPrice()+"" %>

            </td>
            
         </tr>

   <% // continue scriptlet  
       }
      }   // end while loop
   %>
         </table>
   </p>
</body>

   <p> Click any of the above products to view them. </p>
</html>
0
 

Author Comment

by:MegaNasty
ID: 9598920
Any help now?  :)
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9598967
OK.

Since you added the package, you may have some older .class files kicking around (under the Tomcat "work" directory).

If this is the case, your .JSP may be referring to a version of the bean that doesn't include this method.

I notice that at the top of the .JSP file, your import only includes java.util.

Make sure this is changed to

>> import = "java.util.*, classes.store.*"

as you said earlier ;-)
0
 

Author Comment

by:MegaNasty
ID: 9599035
ooops.  That was an older version the jsp I had open in notepad so I just copied that.  The real one has that import line.  

But why would the problem only occur when I use getCategory?  Wouldn't it break down if it couldn't find the bean when the bean is declared??

This is really confusing me...
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9599098
Well I can see why this is confusing.

Can you post the complete error output that you get when you access the JSP.

(Sorry this is taking so long.  Stick with it and I'm sure we'll have it fixed soon).
0
 

Author Comment

by:MegaNasty
ID: 9599163
Error: 500
Location: /cmon/parts.jsp
Internal Servlet Error:

org.apache.jasper.JasperException: Unable to compile C:\Documents and Settings\Matt\Desktop\tomcat\work\DEFAULT\cmon\parts_14.java:128: Method getCategory() not found in class PartsBean.
                         String parttype = currentPart.getCategory();
                                                                  ^
C:\Documents and Settings\Matt\Desktop\tomcat\work\DEFAULT\cmon\parts_14.java:158: Method getPrice() not found in class PartsBean.
                  out.print(  currentPart.getPrice()+"" );
                                                  ^
2 errors

      at org.apache.tomcat.facade.JasperLiaison.javac(JspInterceptor.java:898)
      at org.apache.tomcat.facade.JasperLiaison.processJspFile(JspInterceptor.java:733)
      at org.apache.tomcat.facade.JspInterceptor.requestMap(JspInterceptor.java:506)
      at org.apache.tomcat.core.ContextManager.processRequest(ContextManager.java:968)
      at org.apache.tomcat.core.ContextManager.internalService(ContextManager.java:875)
      at org.apache.tomcat.core.ContextManager.service(ContextManager.java:833)
      at org.apache.tomcat.modules.server.Http10Interceptor.processConnection(Http10Interceptor.java:176)
      at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:494)
      at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:516)
      at java.lang.Thread.run(Thread.java:484)



Here it is.
0
 
LVL 15

Assisted Solution

by:jimmack
jimmack earned 43 total points
ID: 9599262
OK.  I'm not sure where the "14" has come from on the file that is referenced.

Have a look in the C:\Documents....\cmon directory to see if it contains the files you would expect.

Then have a look at parts_14.java in that directory.  This should contain the Servlet code that is generated from your JSP.  If should have the "import classes.store;" at the top.


Whoa!

Hang on.  "classes.store"?

If your package name is classes.store, does this mean that under your WEB-INF, you have the following structure:

WEB-INF\classes\classes\store\ <.class files> ?

I notice that your previous postings of PartTitleBean.java and PartsBean.java don't include a "package" line.

If they do, is this line:

package classes.store;

?

Sorry if this sounds a bit cheeky, but are you sure that all your files are saved and up to date (I only mention this because of your earlier comment about pasting a file that you currently had open in notepad that was out of date)?
0
 

Author Comment

by:MegaNasty
ID: 9599383
Sorry mate.  I must have all the old versions open.  I've checked all my beans have the package line in.  They do.

And the WEB-INF\classes\classes\store\*.class is correct to.  That's all fine.

mmm... Sorry about the postings being so vague.  Lack of sleep.

Any more help would be great.
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9599893
I understand ;-)

How about the content of parts_14.java?

Make sure the imports are correct and make sure you delete and .class files that might be hanging around from earlier builds.

I don't think you should have any class files in the WEB-INF\classes directory any more.

And remember :-)  If the exception report changes at any stage, please post the complete new one ;-)
0
 

Author Comment

by:MegaNasty
ID: 9599894
Lastest update on my problem...

Got rid of all errors.  I basically cleared all my tomcat default stuff, restarted the server and now I'm getting now errors... but!... I'm back to my original problem.  It seems like the beans are empty.

The jsp page basically loads up all the parts (of a certain type which is passed to it) and displays them in a table.  But for some reason the table is empty.  

Basically, it has nothing to iterate.  Kinda weird. Cos like I said, I haven't touched the code much and it works when no servlets are used.

Help *YIKES*
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9599944
Calm down ;-)

Let's go back to an earlier suggestion.

In PartTitleBean.getParts(), add two System.out.printlns like this:

         // get row data
System.out.println("About to parse result set");
         while ( rs.next() ) {
          PartsBean part = new PartsBean();
         // get row data
         while ( rs.next() ) {
          PartsBean part = new PartsBean();
                 
          part.setName(rs.getString("Name"));
System.out.println("Part name = " + part.getName());
          part.setCategory(rs.getString("Category"));
          part.setPrice(rs.getDouble("Price"));
          part.setStock(rs.getInt("Stock"));
          part.setDescription(rs.getString("Description"));
           
          partList.add(part);
         }
     
These outputs should appear in your "catalina.out" log file.

Alternatively, you might find an SQLException somewhere in your log files (if something has gone astray elsewhere).
0
 

Author Comment

by:MegaNasty
ID: 9600039
Awesome.  I'll have to check it out in the morning... waaaaay to tired at the moment! :)

Will check out the log in the morning.

I'll be back in about 10 hours or so... hope you're still around.
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9600107
I'll be ready for you next comment ;-)

But.  I'm in the UK, so 10 hours puts it at about 4am.  I'm afraid you'll need to give me at least 4 hours on top of that :-)

Still.  That's a reasonable amount of time to try some stuff out :-)

Don't let anyone sneak in at the last minute and steal the points with a one-liner :-)

Jim.
0
 

Author Comment

by:MegaNasty
ID: 9603337
It's ok, Jimmack.  I know who's doing all the hardwork for me so don't worry about one-liners.

Now, about this log file... I can't find it.  I'm running Tomcat 3.3, does that matter?  Is there any other way ?  I will eventuall upgrade but for right now I have to use 3.3.

Is that going to be a major problem?
0
 

Author Comment

by:MegaNasty
ID: 9604223
Hope you're coming back soon Jimmack.  I'm all out of ideas and need your help badly.  ARG!
0
 
LVL 3

Assisted Solution

by:krispols
krispols earned 43 total points
ID: 9604775
hello MegaNasty,

Just switch this two line:
      try {
         ResultSet rs = s.executeQuery();
     
     s = con.prepareStatement("SELECT * FROM Parts");          
 
must be
      try {
         s = con.prepareStatement("SELECT * FROM Parts");          
         ResultSet rs = s.executeQuery();
     
 regards
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9605456
Hi,  I'm back.

krispols may have solved the problem.

However, is this just a mistake because you had files open in your editor, or did you really change the order of these two statements?

I know you had it working before, so they must have been in the right order at some stage.

The version of Tomcat shouldn't be an issue, nor should the version of Java you're using.

Basically, you've had all the bits working, just not all at once ;-)
0

Featured Post

VMware Disaster Recovery and Data Protection

In this expert guide, you’ll learn about the components of a Modern Data Center. You will use cases for the value-added capabilities of Veeam®, including combining backup and replication for VMware disaster recovery and using replication for data center migration.

Question has a verified solution.

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

Suggested Solutions

This problem is more common than not and I will show you some things to check to solve this problem.
Two types of users will appreciate AOMEI Backupper Pro: 1 - Those with PCIe drives (and haven't found cloning software that works on them). 2 - Those who want a fast clone of their boot drive (no re-boots needed) and it can clone your drive wh…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

832 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