Constructor of UseBean

Hi Everyone
I am trying to use a parameterized constructor for the Bean which is defined as SESSION scoped. I am wondering whether I've to use jsp:param or jsp:setProperty for passing the values to the constructor. If anybody had done this, kindly guide me.
Thanks in advance.
Raj

Hi Raj,
A few months ago I was wondering the same thing and never got a clear response oddly enough but here's how it is:
The convention for beans is that they do not take parameters in their construction and <jsp:useBean/> makes no provision for that.
I feel your pain. There are some ways around this though.
One is that, if it's a session bean, you can implement HttpSessionBindingListener(HttpSessionBindingEvent e)
which provide notification to your bean when it is placed in a session, i.e. <jsp:useBean ....scope="session"/>, by calling the valueBound() method of the Listener.
You can then use the event's getSession() method to get the session object from which you can obtain Session and ServletContext attributes.
Granted this is not performed on construction but you can fundamentally use this as an init() which will be performed immediatley upon inclusion in the session and so is fairly the same.
There's also the valueUnbound() which is called when the the bean, or whatever class, is about to be released.
Very convenient!
One key point which I've never seen emphasized is that the first call to the <jsp:useBean/> tag will perform the construction and binding...subsequent calls automatically check for prior existence of the bean and so do not call it's constructor or HttpSessionBindingListener.
Another point which I still wonder about is just what is a bean anyway? It is simply a class which abides by a certain convention to permit convenient intuitive (via introspection), parameter passing such as <jsp:...setParameter="*"/>, (maybe not quite right syntax, i forget), whereby all parameters corresponding to the request parameters are set according to the bean's setter methods as named by convention.
I've found that in some cases I'd rather just workup a class which provides the services I require, like a good old fashioned constructor which takes parameters.
If need be I write the code to prevent duplicate construction.
Hey, work's for me. In that case I can use it just like a bean complete with all the getters and setters. If needed just write my own use tags which pass parameters to the constructor.
If anyone wants to blast me for this, have at it...always learning.
Brad

