Using variables in a jsp:useBean tag

I was wondeing if it is possible in any way to use variables in a jsp:useBean tag. Here is an example of what I am trying to do.
<%
String beanType = request.getParameter( "bean" );
if( beanType.equals( "Bean1" ) ) {
beanClass = "com.myCompany.Bean1";
} else {
beanClass = "com.myCompany.Bean2";
%>
<jsp:useBean name="<%= beanType %>" class="<%= beanClass %>"/>
I also tried using this approach
<%
if( beanType.equals( "Bean1" ) ) {
%>
<jsp:useBean id="bean" class="com.myCompany.Bean1"/>
<%
} else if( beanType.equals( "Bean2" ) ) {
%>
<jsp:useBean id="bean" class="com.myCompany.Bean2"/>
<%
%>
Neither approach seems to work. Is there any way around this problem?
Thanks,
Marcus.

Hi,
check:
http://forum.java.sun.com/thread.jsp?forum=45&thread=398998&tstart=75&trange=15

Similar Messages

  • Unable to use jsp:useBean tag

    when I use
    <jsp:useBean id="addressBean" class="AddressBean" scope="session"/>
    I get the following error
    Exception Details: org.apache.jasper.JasperException
    Unable to compile class for JSP No Java compiler was found to compile the generated source for the JSP. This can usually be solved by copying manually $JAVA_HOME/lib/tools.jar from the JDK to the common/lib directory of the Tomcat server, followed by a Tomcat restart. If using an alternate Java compiler, please check its installation and access path.
    So my question is how to use the <jsp:useBean> tag in JSC

    Please see my message How to set developer's mode for oracle jsp engine.
    As a very early warning of the future, this way of setting configuration paramemter in web.xml for oracle jsp engine will be deprecated in the next major version of oc4j and desupported probably later on. Yes, it is still supported in 10.1.3 and the next major version, though.

  • Need help with the jsp:useBean tag

    Dear Fellow Java/JSP developers:
    I am trying to use the <jsp:useBean> tag in a jsp that displays the values from a javaBean that gets populated by another class.
    <%@ page contentType="text/html" pageEncoding="UTF-8"%>
    <%@ page import = "java.util.ArrayList"%>
    <%@ page import = "java.util.Iterator"%>
    <%@ page import = "salattimes.CalendarParse" %>
    <%@ page import = "salattimes.Salat" %>
    <!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>
            <jsp:useBean id="test" scope="session" class="calendar.Time" />
            <% CalendarParse sTime = new CalendarParse();
                Time mytime = sTime.runExample();%>
            <%=mytime.getA() %>
            <%=mytime.getB() %>
            <%=mytime.getC() %>
            <%=mytime.getD() %>
            <%=mytime.getE() %>
        </body>
    </html>However, up to now, I am only able to display the values on my JSP page using the scriptlet
    <% CalendarParse sTime = new CalendarParse();
                Time mytime = sTime.runExample();%> to declare and create the object (the method call sTime.runExample(); populates the fields in the Java Bean), and the expressions:
    <%=mytime.getA() %>
             <%=mytime.getB() %>
             <%=mytime.getC() %>
             <%=mytime.getD() %>
             <%=mytime.getE() %>to present the values on the screen. What I would like to do is assign the object that I create to a javaBean reference declared in a <jsp:useBean> tag as follows:
    <jsp:useBean id="test" scope="session" class="calendar.Time" />
            <% CalendarParse sTime = new CalendarParse();
                test = sTime.runExample();%>and then present the values stored in the bean to the JSP page as follows:
    <jsp:getProperty name="test" property="a" />
            <jsp:getProperty name="test" property="b" />
            <jsp:getProperty name="test" property="c" />
            <jsp:getProperty name="test" property="d" />
            <jsp:getProperty name="test" property="e" />
            <jsp:getProperty name="test" property="f" />Is this possible? When I try the above, I get "null" as my output on the screen. When I try the first approach listed above, I get the values I am looking for. Is there a way to accomplish this using the <jsp:useBean> approach?
    Thanks to all those who reply.
    Sincerely;
    Fayyaz

    The code:
    <jsp:useBean id="calendar" class="calendar.CalendarParse" scope="session"/>
    <c:set var="time" value="${calendar.time}"/>Would be roughly equivalant to:
    calendar.CalendarParse calendar = new calendar.CalendarParse();
    Object time = calendar.getTime();I assumed that the CalendarParse object was in the calendar package because that was were your Time class was (when you used <jsp:useBean id="test" scope="session" class="calendar.Time" />"), but when I look back at your original post I see I was wrong and the use of calendar as both the incorrect package and the variable name was confusing. To make the code more similar to your original post the code should have read:
    <jsp:useBean id="sTime" class="salattimes.CalendarParse"/>
    <c:set var="myTime" value="${sTime.time}" scope="session"/>
    ${myTime.a}
    ${myTime.b}
    ${myTime.c}
    etc...Here is an explanation of the parts:
             /* name of the variable */  /* fully qualified class name, package.className */
    <jsp:useBean id="sTime"           class="salattimes.CalendarParse"/>
      /* name of the new object from bean */  /* source of object, variable.property */    /* Scope of new object */
    <c:set var="myTime"              value="${sTime.time}"             scope="session"/>
    /* data to display variable.property */
    ${myTime.a}Where a 'property' in a bean is defined as a method in the form of getProperty(). So the 'time' property is getTime() and the 'a' property is getA().

  • How can i load A gui JTable bean through jsp:useBean tag in a jsp page

    Hi,
    i am chiranjit , i am in a jsp project . i am desparately looking a solution for below stated problem:
    i want to make a jsp page for master entry , that why i want to load a GUI Java bean in my jsp page.This GUI Bean contaning a JTable in which allow grid type data entry in the jsp page. But i am unable load that bean in the jsp page through jsp:useBean tag in my page.So if you have any solution then send in the forum as early as possible.
    Thank you
    chiranjit

    No can do. JSPs can only output plain HTML (and javascript...) They are not used like normal Java classes.
    If you need a complex GUI then you might use an Applet instead. If you want to use a JSP then you are stuck using normal HTML components, like <table> <form...> <input type="text"> etc...

  • 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 ?

  • How to Implement jsp:useBean tags

    Hi,
    I hav a trouble with using the Tag jsp:useBean
    Actually im using Tomcat4.1 webserver'
    I created a java file and compiled that
    When i included that class file,The Jsp Compiler seeming me a error that the Required class in not found
    Actually wht my problem is that i cannot find out the storage locations for the corresponding files
    I know where to save the jsp
    but i need to know where to put the class file and its source.Bcz that one which i want to use in that tag{<jsp:useBean>}
    I want to know what should i do
    With Regards
    Ganesh B

    Beans are regular Java classes that follow particular conventions defined by the JavaBean's specification. The don't extend from a particular class, they aren't packaged in a particular package, and - germane to the question - they aren't located in a special place on the server. The classes which are loaded into the JSP by the <jsp:useBean> construct are located in the same location as other classes in a web application. They are located in the classes directory of the WEB-INF directory of the web application directory itself. Or, if you bundle your classes into a jar file, then the jar file will be located in the lib directory of the WEB-INF directory. In either case, remember to use packages for your classes including your beans.

  • JSP - useBean tag works only for first request

     

    hey why donnu change the scope to PAGE, give a try.........
              Vishal Vishnoi wrote:
              > Using Weblogic 5.1 I am trying to work with a simple example of a JSP
              > page which has got a usebean tag. The tag is
              >
              > <jsp:useBean id="resourceTypes" type="java.util.ArrayList"
              > scope="request" />
              >
              > * This works only the first time I load the page.
              >
              > If I try to load the page again. I get the following error
              >
              > javax.servlet.ServletException: Could not find bean 'resourceTypes',
              > type 'java.
              > util.ArrayList' in scope
              >
              > --Vishal
              

  • Question about the jsp:useBean tag

    Hi, I'm a relative newcomer to jsp, but the following piece of javascript code has me very confused:
    <%@ page import="com.jinsoft.bank.web.*" %>
    <jsp:useBean id="account" class="AccountBean" />
    This will result in java.lang.ClassNotFoundException, and it complains that AccountBean cannot be found.
    However, when I fully qualify the class, it works:
    <%@ page import="com.jinsoft.bank.web.*" %>
    <jsp:useBean id="account" class="com.jinsoft.bank.web.AccountBean" />
    Am I doing something wrong?
    Isn't the import tag supposed to help?
    Thanks for any help!

    Hi Kim
    I'm really interested in the particular error that you are generating. I tried this out using Tomcat 3.2.3 and it doesn't seem to be a problem. What application Server are you using?
    Another way to find out if the problem is with the Application Server is to check the .java file that is created out of the jsp page before it is compiled. Individual Application servers have different ways of storing this intermediate .java file but most of them keep it if the compilation does not succeed.
    You may possibly have to file a bug if everything else checks out fine. Another point, are you able to import the same bean into a Servlet and use it there?
    Keep us posted.
    Good Luck!
    Eshwar Rao
    Developer Technical Support
    Sun microsystems inc
    http://www.sun.com/developers/support

  • 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]
              >
              >
              

  • 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

  • How use bean of array with tag "jsp:useBean"??

    hi,all
    a bean of array put request with a servlet and forward a jsp page,this jsp use "jsp:useBean" of tag get the bean of array.
    how do for jsp:useBean of tag??
    thx.....

    You can't use an array directly in a jsppage. first u have to write the line <useBean /> through which you can access youtr class
    <jsp:useBean id="email" class="Pack.Email" scope="session" />
    after writing this line you have your class in your hand, you can think of "email" as it is a class object of Email class which is a Bean...
    declare a private array in the Bean and then made method getArray() which will return an array ... then you can use your array in jsp....
    an example of using a class variable in JSp is given below
    public String[] getArray() // note method must be public
    return array;
    now in your jsp page you have to use that class with
    <jsp:useBean id="email" class="Pack.Email" scope="session" />
    and cnow you can use array like this....
    <%
    String[] array=email.getArray();
    for (int i=0; i< array.length;i++ )
    out.println(array]);
    %>
    Does it solve your problem now ?

  • How to use "scope " attrubute in useBean tag

    Can anyone please tell me if I can use the same JavaBean Class to hold information form different pages? well, let me explain exactely what I want to do:
    I have a Java bean Class that holds a property 'Name':
    package ContactManager;
    public class Person {
    private String name="%";
    public String getName () {
    return this.name;
    public void setName (String my_name) {
    name = my_name + "%" ;
    I'm using this class to store temporarly the Criteria of search from a JSP/HTML page to send to a database for search and for UPDATE -> this of course is done in different HTML/JSP pages. The problem I have is that the first time I set the properties (when the user make a search) this value remains unchanged [-> the second time when the user asks for update, I try to use the same bean to keep the value => unfortuntly it returns me the old value]
    My question is: is the use of 'scope' attribute of the "jsp:useBean" tag can solve this problem? if yes how to use it? I've tryed to set the scope of the bean to page but that does not help :-(
    Pleaze help, I'm stuck.... Bellow is the 4 JSP pages for:
    - person_search.jsp / person_result.jsp
    - request_modify.jsp/ DoModify.jsp
    1 -person_search.jsp
    <%@ page import="java.sql.*" %>
    <HTML>
    <HEAD><TITLE>Person Search</TITLE></HEAD>
    <BODY><CENTER>
    <form method="POST" action="person_result.jsp">
    Name <input type="text" name="name" size="47"></p>
    <input type="submit" value="Submit" name="B1">
    <input type="reset" value="Reset" name="B2"></p>
    </form></body>
    </html>
    2- person_result.jsp
    <%@ page import="java.sql.*" %>
    <HTML><BODY>
    <jsp:useBean id="theBean" class="ContactManager.Person"/>
    <jsp:setProperty name="theBean" property="*" />
    Name<BR>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    %>
    <%
    try {
    Connection con = DriverManager.getConnection("jdbc:odbc:ContactManager");
    Statement s = con.createStatement();
    String sql = "SELECT Client.ClientID, Client.Name FROM Client where Client.Name like " + "'" + theBean.getName() + "'";
    ResultSet rs = s.executeQuery(sql);
    while (rs.next()) {
    String myId = rs.getString(1);
    %>
    <TR>
    <TD><%= myId %></TD>
    <TD><a href="person_detail.jsp?id=<%= myId %>"><%=rs.getString(2)%></a></TD>
    <TD><a href="delete_person.jsp?id=<%= myId %>">Delete</a></TD><BR>
    </TR>
    <%
    rs.close();
    s.close();
    con.close();
    catch (SQLException e) {
    System.out.println(e.toString());
    catch (Exception e) {
    System.out.println(e.toString());
    %>
    </BODY>
    </HTML>
    3- request_modify.jsp
    <%@ page import="java.sql.*" %>
    <html>
    <head><title>AddressBook: Modifying Person <%= request.getParameter ("id") %></title> </head>
    <body bgcolor="#ffffee">
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    %>
    <%
    int rowsAffected = 0;
    try {
    Connection con = DriverManager.getConnection("jdbc:odbc:ContactManager");
    Statement s = con.createStatement();
    String sql = "SELECT Client.ClientID, Client.Name FROM Client where ClientID ="+ request.getParameter("id");
    ResultSet rs = s.executeQuery(sql);
    if (rs.next()) {
    %>
    Client Name is <input type=text name=name value=<%= rs.getString(2) %>> <br>
    <TD><a href="person_do_modify.jsp?id=<%= rs.getString(1)%>">Confirm Modify</a></TD>
    <%
    rs.close();
    s.close();
    con.close();
    catch (SQLException e) {
    System.out.println(e.toString());
    catch (Exception e) {
    System.out.println(e.toString());
    %>
    </BODY> </HTML>
    4- do_modify.jsp
    <%@ page import="java.sql.*" %>
    <html>
    <head><title>AddressBook: Modifying Address <%= request.getParameter ("id") %></title></head>
    <body bgcolor="#ffffee">
    <jsp:useBean id="theBean" class="ContactManager.Person" scope="page"/>
    <jsp:setProperty name="theBean" property="name"/>
    <%
    try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("JDBC driver loaded");
    catch (ClassNotFoundException e) {
    System.out.println(e.toString());
    %>
    <%
    int rowsAffected = 0;
    try {
    Connection con = DriverManager.getConnection("jdbc:odbc:ContactManager");
    PreparedStatement preparedStatement = con.prepareStatement ("UPDATE Client SET Name=? WHERE ClientID =?");
    preparedStatement.setString (1, theBean.getName());
    preparedStatement.setString (2, request.getParameter("id"));
    rowsAffected = preparedStatement.executeUpdate ();
    preparedStatement.close ();
    if (rowsAffected == 1) {
    %>
    done
    <%
    else{
    %>
    Not Modified
    <%
    con.close();
    catch (SQLException e) {
    System.out.println(e.toString());
    catch (Exception e) {
    %>
    </BODY></HTML>
    Thank you for the help.
    Sammy

    While a quick search on the <jsp:useBean> tag and the scope attribute will probably yield more information than I can summarize in a few sentences, I'm pretty sure that using the scope="page" attribute on a bean will cause that bean to be instantiated every time the page is loaded. In order for a bean to persist longer than the existance of that page (whether you're loading a new page, or reloading the same one), you'd need to set the scope to session or application (you'd probably want session).

  • Which one better to use - jsp:useBean or import statement

    Hi,
    I just want to know that which one is better to use jsp:useBean or import statement .
    I can instantiate and call method of myclass -
    1) by importing the class through import tag in jsp as <%@page import="myclass"%. or
    2). by using <jsp:useBean tag....
    i have these two option to do the same thing. i know that basically useBean is used to call setter and getter method of bean class and but it can be used to call a normal java file that have some logic .
    so what should i used , which one is better and why?
    useBean provides scope and object instance so no need to create object by new operator. and with import you have to create an instance .
    but which tag should i use in my jsp?
    i am confused???

    ok, means i can use jsp:useBean tag for all my
    classes that are not actually bean. so it will be
    instantiated at run time and provide efficiency .No. Jsp:useBean is used for java bean components.
    >
    but when should i use import statement in my jsp and
    it happen at translation time so will it create any
    type of burden for my code if i import multiple
    classes.For non-java beans, you need to import the classes, period.
    It's not a burden, it's a necessity.

  • Why do you use jsp:useBean?

    Hi,
    I have one "simple" question :) : When or why do you are using <jsp:useBean>,<jsp:getProperty> and <jsp:setProperty>?
    For practice, I am creating a form, sends the data to a servlet and the servlet "packs" the parameter into a Bean and put this Bean into a request- or SessionScope. After that, my resultpage could access the property name of the bean with (for instance) sessionScope.Bean.name.
    I wanted to use the 3 tags above first, but after I realised the way I describes above I didn't have to use these three jsp tags. Therefore I wonder when you are using these tags.
    Thnx
    Alex

    hi
    The component model for JSP technology is based on JavaBeans component architecture. JavaBeans components are nothing but Java objects which follow a well-defined design/naming pattern: the bean encapsulates its properties by declaring them private and provides public accessor (getter/setter) methods for reading and modifying their values.
    Before you can access a bean within a JSP page, it is necessary to identify the bean and obtain a reference to it. The <jsp:useBean> tag tries to obtain a reference to an existing instance using the specified id and scope, as the bean may have been previously created and placed into the session or application scope from within a different JSP page. The bean is newly instantiated using the Java class name specified through the class attribute only if a reference was not obtained from the specified scope. Consider the tag:
    sun site

  • Running jsp using Beans (jsp:useBean) on Tomcat 3.2.1 on Linux 7.0

    Hi all,
    In which folder do I keep my java bean class files so that my jsp can use jsp:useBean tag while my jsp's are stored in /webapps/examples/jsp/seet folder.
    Thanks in advance.
    Seetesh

    If their just .class files put them into /webapps/project/WEB-INF/classes
    If they're packaged as a JAR put them into /webapps/project/WEB-INF/lib
    These folders are automatically added to Tomcats classpath.

Maybe you are looking for