Why do we need jsp:useBean???

Hi All,
I am going over both the J2EE tutorial and JSP1.2 spec.
As far as I read, it seems to me that "jsp:useBean" is a way of creating a bean object.
<jsp:useBean id="local" scope="application" class="Mylocales">
If I put the class file in the import statement, can I create the object in the scriptlet
<% Mylocales local = new Mylocales(); %>
and set/get properties by calling
local.setName(); // assume these methods are in the class
local.getName();
without using "jsp:setProperty" and "jsp:getProperty".In this way, isn't it a redundancy to have "jsp:useBean" in JSP spec? We can always create any kind of objects in the scriptlets.
Since "jsp:useBean" has been there for years, I believe something must be wrong with my rationale. However, both the spec and the tutorial couldn't answer this question. Can anyone clear it up to me?
Thx in advance.
Kevin

There's nothing wrong with your rationale; useBean IS a redundant tag, but it does provide some compact functionality without having to write extra code.
http://java.sun.com/products/jsp/tags/11/syntaxref1115.html covers the syntax of this tag; one advantage of using this tag is the 'scope' attribute, that allows you to define, at object creation, just how long the object will be around. You can limit an object's scope to the page that declared it, or allow it to be accessed by any page that shares the same session, or request, or application.
I do believe that the main point of this tag comes in at the design level; one of the strongest reasons to use JSPs at all is to separate out the application logic from the page presentation. This means that anyone who can use HTML should be able to maintain the JSP pages in the application. Instead of having to teach a non-programmer a little bit of code, just demonstrate the use of a single tag that can be reused throughout the application. The logical extension of this idea is the tag library.
Myself, I mix and match as needed, but there are never more than a few lines of scriptlet code in my JSP pages. If there's more code than HTML in my JSP page, I'll go ahead and use a servlet instead.
Anyway, I guess my point is that JSP pages are flexible, you can pick the functionality that you want to use, and the useBean tag isn't quite superfluous.