Similar Messages

  • Constructor parameter and useBean -tag

    Greetings,
    Is there a way to pass a contructor parameter when using the JSP tags:
    <%@ page import="DBTool" %>
    <jsp:useBean id='manager' scope="application" class=DBTool/>
    The DBTool class needs init parameters in the contructor, but I don`t know any way how to do it when using the useBean tag?
    Regards,
    Eki

    This is as close as you are going to get. The code within the jsp:useBean tag will only get executed when the object needs to be created. With a scope of application, it will only get run once unless you call application.removeAttribute("manager") OR getServletContext().removeAttribute("manager").
    Hope this helps
    <%@ page import="DBTool" %>
    <jsp:useBean id="manager" scope="application" class="DBTool">
           <%
               manager.setProperty1(13);
               manager.setMyProperty2("MyProperty");
           %>
    </jsp:useBean>OR if you want it to be cleaner
    <%@ page import="DBTool" %>
    <jsp:useBean id="manager" scope="application" class="DBTool">
           <% manager.init(parms); %>
    </jsp:useBean>

  • HELP: jsp:useBean not "working"

    I have written a JSP that utilizes some JavaBeans. With one, I do something similar to the following:
    <jsp:useBean id="BeanA" class="mypackage.myFirstBean" />
    That statement executes just fine, as the debug HTML statement that follows is printed using <c:out>.
    Then I follow that with something nearly identical:
    <jsp:useBean id="BeanB" class="mypackage.mySecondBean" />
    The debug statement after this second <jsp:useBean> call is not executed.
    The two beans have no-argument constructors and are in the same package, and both are found in the right hierarchy under WEB-INF/classes inside my WAR file. Also, both are named properly in the JSP. The only difference is that one "executes," and the other does not. I don't even get to call <c:set> on them to actually make them do some work!
    Any insight is appreciated. Let me know if there is anything else I can provide.
    Thanks for your help, and Happy New Year!

    The symptom you described is certainly curious.
    Can you put the second "useBean" line before the first one? Then please tell us if it "executes".

  • Calling an inner class in a jsp:usebean tag

    Hi everybody !
    Here's my problem : working in my project on multiple pages, I'm using inner classes/beans to limitate my '.java' files but I'm stuck when calling that 'inner-bean' in my jsp:usebean tag.
    First, I tried to declare in the class parameter : 'class="MyPrincipalBean.theInnerBean" but jsp returns me a 'not found' message.
    I tried an other issue with this :
    'class="MyPrincipalBean$theInnerBean" but I encountered a 'Attempt to use a bean type without a void constructor in jsp:useBean tag (JSP 1.1 specification, 2.13.1)'. Since I can't find that specification, I'm sending an SOS.
    Am I on the good way ? If somebody as encoutered that sort of problem, it would be very kind of you to help me.
    Thanks for your help !
    [email protected]

    Thanks for your help!
    I must recognize that my explainations weren't really precise.
    My principal bean owns a table of my inner-class type :
    public class FirstBean extends EntityBean {
    private SecondBean[] tabSB;
    public SecondBean[] getTabSB() {...}
    public void setTabSB(SecondBean[] p_tabSB) {...}
    public class SecondBean {...}
    So I can call a specific bean from the tab in my Servlet for another page.
    But I think I have the solution and I need your advise :
    I tried this :
    <jsp:useBean id="FirstBean" class="<...>.FirstBean" scope="session" />
    <jsp:useBean id="SecBean" beanName="<...>.FirstBean$SecondBean" type="<...>.FirstBean$SecondBean" scope="request" />
    And would you believe it ? It seems to work ! But I have to test this farther to be sure. What do you think of it ?

  • jsp:useBean error== The value for useBean class is invalid

    Can anybody tell me why am i getting the error for the JavaBean.
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: /SimpleBean.jsp(9,0) The value for the useBean class attribute com.stardeveloper.bean.test.SimpleBean is invalid.
         org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
         org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
         org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:148)
         org.apache.jasper.compiler.Generator$GenerateVisitor.visit(Generator.java:1272)
         org.apache.jasper.compiler.Node$UseBean.accept(Node.java:1178)
         org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
         org.apache.jasper.compiler.Node$Visitor.visitBody(Node.java:2411)
         org.apache.jasper.compiler.Node$Visitor.visit(Node.java:2417)
         org.apache.jasper.compiler.Node$Root.accept(Node.java:495)
         org.apache.jasper.compiler.Node$Nodes.visit(Node.java:2361)
         org.apache.jasper.compiler.Generator.generate(Generator.java:3426)
         org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:216)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:332)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:312)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:299)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:586)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:317)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    note The full stack trace of the root cause is available in the Apache Tomcat/6.0.20 logs.
    Apache Tomcat/6.0.20
    my jsp file is in path c:\tomcat6\webapps\dev\SimpleBean.jsp
    my JavaBean compiled class is in path
    c:\tomcat6\webapps\dev\WEB-INF\classes\com\stardeveloper\bean\test\SimpleBean.class
    and my SimpleBean java class declaration is
    package com.stardeveloper.bean.test;
    public class SimpleBean implements java.io.Serializable
    and my jsp page SimpleBean.jsp pages call to useBean is as follows
    <jsp:useBean id="simple" class="com.stardeveloper.bean.test.SimpleBean">
         <jsp:setProperty name="simple" property="name" value="Sujoy" />
         <jsp:setProperty name="simple" property="age" value="26" />
    </jsp:useBean>
    Please help me anybody.

    First, try restarting Tomcat :-)
    Main 3 reasons for "useBean class is invalid"
    - class must be in a package (ok)
    - class must be public, and have public constructor that takes no arguments (check)
    - class must be compiled, valid and on the classpath. Normally this means the WEB-INF/classes directory.
    From what you have told us, everything seems to check out.
    Try recompiling the .class file to ensure it is valid.
    Does your constructor do anything which might thrown an exception?
    Can you invoke it in scriptlet code without getting an exception?
    <%@ page import="com.stardeveloper.bean.test.SimpleBean" %>
    <% SimpleBean sb = new SimpleBean() %>Trying it in scriptlet code like this might give you a different error message that might help your diagnosis.
    cheers,
    evnafets

  • Can we use an overloaded constructor of a Java Bean with Session Tracking

    Hi Friends,
    If any one can solve my query.... It would be helpful.
    Query:
    I have a Java Bean with an overloaded constructor in it. I want to use the overloaded constructor in my JSP.
    1. One way of doing that is to use it directly in the "Scriptlets" (<% %>). But then I am not sure of the way to do session tracking. I think I can use the implicit objects like "session", "request" etc. but not sure of the approach or of the implementation method.
    2. Another way is through the directive <jsp: useBean>. But I cannot call an overloaded constructor with <jsp: useBean>. The only alternative way is to use the directive <jsp: useBean> where I have to write getter and setter methods in the Java Bean and use the <jsp: setProperty> and <jsp: getProperty> standard actions. Then with this approach I cannot use the overloaded constructor.
    Can any one suggest me the best approach to solve this problem ?
    Thanks and Regards,
    Gaive.

    My first reaction is that you can refactor your overloaded constructor into an init(arguments...) method. Instead of overloaded constructor, you can call that init method. This is the ideal solution if possible.
    As to the two choices you listed:
    1. This is OK, I believe. You can use scriplet to define the bean and put it into session scope of the pageContext. I am not sure exactly what you meant by session tracking; whatever you meant, it should be doable using HttpSessionAttributeListener and/or HttpSessionBindingListener.
    2. Agreed. There is no way that <jsp:useBean> can call a constructor that has non-empty arguments.
    Please tell me how it works for you.

  • The value for The value for the useBean invalid?

    I get following error when I try to test application in iexplorer.
    org.apache.jasper.JasperException: /guestBookLogin.jsp(12,0) The value for the useBean class attribute com.deitel.jhtp6.jsp.beans.GuestBean is invalid.
    I got this code from a case study and I was testing it. I get
    org.apache.jasper.JasperException: /guestBookLogin.jsp(12,0) The value for the useBean class attribute com.deitel.jhtp6.jsp.beans.GuestBean is invalid.
    error
    I believe this is becaus of version difference but here is my code
    guestBookLogin.jsp
    <!- <?xml version = "1.0"?> -->
    <!-  DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" -->
    <!-- Fig. 27.22: guestBookLogin.jsp -->
    <%-- page settings --%>
    <%@ page errorPage = "guestBookErrorPage.jsp" %>
    <%-- beans used in this JSP --%>
    <jsp:useBean id = "guest" scope = "page"
       class = "com.deitel.jhtp6.jsp.beans.GuestBean" />
    <jsp:useBean id = "guestData" scope = "request"
       class = "com.deitel.jhtp6.jsp.beans.GuestDataBean" />
    <html xmlns = "http://www.w3.org/1999/xhtml">
    <head>
       <title>Guest Book Login</title>
       <style type = "text/css">
          body
             font-family: tahoma, helvetica, arial, sans-serif;
          table, tr, td
             font-size: .9em;
             border: 3px groove;
             padding: 5px;
             background-color: #dddddd;
          }`
       </style>
    </head>
    <body>
       <jsp:setProperty name = "guest" property = "*" />
       <% // start scriptlet
          if ( guest.getFirstName() == null ||
               guest.getLastName() == null ||
               guest.getEmail() == null )
       %> <%-- end scriptlet to insert fixed template data --%>
             <form method = "post" action = "guestBookLogin.jsp">
                <p>Enter your first name, last name and email
                   address to register in our guest book.</p>
                <table>
                   <tr>
                      <td>First name</td>
                      <td>
                         <input type = "text" name = "firstName" />
                      </td>
                   </tr>
                   <tr>
                      <td>Last name</td>
                      <td>
                         <input type = "text" name = "lastName" />
                      </td>
                   </tr>
                   <tr>
                      <td>Email</td>
                      <td>
                         <input type = "text" name = "email" />
                      </td>
                   </tr>
                   <tr>
                      <td colspan = "2">
                         <input type = "submit" value = "Submit" />
                      </td>
                   </tr>
                </table>
             </form>
       <% // continue scriptlet
          }  // end if
          else
             guestData.addGuest( guest );
       %> <%-- end scriptlet to insert jsp:forward action --%>
             <%-- forward to display guest book contents --%>
             <jsp:forward page = "guestBookView.jsp" />
       <% // continue scriptlet
          }  // end else
       %> <%-- end scriptlet --%>
    </body>
    </html>GuestBean.java
    * @(#)GuestBean.java
    * @author:
    * @Description: JavaBean to store data for a guest in the guest book.
    * @version 1.00 2008/7/18
    // JavaBean to store data for a guest in the guest book.
    package com.deitel.jhtp6.jsp.beans;
    public class GuestBean
       private String firstName;
       private String lastName;
       private String email;
       //Constructors
       public GuestBean(){
            public GuestBean(String firstname, String lastname, String email){
                 this.firstName=firstname;
                 this.lastName=lastName;
                 this.email=email;
       // set the guest's first name
       public void setFirstName( String name )
          firstName = name; 
       } // end method setFirstName
       // get the guest's first name
       public String getFirstName()
          return firstName; 
       } // end method getFirstName
       // set the guest's last name
       public void setLastName( String name )
          lastName = name; 
       } // end method setLastName
       // get the guest's last name
       public String getLastName()
          return lastName; 
       } // end method getLastName
       // set the guest's email address
       public void setEmail( String address )
          email = address;
       } // end method setEmail
       // get the guest's email address
       public String getEmail()
          return email; 
       } // end method getEmail
    } // end class GuestBeanGuestBeanData.java
    * @(#)GuestDataBean.java
    * @author
    * @version 1.00 2008/7/18
    // Fig. 27.21: GuestDataBean.java
    // Class GuestDataBean makes a database connection and supports
    // inserting and retrieving data from the database.
    package com.deitel.jhtp6.jsp.beans;
    import java.sql.SQLException;
    import javax.sql.rowset.CachedRowSet;
    import java.util.ArrayList;
    import com.sun.rowset.CachedRowSetImpl; // CachedRowSet implementation
    public class GuestDataBean
       private CachedRowSet rowSet;
       // construct TitlesBean object
       public GuestDataBean() throws Exception
          // load the MySQL driver
          Class.forName( "com.mysql.jdbc.Driver" );
          // specify properties of CachedRowSet
          rowSet = new CachedRowSetImpl(); 
          rowSet.setUrl( "jdbc:mysql://localhost/VirsarMedia" );
          rowSet.setUsername( "root" );
          rowSet.setPassword( "" );
           // obtain list of titles
          rowSet.setCommand(
             "SELECT firstName, lastName, email FROM guest" );
          rowSet.execute();
       } // end GuestDataBean constructor
       // return an ArrayList of GuestBeans
       public ArrayList< GuestBean > getGuestList() throws SQLException
          ArrayList< GuestBean > guestList = new ArrayList< GuestBean >();
          rowSet.beforeFirst(); // move cursor before the first row
          // get row data
          while ( rowSet.next() )
             GuestBean guest = new GuestBean();
             guest.setFirstName( rowSet.getString( 1 ) );
             guest.setLastName( rowSet.getString( 2 ) );
             guest.setEmail( rowSet.getString( 3 ) );
             guestList.add( guest );
          } // end while
          return guestList;
       } // end method getGuestList
       // insert a guest in guestbook database
       public void addGuest( GuestBean guest ) throws SQLException
          rowSet.moveToInsertRow(); // move cursor to the insert row
          // update the three columns of the insert row
          rowSet.updateString( 1, guest.getFirstName() );
          rowSet.updateString( 2, guest.getLastName() );
          rowSet.updateString( 3, guest.getEmail() );
          rowSet.insertRow(); // insert row to rowSet
          rowSet.moveToCurrentRow(); // move cursor to the current row
          rowSet.acceptChanges(); // propagate changes to database
       } // end method addGuest
    } // end class GuestDataBeanguestBookErrorPage.jsp
    <!-- <?xml version = "1.0"?> -->
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <!-- Fig. 27.24: guestBookErrorPage.jsp -->
    <%-- page settings --%>
    <%@ page isErrorPage = "true" %>
    <%@ page import = "java.util.*" %>
    <%@ page import = "java.sql.*" %>
    <html xmlns = "http://www.w3.org/1999/xhtml">
       <head>
          <title>Error!</title>
          <style type = "text/css">
             .bigRed
                font-size: 2em;
                color: red;
                font-weight: bold;
          </style>
       </head>
       <body>
          <p class = "bigRed">
          <% // scriptlet to determine exception type
             // and output beginning of error message
             if ( exception instanceof SQLException )
          %>
                A SQLException
          <%
             } // end if
               else if ( exception instanceof ClassNotFoundException )
          %>
                A ClassNotFoundException
          <%
             } // end else if
             else
          %>
                An exception
          <%
             } // end else
          %>
          <%-- end scriptlet to insert fixed template data --%>
             <%-- continue error message output --%>
             occurred while interacting with the guestbook database.
          </p>
          <p class = "bigRed">
             The error message was:<br />
             <%= exception.getMessage() %>
          </p>
          <p class = "bigRed">Please try again later</p>
       </body>
    </html>
    guestBookView.jsp
    <!-- <?xml version = "1.0"?> -->
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <!-- Fig. 27.23: guestBookView.jsp -->
    <%-- page settings --%>
    <%@ page errorPage = "guestBookErrorPage.jsp" %>
    <%@ page import = "java.util.*" %>
    <%@ page import = "com.deitel.jhtp6.jsp.beans.*" %>
    <%-- GuestDataBean to obtain guest list --%>
    <jsp:useBean id = "guestData" scope = "request"
       class = "com.deitel.jhtp6.jsp.beans.GuestDataBean" />
    <html xmlns = "http://www.w3.org/1999/xhtml">
       <head>
          <title>Guest List</title>
          <style type = "text/css">
             body
                font-family: tahoma, helvetica, arial, sans-serif;
             table, tr, td, th
                text-align: center;
                font-size: .9em;
                border: 3px groove;
                padding: 5px;
                background-color: #dddddd;
          </style>
       </head>
       <body>
          <p style = "font-size: 2em;">Guest List</p>
          <table>
             <thead>
                <tr>
                   <th style = "width: 100px;">Last name</th>
                   <th style = "width: 100px;">First name</th>
                   <th style = "width: 200px;">Email</th>
                </tr>
             </thead>
             <tbody>
             <% // start scriptlet
                List guestList = guestData.getGuestList();
                Iterator guestListIterator = guestList.iterator();
                GuestBean guest;
                while ( guestListIterator.hasNext() )
                   guest = ( GuestBean ) guestListIterator.next();
             %> <%-- end scriptlet; insert fixed template data --%>
                   <tr>
                      <td><%= guest.getLastName() %></td>
                      <td><%= guest.getFirstName() %></td>
                      <td>
                         <a href = "mailto:<%= guest.getEmail() %>">
                            <%= guest.getEmail() %></a>
                      </td>
                   </tr>
             <% // continue scriptlet
                } // end while
             %> <%-- end scriptlet --%>
             </tbody>
          </table>
       </body>
    </html>Edited by: Areeba on Jul 19, 2008 10:34 PM

    Thanks I got it working. The problem was my mistake (ofcourse) I had my class in this folder WEB_INF/com/..... I did had classes folder under WE-INF . I'll get rest working soon. Thanks for the help.
    Edited by: Areeba on Jul 21, 2008 5:02 PM
    =====================
    I get this eror
    javax.servlet.ServletException: Can't call commit when autocommit=true
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
         org.apache.jsp.guestBookLogin_jsp._jspService(org.apache.jsp.guestBookLogin_jsp:172)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    javax.sql.rowset.spi.SyncProviderException: Can't call commit when autocommit=true
         com.sun.rowset.CachedRowSetImpl.acceptChanges(CachedRowSetImpl.java:886)
         com.deitel.jhtp6.jsp.beans.GuestDataBean.addGuest(GuestDataBean.java:75)
         org.apache.jsp.guestBookLogin_jsp._jspService(org.apache.jsp.guestBookLogin_jsp:145)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:291)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)on here
      rowSet.acceptChanges(); // propagate changes to databaseit updated the database but with error.
    Edited by: Areeba on Jul 21, 2008 5:23 PM
    Edited by: Areeba on Jul 21, 2008 5:57 PM

  • Type="Class"  in the jsp:useBean tag

    Hi every one
    I create a class named quiz containing four Strings question,answer1,answer2,answer3
    I initialize them in the constructor.
    I made four get methods ...getQuestion(), getAnswer1 ...and so on.
    I made the class implement the serializable interface.
    in the main i created an object of that class and stored it on a file with .ser extension and i do the following in the jsp page
    <jsp:useBean id="anyID" BeanName="name of the .ser file" type="className--i put the class name--"/>
    but he gives me classnotfoundexception for the classname in the type field.
    what can i do?
    thnx in advance.

    what can i do?Make sure that the class "quiz" is available to your web app.
    Should be under the web-inf/classes directory (in its package directory)
    Regarding your Quiz class:
    - It must be in a package
    - Also that it has a public noargs constructor:
    package myPackage
      public Quiz(){
       }This class file should be in web-inf/classes/myPackage/Quiz.class
    Hope this helps,
    evnafets

  • Constructor in javabean

    Hi Everybody,
    I am new to JSP/JavaBean. I am facing a problem with Javabean. Constructor in the javabean is called everytime when the jsp file is accessed. Is there any way that constructor is initialised only once.
    Actually i have set connection object in constructor which is closed after logout(). But when i check resources i could find lots of connection object opened.
    Constructor
    public GSKBean() throws LDAPException
    conf=new Parameters(FILE_NAME);
    this.server=conf.getStringParam("adminServer");
    auth=new AuthBean(conf);
    anon=auth.getconnect(server);
    dir_access=new DirectoryAccessBean(anon,conf);
    JSP file
    <jsp:useBean id="gsklogin" class="com.GSKUtil.GSKBean"/>
    Can anyone tell me will Constructor from class GSKBean will be called everytime when JSP page is called.
    Do i have to give scope=session or something so that connection object could be reduced.
    What the alternative.
    thanks in advance.

    Hi,
    Thanks Greg for you kind Co-operation. I am in a dilema. Can i use scope=application, as session scope instantiate the class per session and as an Internet Application opening Connection Objects per session would consume more resources. Hence i am thinking will it be better if we keep scope=application. In this scope class instance would be instantiated only once keeping connection object only one the first time when its instantiated. But i need to know would that effect client accessing function of that class simultaniously. What will be the impact if i keep Application Scope. Is Session Scope Better option than Application Scope though Connection to Database is obtained from Bean Constructor. Is there any other convinient way to intialise connection to database so that only one connection to database is obtained. Any assistance would be highly appreciated.
    <jsp:useBean id="gsklogin" class="com.GSKUtil.GSKBean" scope="application"/>

  • Error trying to use jsp:useBean

              I am trying to use a class in a JSP that is basically a connection to an
              Oracle database. It works fine when used from a servlet. However, when I try
              to instantiate it from a JPS page, I get errors. Here is the snippet from
              the JSP page:
              <%@ page import="engr.projmgmt.*" %>
              <jsp:useBean id="OB" class="engr.projmgmt.OracleBroker" />
              The class is here:
              /usr/local/apache/servlets/engr/projmgmt/OracleBroker.class
              The weblogic class path contains /usr/local/apache/servlets.
              I get the following error in the weblogic log:
              Mon Aug 13 17:39:15 PDT 2001:<E> <ServletContext-General> Servlet failed
              with Exception
              java.lang.ClassNotFoundException: class engr.projmgmt.OracleBroker :
              java.lang.IllegalAccessException: engr/projmgmt/OracleBroker
              at java.beans.Beans.instantiate(Beans.java:215)
              at java.beans.Beans.instantiate(Beans.java:55)
              at jsp_servlet._PM._index._jspService(_index.java:90)
              at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
              at
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
              :120)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:915)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:879)
              at
              weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContext
              Manager.java:269)
              at
              weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:365)
              at
              weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:253)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:129)
              --------------- nested within: ------------------
              weblogic.utils.NestedRuntimeException: cannot instantiate
              'engr.projmgmt.OracleBroker' - with nested exception:
              [java.lang.ClassNotFoundException: class engr.projmgmt.OracleBroker :
              java.lang.IllegalAccessException: engr/projmgmt/OracleBroker]
              at jsp_servlet._PM._index._jspService(_index.java:92)
              at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
              at
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
              :120)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:915)
              at
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              l.java:879)
              at
              weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContext
              Manager.java:269)
              at
              weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:365)
              at
              weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:253)
              at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:129)
              Anyone have anyideas?
              Thanks,
              CC
              

    I appears that your default constructor is not publicly accessible from the
              exception.
              Sam
              "Chuck Carson" <[email protected]> wrote in message
              news:[email protected]...
              >
              > I am trying to use a class in a JSP that is basically a connection to an
              > Oracle database. It works fine when used from a servlet. However, when I
              try
              > to instantiate it from a JPS page, I get errors. Here is the snippet from
              > the JSP page:
              >
              > <%@ page import="engr.projmgmt.*" %>
              > <jsp:useBean id="OB" class="engr.projmgmt.OracleBroker" />
              >
              > The class is here:
              > /usr/local/apache/servlets/engr/projmgmt/OracleBroker.class
              > The weblogic class path contains /usr/local/apache/servlets.
              >
              > I get the following error in the weblogic log:
              >
              > Mon Aug 13 17:39:15 PDT 2001:<E> <ServletContext-General> Servlet failed
              > with Exception
              > java.lang.ClassNotFoundException: class engr.projmgmt.OracleBroker :
              > java.lang.IllegalAccessException: engr/projmgmt/OracleBroker
              > at java.beans.Beans.instantiate(Beans.java:215)
              > at java.beans.Beans.instantiate(Beans.java:55)
              > at jsp_servlet._PM._index._jspService(_index.java:90)
              > at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
              > :120)
              > at
              >
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              > l.java:915)
              > at
              >
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              > l.java:879)
              > at
              >
              weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContext
              > Manager.java:269)
              > at
              >
              weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:365)
              > at
              > weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:253)
              > at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:129)
              > --------------- nested within: ------------------
              > weblogic.utils.NestedRuntimeException: cannot instantiate
              > 'engr.projmgmt.OracleBroker' - with nested exception:
              > [java.lang.ClassNotFoundException: class engr.projmgmt.OracleBroker :
              > java.lang.IllegalAccessException: engr/projmgmt/OracleBroker]
              > at jsp_servlet._PM._index._jspService(_index.java:92)
              > at weblogic.servlet.jsp.JspBase.service(JspBase.java:27)
              > at
              >
              weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubImpl.java
              > :120)
              > at
              >
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              > l.java:915)
              > at
              >
              weblogic.servlet.internal.ServletContextImpl.invokeServlet(ServletContextImp
              > l.java:879)
              > at
              >
              weblogic.servlet.internal.ServletContextManager.invokeServlet(ServletContext
              > Manager.java:269)
              > at
              >
              weblogic.socket.MuxableSocketHTTP.invokeServlet(MuxableSocketHTTP.java:365)
              > at
              > weblogic.socket.MuxableSocketHTTP.execute(MuxableSocketHTTP.java:253)
              > at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:129)
              >
              >
              > Anyone have anyideas?
              >
              > Thanks,
              > CC
              >
              >
              

  • Calling Beans Constructor

    HI
    My question is two fold
    1. when we use a bean like <jsp:useBean....> we create the object with no arguments
    constructor, is there a way to construct an object with arguments here itself, i cant call
    the argumented constructor fromk the no args coz i need to supply args there.
    2. Is there a way in which an object instantiated (not as a bean) in one jsp can be used
    in another?
    Thanks

    HIHi
    >
    My question is two foldHere are my suggestions
    >
    1. when we use a bean like <jsp:useBean....> we create
    the object with no arguments
    constructor, is there a way to construct an object
    with arguments here itself, i cant call
    the argumented constructor fromk the no args coz i
    need to supply args there.
    You cannot use the parameterized constructor. But you can achieve the same effect. You can write setter methods for the attributes you need to pass in constructor. In jsp you can use useBean tag as:
    <jsp:useBean id="<instance name>" ... >
    <jsp:setProperty name="<instance name as in useBean>"
    property="<property Name like income>" ... />
    </jsp:useBean>
    In this case the method set<PropertyName> (in eg setIncome) will be invoke after calling the default constructor. Thus you get ensure that the object is in required state.
    2. Is there a way in which an object instantiated (not
    as a bean) in one jsp can be used
    in another? yes.
    you can put it into Http Session object.
    HttpSession session=request.getSession(); //request is object of HttpServletRequest which is available in JSP
    session.setAttribute("MyObject",<Object you need to access>);
    Now you can access the same object in else where invoking getAttribute(String) method of Session class
    ThanksHope so it solves your problem
    Cheers
    abhishek

  • UseBean tag gives error please help

    Hi,
    I keep getting an error in my browser regarding the java.util.Collection class I am including in my jsp page.
    <%@ page import="java.util.*, src.com.database.*, src.com.data.*, src.com.business.*" %>
    <jsp:useBean id="persons" scope="request" class="java.util.Collection" />I see the following error:
    The value for the useBean class attribute java.util.Collection is invalid
    The collection is not empty because back on the server I loop over the collectiion and see a lot of data.
    When I import a String class like this it works fine:
    <jsp:useBean id="errorMsg" scope="request" class="java.lang.String" />I use tomcat 6.0.10 and java 1.6.0
    Thanks for any help,
    Jarno

    You can use only bean, not a class.A bean is actually a class ;)
    The point is that the declared class should have at least an no-arg constructor and thus is instantiable (e.g. SomeObject someObject = new SomeObject(); must be possible). An interface doesn't confirm this requirement as you simply cannot instantiate interfaces.

  • How do I change or access the setProperty of useBean from the Java class?

    I'm learning JSP beans. Let's say I've got this JSP:
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>JSP Page</title>
    </head>
    <body>
         <h1>Hello World!</h1>
         <jsp:useBean id="b" scope="page" class="consumidor.BuscaItems">
              <jsp:setProperty name="b" property="what" value="something"/>
         </jsp:useBean>
         <p><jsp:getProperty name="b" property="what"/></p>
    </body>
    </html>And this BuscaItems.java class :
    package consumidor;
    public class BuscaItems {
         public String what="Not defined";
         //Constructor
         public BuscaItems(){
              what="THIS IS WHAT I WANT";
         public void setWhat(String a){
              what=a;
         public String getWhat(){
              return what;
    }But the website returns "something" and not "THIS IS WHAT I WANT", Is this possible?

    I'm sorry for my ignorance about what a constructor is. Thank you for clarifying me the things.
    package consumidor;
    public class BuscaItems {
         public String what="Not defined";
         //Constructor
         public BuscaItems(){
         public void setWhat(String a){
              // Imaginary process to get what I want
              String result="This is what I want";
              what=result;
         public String getWhat(){
              return what;
    }

  • RE: Strange behavior with initialization in  jsp:useBean tags? (wl 5.1 sp6/8 on sol 8)

    Hello,
              I am trying to initialize a session scope bean using the <jsp:useBean ..>
              Init Code </jsp:useBean>
              syntax. This works fine for the initial page load -- the information in the
              bean
              is there and everything looks fine. However, when I do a reload of the page,
              then all of the information on the bean disappears. The setter methods of
              the
              bean are not getting invoked, nor are the beans constructers.
              However, one thing that I do notice is that after I modify the page, then
              in the WL output I see constructors called for the beans that I am using,
              then I see the compilation directive for the changed JSP. It almost looks
              like WL is creating some beans with the default constructors, then
              when my page loads, it creates some other beans using the initialization
              code.
              After a reload, it then stops using the beans that have been initialized and
              then uses those that have been created with the normal default constructors.
              This is on WL5.1 sp6 on Solaris 8. I also tried with sp8 but there
              was no difference in behavior.
              If anyone has any pointers I would appreciate it. I had thought that 5.1
              was up to the 1.1 JSP spec, but maybe I was mistaken. FWIW,
              here is the init code I am using:
              <jsp:useBean id="myFoo" scope="session" class="com.foo">
              FooDAO dao = new FooDAO();
              ArrayList listOfFoos = dao.getAllFoos(1);
              myFoo = (Foo) listOfFoos.get(0));
              </jsp:useBean>
              This snippet is being statically included with a <%@ include file %>
              by the page that I am invoking.
              Regards,
              Nathan
              [email protected]
              

    .... add the session binding interface to assist in your debugging. Post
              your results. It sounds like you are losing the session, but who knows ...
              Peace,
              Cameron Purdy
              Tangosol, Inc.
              http://www.tangosol.com
              +1.617.623.5782
              WebLogic Consulting Available
              "Nathan Cuka" <[email protected]> wrote in message
              news:[email protected]...
              > Hello,
              >
              > I am trying to initialize a session scope bean using the <jsp:useBean ..>
              > Init Code </jsp:useBean>
              > syntax. This works fine for the initial page load -- the information in
              the
              > bean
              > is there and everything looks fine. However, when I do a reload of the
              page,
              > then all of the information on the bean disappears. The setter methods of
              > the
              > bean are not getting invoked, nor are the beans constructers.
              >
              > However, one thing that I do notice is that after I modify the page, then
              > in the WL output I see constructors called for the beans that I am using,
              > then I see the compilation directive for the changed JSP. It almost looks
              > like WL is creating some beans with the default constructors, then
              > when my page loads, it creates some other beans using the initialization
              > code.
              > After a reload, it then stops using the beans that have been initialized
              and
              > then uses those that have been created with the normal default
              constructors.
              >
              > This is on WL5.1 sp6 on Solaris 8. I also tried with sp8 but there
              > was no difference in behavior.
              >
              > If anyone has any pointers I would appreciate it. I had thought that 5.1
              > was up to the 1.1 JSP spec, but maybe I was mistaken. FWIW,
              > here is the init code I am using:
              >
              > <jsp:useBean id="myFoo" scope="session" class="com.foo">
              > FooDAO dao = new FooDAO();
              > ArrayList listOfFoos = dao.getAllFoos(1);
              > myFoo = (Foo) listOfFoos.get(0));
              > </jsp:useBean>
              >
              > This snippet is being statically included with a <%@ include file %>
              > by the page that I am invoking.
              >
              > Regards,
              >
              > Nathan
              > [email protected]
              >
              >
              

  • Error while calling a super class public method in the subclass constructor

    Hi ,
    I have code like this:
    CLASS gacl_applog DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
                create_new_a
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXPORTING  pfx_log_hndl TYPE balloghndl
                   EXCEPTIONS error
    ENDCLASS.
    CLASS gacl_applog IMPLEMENTATION.
      METHOD create_new_a.
        DATA: ls_log TYPE bal_s_log.
      Header aufsetzen
        MOVE pf_extnumber TO ls_log-extnumber.
        ls_log-object     = pf_obj.
        ls_log-subobject  = pf_subobj.
        ls_log-aluser     = sy-uname.
        ls_log-alprog     = sy-repid.
        ls_log-aldate     = sy-datum.
        ls_log-altime     = sy-uzeit.
        ls_log-aldate_del = ls_log-aldate + 1.
        CALL FUNCTION 'BAL_LOG_CREATE'
             EXPORTING
                  i_s_log      = ls_log
             IMPORTING
                  e_log_handle = pfx_log_hndl
             EXCEPTIONS
                  OTHERS       = 1.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID      sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH    sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    CLASS gcl_applog_temp DEFINITION INHERITING FROM gacl_applog.
      PUBLIC SECTION.
        DATA: log_hndl   TYPE balloghndl READ-ONLY
            , t_log_hndl TYPE bal_t_logh READ-ONLY
        METHODS: constructor
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXCEPTIONS error
               , msg_add      REDEFINITION
               , display      REDEFINITION
    ENDCLASS.
    CLASS gcl_applog_temp IMPLEMENTATION.
      METHOD constructor.
        CALL METHOD create_new_a
               EXPORTING  pf_obj       = pf_obj
                          pf_subobj    = pf_subobj
                          pf_extnumber = pf_extnumber
               IMPORTING  pfx_log_hndl = log_hndl.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    A public method of Super class has been called from the constructor of the sub class. we are getting the syntax error :
    ' In the constructor method, you can only access instance attributes, instance methods, or "ME" after calling the constructor of the superclass…'
    Can you please suggest how to change the code with out affecting the functioanlity.
    Thank you ,
    Lakshmi.

    Hi,
    Call that method by instance of Subclass.   OR
    SUPER-->method.
    Read very useful document
    Constructors
    Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class.
    The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows:
    METHODS CONSTRUCTOR
            IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
            EXCEPTIONS.. <ei>.
    and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement.
    The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows:
    CLASS-METHODS CLASS_CONSTRUCTOR.
    and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class.
    Pls. reward if useful....

Maybe you are looking for

  • Trying to do a system recovery

    Hi, so I have an HP notebook and a few days a ago I did a system recovery to its factory settings. Problem is, when it got to the second disk, around 60% it gave an error and stopped. I dont know why, the disks look like they are in tip top shape. I

  • Oracle Intelligent Agent Not Responding

    I have installed Oracle 8.0.5.1 on RedHat Linux 6.0. I have everything running (thanks to the howto at fortwayne.com). When I try to discover the Oracle8 instance running on my linux box from an NT workstation running Oracle Enterprise Manager (OEM),

  • IPod Classic and iHome, alarm feature is not available!

    yeah, the most important feature to the ihome (even the latest version, iH8) is not available with the new ipods. i know mine works because i used to have the 30gb video. here are my troubleshooting specs: scenario 1: -set the alarm for a minute late

  • Integration model

    Hi all I want to work in ECC only with process orders, so I have created and activated the order model. The problem is that, I can't transfer the order from APO to ECC because of the system message: there is no planned order model.........if I active

  • For no reason Afaria App Store pop-up

    Hi, At one of our customers a couple of iPhone users are getting a pop-up message if they'd like to install the Afaria client from the app store. We don't have Afaria running here and we don't centrally manage the iPhone. We just gave every user ther