Similar Messages

  • 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

  • Why do I need JSP, Servlets, JSF?

    I want to design web pages in HTML and Javascript and use EJBs to handle business logic. That's it. I don't want to learn another API (ie JSP, Servlets, ...) for designing web pages. Is there a way I can access EJBs from Javascript using XML-based messaging or some other means? JSP seems like a waste.

    Hi,
    JSP is just like HTML mix with JAVA codes. You can mix it with servlets, as you can use servlets to access methods within your EJB. You can call a servlet from within your JSP. Use your JSP as presentation and use the servlets to get data from the EJB and pass it on to your presentation to display it to user. I am not sure of any other way. If you are trying to use Java application server as your server. Then, you have to follow the rules. Otherwise, use another technology such as HTML with ASP or even .NET. So you may have to install IIS as the server. OK
    eve

  • Why use jsp:useBean?

    I got the below sample code in sun document. Here bookId is passed as a parameter in cart.remove method and sql query. I want to know why the statement "<jsp:useBean id="bookId" type="java.lang.String" /> " is used.
    <c:set var="bookId" value="${param.Remove}"/>
    <jsp:useBean id="bookId" type="java.lang.String" />
    <% cart.remove(bookId); %>
    <sql:query var="books"
    dataSource="${applicationScope.bookDS}">
    select * from PUBLIC.books where id = ?
    <sql:param value="${bookId}" />
    </sql:query>
    thanks,
    Vinodh

    The useBean tag has a side effect of creating a local scriptlet variable with the id "bookId"
    This variable is then used on the next line in the scriptlet code.
    In effect, it is executing the following code
    <c:set var="bookId" value="${param.Remove}"/>
    <%
    String bookId = (String)pageContext.findAttribute("bookId");
    cart.remove(bookId); %>which if you think about it, you could get rid of the <c:set> and have the scriptlet code access the variable directly.
    <%
    String bookId = request.getParameter("Remove");
    cart.remove(bookId); %>Mixing scriptlet and JSTL code in this fashion gets confusing.
    The scriptlet code here is part of the 1% of code that can't be replaced directly by JSTL (but could be replaced by a custom function/tag)
    However it more probably belongs in a servlet/bean.

  • Need help on jsp:useBean

    My JSP code that calls the bean is as follows:
    <%@ page import ="java.sql.*" %>
    <%! String loginId, logPassword; %>
    <% loginId=request.getParameter("LoginId");
         logPassword=request.getParameter ("LogPassword");%>
    <jsp:useBean id="simpleCon" scope="session" class="OSA_Java.SimpleConnection">
    <jsp:setProperty name="simpleCon" property="driver"
    value="sun.jdbc.odbc.JdbcOdbcDriver"/>
    <jsp:setProperty name="simpleCon" property="url" value="jdbc:odbc:OSA"/>
    <jsp:setProperty name="simpleCon" property="username" value=""/>
    <jsp:setProperty name="simpleCon" property="password" value=""/>
    </jsp:useBean>
    <%! Connection conObj; %>
    <% conObj=simpleCon.getCon();%>
    <% if ( conObj == null)
         { out.println ("Connection failed");return; }
    %>
    <jsp:useBean id="loginBean" scope="session" class="OSA_Java.LoginBean">
    <jsp:setProperty name="loginBean" property="con" value="<%=conObj%>"/>
    <jsp:setProperty name="loginBean" property="loginId" value="<%=loginId%>"/>
    <jsp:setProperty name="loginBean" property="logPassword" value="<%=logPassword%>"/>
    <jsp:setProperty name="loginBean" property="*" />
    </jsp:useBean>
    <html>
    <head>
    <title>Customer Orders</title>
    <h4><center>Customer Orders</center> </h4>
    </head>
    <body>
    <%
         String loginResults = loginBean.getCustomerName();
         if (loginResults != null)
              out.println ("Hello " + loginResults + "!! Welcome to this site" );
    %>
    <pre>
         Place Orders Track
    Orders Report Defects/Changes
    </pre>
    <% }
         else { %> 
              <%= "Error!!! Invalid User Name/Password" %>
              <%@ include file="Login.htm" %>
         <% } %>
    </p>
    <p>
    </p>
    <p>
    </p>
    <p>
    </p>
    </body>
    </html>
    My bean code for SimpleConnection is as follows:
    package OSA_Java;
    import java.sql.*;
    public class SimpleConnection
         public String driver, url, username, password;
         public String loginId,logPassword;
         public Connection con;
         public SimpleConnection () {}
         public void setDriver (String driver)
              this.driver = driver;
         public String getDriver ()
              return driver;
         public void setUrl (String url)
              this.url = url;
         public String getUrl ()
              return url;
         public void setUsername (String userName)
              this.username = username;
         public String getUsername ()
              return username;
         public void setPassword (String password)
              this.password = password;
         public String getPassword ()
              return password;
         public void setLoginId (String loginId)
              this.loginId = loginId;
         public String getLoginId ()
              return loginId;
         public void setLogPassword (String logPassword)
                   this.logPassword = logPassword;
              public String getLogPassword ()
                   return logPassword;
         public void setCon (Connection con)
              this.con = con;
         public Connection getCon ()
              System.out.println ("in get Con url" + con + " driver " + driver);
              if ( con == null) // Connect, if not already connected
                   try
                        //Load database driver.
                        Class.forName (driver);
                        // Establish network connection to database
                        System.out.println(driver);
                        con= DriverManager.getConnection (url, username, password);
                        System.out.println("in get url" + url);
                   } catch(Exception e)
                        System.out.println("in get Con" + e);
                   System.out.println("returning con" + con);
                   return con;
    When I load the JSP file, it prints a message "connection failed".
    and no message from SimpleConnection is printed on the server.
    Thanks
    newtojsp

    <jsp:useBean id="simpleCon" scope="session" class="OSA_Java.SimpleConnection">
    <jsp:setProperty name="simpleCon" property="driver"
    value="sun.jdbc.odbc.JdbcOdbcDriver"/>
    <jsp:setProperty name="simpleCon" property="url" value="jdbc:odbc:OSA"/>
    <jsp:setProperty name="simpleCon" property="username" value=""/>
    <jsp:setProperty name="simpleCon" property="password" value=""/>
    </jsp:useBean>
    Where is your .class file from the bean? Is it under /WEB-INF/classes/OSA_Java/SimpleConnection.class?

  • 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().

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

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

  • What am I doing wrong with the isNew() method?  and why do I need the other methods?

    I have coded an include jsp like this.
              <%@page language="Java"%>
              <%@page import="javax.servlet.http.HttpSession"%>
              <%!
              String iContextPath;
              String iCommonPath;
              String iImagesPath;
              %>
              <%
              iContextPath = request.getContextPath();
              iCommonPath = iContextPath + "/common";
              iImagesPath = iCommonPath + "/images";
              System.err.println(" here ");
              HttpSession thisSession = request.getSession( false );
              if( thisSession.isNew() ){
              System.err.println("isnew");
              response.sendRedirect( iContextPath + "/common/login.jsp" );
              %>
              Now I also have a redirect.jsp in the root of an application that contains
              this.
              <html>
              <body>
              <%
              System.err.println("Redirecting at this time from the root");
              response.sendRedirect( request.getContextPath() + "/secureArea/");
              %>
              </body>
              </html>
              And I have a logout.java servlet that looks like this.
              package com.pch.epics;
              import java.io.IOException;
              import javax.servlet.ServletException;
              import javax.servlet.http.HttpServlet;
              import javax.servlet.http.HttpServletRequest;
              import javax.servlet.http.HttpServletResponse;
              import weblogic.servlet.security.ServletAuthentication;
              public class Logout extends HttpServlet{
              private static final String CONTENT_TYPE = "text/html";
              //Initialize global variables
              public void init() throws ServletException{
              //Process the HTTP Get request
              public void doGet( HttpServletRequest request, HttpServletResponse
              response ) throws ServletException, IOException{
              String username = "";
              if( request.getUserPrincipal() == null ){
              username = "Unknown";
              } else {
              username = request.getUserPrincipal().getName();
              System.err.println( "ePics logging out '" + username + "'" );
              request.getSession( false ).invalidate();
              ServletAuthentication.logout( request );
              ServletAuthentication.invalidateAll( request );
              ServletAuthentication.killCookie( request );
              response.sendRedirect( request.getContextPath() );
              //Process the HTTP Post request
              public void doPost( HttpServletRequest request, HttpServletResponse
              response ) throws ServletException, IOException{
              doGet( request, response );
              //Clean up resources
              public void destroy(){
              First of all, why won't the isNew() report a new session in the server log?
              EVERY request coming in says it's an old request (ie it's not new). The
              J2EE Applications and BEA WebLogic Server book from BEA says this should
              work.
              My second question is why do I need to do those three lines from
              ServletAuthentication to logout a user? Ok, maybe I'm from the MS world,
              but that seems excessive, especially since I've already done a
              session.invalidate() right before it, but the bea docs say I'm required to
              do all four!
              

    When you invalidate a session. You invalidate the session of the web
              application that your jsp/servlet is part of. It is possible to have more
              than one web application on WLS and have them share a authentication info.
              While these applications share authentication they do not share their
              sessions so because of that calling session invalidate does not kill all the
              sessions. ServletAuthentication is needed to kill all the sessions and do a
              complete logout from WLS.
              "Flip" <[remove][email protected]> wrote in message
              news:[email protected]...
              > I have coded an include jsp like this.
              >
              > <%@page language="Java"%>
              > <%@page import="javax.servlet.http.HttpSession"%>
              > <%!
              > String iContextPath;
              > String iCommonPath;
              > String iImagesPath;
              > %>
              > <%
              > iContextPath = request.getContextPath();
              > iCommonPath = iContextPath + "/common";
              > iImagesPath = iCommonPath + "/images";
              >
              > System.err.println(" here ");
              > HttpSession thisSession = request.getSession( false );
              > if( thisSession.isNew() ){
              > System.err.println("isnew");
              > response.sendRedirect( iContextPath + "/common/login.jsp" );
              > }
              >
              > %>
              >
              > Now I also have a redirect.jsp in the root of an application that contains
              > this.
              > <html>
              > <body>
              > <%
              > System.err.println("Redirecting at this time from the root");
              > response.sendRedirect( request.getContextPath() + "/secureArea/");
              > %>
              > </body>
              > </html>
              >
              > And I have a logout.java servlet that looks like this.
              > package com.pch.epics;
              >
              > import java.io.IOException;
              > import javax.servlet.ServletException;
              > import javax.servlet.http.HttpServlet;
              > import javax.servlet.http.HttpServletRequest;
              > import javax.servlet.http.HttpServletResponse;
              > import weblogic.servlet.security.ServletAuthentication;
              >
              > public class Logout extends HttpServlet{
              > private static final String CONTENT_TYPE = "text/html";
              > //Initialize global variables
              > public void init() throws ServletException{
              > }
              >
              > //Process the HTTP Get request
              > public void doGet( HttpServletRequest request, HttpServletResponse
              > response ) throws ServletException, IOException{
              > String username = "";
              > if( request.getUserPrincipal() == null ){
              > username = "Unknown";
              > } else {
              > username = request.getUserPrincipal().getName();
              > }
              > System.err.println( "ePics logging out '" + username + "'" );
              > request.getSession( false ).invalidate();
              > ServletAuthentication.logout( request );
              > ServletAuthentication.invalidateAll( request );
              > ServletAuthentication.killCookie( request );
              > response.sendRedirect( request.getContextPath() );
              > }
              >
              > //Process the HTTP Post request
              > public void doPost( HttpServletRequest request, HttpServletResponse
              > response ) throws ServletException, IOException{
              > doGet( request, response );
              > }
              >
              > //Clean up resources
              > public void destroy(){
              > }
              > }
              >
              > First of all, why won't the isNew() report a new session in the server
              log?
              > EVERY request coming in says it's an old request (ie it's not new). The
              > J2EE Applications and BEA WebLogic Server book from BEA says this should
              > work.
              >
              > My second question is why do I need to do those three lines from
              > ServletAuthentication to logout a user? Ok, maybe I'm from the MS world,
              > but that seems excessive, especially since I've already done a
              > session.invalidate() right before it, but the bea docs say I'm required to
              > do all four!
              >
              >
              >
              

  • Jsp:useBean and assigning a value to that bean

    Hello,
    I have a type called Country and I have declared a bean using the "jsp:useBean" syntax.
    I then try to assign a value to that bean in a scriptlet. Eventually I try to retrieve the values using "jsp:getProperty". The problem is that it appears to null.
    Here is the code of the jsp
    <%@ page language="java" %>
    <%@ page import="com.parispano.latinamericaguide.*" %>
    <%
    /* We retrieve the Countries object from the servlet context. */
    ServletContext sc = getServletContext();
    Countries cs = (Countries)sc.getAttribute("countries");
    %>
    <jsp:useBean id="country" class="com.parispano.latinamericaguide.Country"/>
    <%
    /* If the request contains a country id, then we set the variable. */
    country = cs.getCountryFromId(Integer.parseInt(request.getParameter("countryID")));
    %>
    <html>
    <head>
    <title>Country details</title>
    </head>
    <body>
    <table>
    <tr><td>Name</td><td><jsp:getProperty name="country" property="name"/><!-- This is not working--></td></tr>
    <table>
    <%
    out.println(country.getName());//This is working
    %>
    </body>
    </html>This is the code for the bean
    package com.parispano.latinamericaguide;
    * @author Julien Martin
    * Represents a country.
    public class Country implements Comparable {
         private int id;
         private String name;
         private int landArea;
         private String capital;
         private String currency;
         private String flag;
         private String internet_domain;
         private String dialling_code;
         private float literacy;
         private float male_life_expectancy;
         private float female_life_expectancy;
         private String map;
         private int population;
         private int population_year;
         private float birth_rate;
         private int birth_rate_year;
         private float death_rate;
         private int death_rate_year;
         private int gdp;
         private int gdp_per_head;
         private int gdp_year;
         private float unemployment_rate;
         private int unemployment_rate_year;
         public Country() {
         public Country(
              int id,
              String name,
              int landArea,
              String capital,
              String currency,
              String flag,
              String internet_domain,
              String dialling_code,
              float literacy,
              float male_life_expectancy,
              float female_life_expectancy,
              String map,
              int population,
              int population_year,
              float birth_rate,
              int birth_rate_year,
              float death_rate,
              int death_year_rate,
              int gdp,
              int gdp_year,
              float unemployment_rate,
              int unemployment_rate_year) {
              this.id = id;
              this.name = name;
              this.landArea = landArea;
              this.capital = capital;
              this.currency = currency;
              this.flag = flag;
              this.internet_domain = internet_domain;
              this.dialling_code = dialling_code;
              this.literacy = literacy;
              this.male_life_expectancy = male_life_expectancy;
              this.female_life_expectancy = female_life_expectancy;
              this.map = map;
              this.population = population;
              this.population_year = population_year;
              this.birth_rate = birth_rate;
              this.birth_rate_year = birth_rate_year;
              this.death_rate = death_rate;
              this.death_rate_year = death_year_rate;
              this.gdp = gdp;
              this.gdp_year = gdp_year;
              this.unemployment_rate = unemployment_rate;
              this.unemployment_rate_year = unemployment_rate_year;
         public float getBirth_rate() {
              return birth_rate;
         public int getBirth_rate_year() {
              return birth_rate_year;
         public String getCapital() {
              return capital;
         public String getCurrency() {
              return currency;
         public float getDeath_rate() {
              return death_rate;
         public int getDeath_rate_year() {
              return death_rate_year;
         public String getDialling_code() {
              return dialling_code;
         public float getFemale_life_expectancy() {
              return female_life_expectancy;
         public String getFlag() {
              return flag;
         public int getGdp() {
              return gdp;
         public int getGdp_per_head() {
              return gdp / population;
         public int getGdp_year() {
              return gdp_year;
         public int getId() {
              return id;
         public String getInternet_domain() {
              return internet_domain;
         public float getLiteracy() {
              return literacy;
         public float getMale_life_expectancy() {
              return male_life_expectancy;
         public String getMap() {
              return map;
         public String getName() {
              return name;
         public int getPopulation() {
              return population;
         public int getPopulation_year() {
              return population_year;
         public int getLandArea() {
              return landArea;
         public float getUnemployment_rate() {
              return unemployment_rate;
         public int getUnemployment_rate_year() {
              return unemployment_rate_year;
         public void setBirth_rate(float f) {
              birth_rate = f;
         public void setBirth_rate_year(int i) {
              birth_rate_year = i;
         public void setCapital(String string) {
              capital = string;
         public void setCurrency(String string) {
              currency = string;
         public void setDeath_rate(float f) {
              death_rate = f;
         public void setDeath_rate_year(int i) {
              death_rate_year = i;
         public void setDialling_code(String string) {
              dialling_code = string;
         public void setFemale_life_expectancy(float f) {
              female_life_expectancy = f;
         public void setFlag(String string) {
              flag = string;
         public void setGdp(int i) {
              gdp = i;
         public void setGdp_per_head(int i) {
              gdp_per_head = gdp/population;
         public void setGdp_year(int i) {
              gdp_year = i;
         public void setId(int i) {
              id = i;
         public void setInternet_domain(String string) {
              internet_domain = string;
         public void setLiteracy(float f) {
              literacy = f;
         public void setMale_life_expectancy(float f) {
              male_life_expectancy = f;
         public void setMap(String string) {
              map = string;
         public void setName(String string) {
              name = string;
         public void setPopulation(int i) {
              population = i;
         public void setPopulation_year(int i) {
              population_year = i;
         public void setlandArea(int i) {
              landArea = i;
         public void setUnemployement_rate(float f) {
              unemployment_rate = f;
         public void setUnemployment_rate_year(int i) {
              unemployment_rate_year = i;
         public String toString() {
              return name;
         public int compareTo(Object o) {
              Country c = (Country)o;
              int cmp = name.compareTo(c.name);
              System.out.println(cmp);
              return cmp;
    }Can anyone please help?
    Thanks in advance,
    Julien.

    Thanks,
    I have added scope="application". It still show "null" indicating that the bean is not initialized with the properties. I would like a quicker way to initialize a bean property than invoking the setProperty tag for each property.
    Here is a simple example that demonstrates the problem:
    <%@ page language="java" %>
    <%@ page import="com.tests.*" %>
    <jsp:useBean id="monBean" class="com.tests.MonBean" scope="application"/>
    <%
    MonBean mb = new MonBean();
    mb.setName("toto");
    monBean= mb;
    %>
    <html>
    <head>
    <title>Lomboz JSP</title>
    </head>
    <body bgcolor="#FFFFFF">
    <jsp:getProperty name="monBean" property="name"/>
    </body>
    </html>And the bean
    package com.tests;
    public class MonBean {
    private String name;
    public String getName() {
         return name;
    public void setName(String name) {
         this.name = name;
    }This show "null".
    Any other idea why this is not working?
    Thanks,
    Julien

  • Jsp:useBean giving error while compiling JSP's in JDeveloper

    Hello,
    I am having another problem with JSP's in JDeveloper 10.1.3. jsp:useBean and jsp:setProperty are all giving problems. I am not sure what I need to do to get rid of this error
    Thanks,
    Lakshmisri

    Your original post mentions issues with jsp:useBean and jsp:setProperty, now you're talking about tag libraries and directives. Can you be more specific about what you're trying to do? Are you having problems getting JDev to recognize a tag library or are you having problems with the tag library when running the app? What directive are you trying to use that causes the termination error?

  • Why do I need to pass params. to getConnection when using OracleDataSource?

    Hi,
    I've been experimenting with Tomcat 5.5 and using Oracle proxy sessions. After many false starts, I finally have something working, but I have a question about some of the code.
    My setup:
    In <catalina_home>/conf/server.xml I have this section:
    <Context path="/App1" docBase="App1"
    debug="5" reloadable="true" crossContext="true">
    <Resource name="App1ConnectionPool" auth="Container"
    type="oracle.jdbc.pool.OracleDataSource"
    driverClassName="oracle.jdbc.driver.OracleDriver"
    factory="oracle.jdbc.pool.OracleDataSourceFactory"
    url="jdbc:oracle:thin:@127.0.0.1:1521:oddjob"
    username="app1" password="app1" maxActive="20" maxIdle="10"/>
    </Context>
    In my App directory, web.xml has:
    <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>App1ConnectionPool</res-ref-name>
    <res-type>oracle.jdbc.pool.OracleDataSource</res-type>
    <res-auth>Container</res-auth>
    </resource-ref>
    And finally, my java code:
    package web;
    import oracle.jdbc.pool.OracleDataSource;
    import oracle.jdbc.driver.OracleConnection;
    import javax.naming.*;
    import java.sql.SQLException;
    import java.sql.ResultSet;
    import java.sql.Statement;
    import java.util.Properties;
    public class ConnectionPool {
    String message = "Not Connected";
    public void init() {
    OracleConnection conn = null;
    ResultSet rst = null;
    Statement stmt = null;
    try {
    Context initContext = new InitialContext();
    Context envContext = (Context) initContext.lookup("java:/comp/env");
    OracleDataSource ds = (OracleDataSource) envContext.lookup("App1ConnectionPool");
    message = "Here.";
    if (envContext == null)
    throw new Exception("Error: No Context");
    if (ds == null)
    throw new Exception("Error: No DataSource");
    if (ds != null) {
    message = "Trying to connect...";
    conn = (OracleConnection ) ds.getConnection("app1","app1");
    Properties prop = new Properties();
    prop.put("PROXY_USER_NAME", "xxx/yyy");
    if (conn != null) {
    message = "Got Connection " + conn.toString() + ", ";
              conn.openProxySession(OracleConnection.PROXYTYPE_USER_NAME,prop);
    stmt = conn.createStatement();
    //rst = stmt.executeQuery("SELECT 'Success obtaining connection' FROM DUAL");
    rst = stmt.executeQuery("SELECT count(*) from sch_header");
    if (rst.next()) {
    message = "# of NJ schools: " + rst.getString(1);
    rst.close();
    rst = null;
    stmt.close();
    stmt = null;
    conn.close(); // Return to connection pool
    conn = null; // Make sure we don't close it twice
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    // Always make sure result sets and statements are closed,
    // and the connection is returned to the pool
    if (rst != null) {
    try {
    rst.close();
    } catch (SQLException e) {
    rst = null;
    if (stmt != null) {
    try {
    stmt.close();
    } catch (SQLException e) {
    stmt = null;
    if (conn != null) {
    try {
    conn.close();
    } catch (SQLException e) {
    conn = null;
    public String getMessage() {
    return message;
    My question concerns this line of code:
    conn = (OracleConnection ) ds.getConnection("app1","app1");
    Why do I need to pass in the user name/password? Other examples, that I see simply have:
    conn = (OracleConnection ) ds.getConnection();
    But when I use this code, I get the following error:
    java.sql.SQLException: invalid arguments in call
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
         at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236)
         at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:414)
         at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
         at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
         at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
         at oracle.jdbc.pool.OracleDataSource.getPhysicalConnection(OracleDataSource.java:297)
         at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:221)
         at oracle.jdbc.pool.OracleDataSource.getConnection(OracleDataSource.java:165)
         at web.ConnectionPool.init(ConnectionPool.java:32)
    ... more follows, but I trimmed to keep posting shorter :-)
    Is there anyway that I can avoid having to pass the user/password to getConnection()? It seems that I should be able to control the user/password used to establish the connection pool directly in the server.xml file and not have to supply it again in my java code. In earlier experiments when I was using "import java.sql.*" and using it's DataSource, I can use getConnection() without having to pass user/password, but then the Oracle Proxy methods don't work.
    I'm a java newbie so I guess that I should be happy that I finally figured out how to get proxy connections working. However it seems that I am missing something and I want this code to be as clean as possible.
    If anyone can point me to a better method of using connection pools and proxy sessions, I would appreciate it.
    Thanks,
    Alan

    Hi,
    Thanks for the replies.
    Avi, I'm not really sure what you are getting at with the setConnectionProperties. I looked at the javadoc and saw that I can specify user/password, but since I'm using a connection pool, shouldn't my Datasource already have that information?
    Maro, your comment about not having set the user/password for the Datasource is interesting. Are you referring to setting it in the server.xml configuration file? As you can see I did specify it in addition to setting the URL. In my code example, I'm not having to respecify the URL, but maybe I have a typo in my config file that is causing the username/password not to be read properly??
    The other weird thing is that I would have expected to see a pool of connections for user App1 in V$SESSION, but I see nothing. If I use a utility to repeatedly call a JSP page that makes use of my java example, then I do see v$session contain brief sessions for App1 and ADAVEY (proxy). The response time of the JSP seems much quicker than I would have expected if there wasn't some sort of physical connection already established though. Maybe this is just more evidence of not having my server.xml configured properly?
    Thanks.

  • Jsp:useBean gives cannot be resolved to a type in Tomcat

    Hi, I am using Tomcat 5.5
    I have a simple JavaBean for test purposes :
    import java.io.Serializable;
        public class testBean implements Serializable {
            int number;
            public testBean() {
            public int getNumber() {
                return number;
            public void setNumber(int newValue) {
                number = newValue;
        }In a file called testBean.java
    I have successfuly compiled it and put the class file the WEB-INF/classes directory.
    I have the following JSP page :
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <jsp:useBean id="pub" scope="session" class="testBean" />
    <jsp:setProperty name="pub" property="number" value="1" />
    <html>
    <head>
    </head>
    <body>
    <jsp:getProperty name="pub" property="number" />
    </body>
    </html>When I open this jsp page I get the following error:
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 2 in the jsp file: /test.jsp
    Generated servlet error:
    testBean cannot be resolved to a typeThis example is pretty minimal and I don't understand why it doesn't work. The error seems to be coming from the first JSP statement.
    Any help would be greatly appreciated.
    Thanks in advance.

    1. Put your bean class in a package.
    package test;
    import...........2. Put the .class file in web-inf/classes/test/testBean.class
    3. Specify the fully qualified name of the class in the useBean declaration.
    <jsp:useBean class="test.testBean" .../>Note: You'd be better off following the java bean naming conventions. Specifically your class name should be TestBean (first letter caps).
    ram.

  • 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

Maybe you are looking for

  • Windows 7: No two finger scrolling

    Fresh install of Windows 7 on a boot camp partition.  Installed the drivers off of a snow leopard cd. Right click works, two finger scrolling doesn't. In device manager, the "Apple Trackpad" driver is dated 3/09. Any ideas?

  • Wls6.0 ldap configuration

    I've got the same problem as the college from Thu Jun 28 2001: I have configured weblogic 6.0 with the netscape directory server 4.1 but still there is a warning message in weblogic "every new user will be added to the file realm". I suppose my ldap

  • WFA 2.1+ CM Snapshot support with Unified Manager 6.0+

    Hi All, If you've come here, you may have noticed that WFA 2.1 appears to lack support of Snapshots in cDOT, and the Snapshot database view within OnCommand Unified Manager 6.0 and above is empty. This pack intends to fill that gap by providing a sep

  • Video post-processing

    I don't know anything about DSLR video but am interested in learning. LR3 has the ability to import video along with my images. But now what? Gazzilions of resources for processing images. I can't find anything on any kind of a workflow to handle the

  • How can i set this comparison in formula node

    a=[0,100] a<=5          => x=1 5<a<=10    => x=2 10<a<=95  => x=3 95<a<=98  => x=4 a>98          => x=5 Thank you. Solved! Go to Solution.