UseBean functionality

i have a servlet centric architecture where i am creating a bean in the servlet and passing it to a jsp using the setAttribute() method.
MyBean myObject = new MyBean();
myObject.setProperty1(value);
myObject.setProperty2(value);
request.setAttribute( "obj", myObject );
once it gets to my jsp, i want to get the object and maintain its persistance throughout the scope of the session. to do this, i am TRYING to use the <jsp:useBean/> tag, but it is creating a NEW object and not retrieving the one passed by the servlet.
<%@ page import="myPackage.MyBean" session="true" %>
<jsp:useBean id="obj" class="MyBean" scope="session"/>
<%
if (null != obj)
System.out.println("bean is NOT null");
else
System.out.println("bean is null");
%>
according to "Web Development with JavaServer Pages" by Fields & Kolb, pg 226 - this should be possible. if it is NOT, can someone instruct me on how to maintain the objects persistance using getAttribute()? i would prefer to use the <jsp:useBean/> tag if possible, though.

try this :
HttpSession session = request.getSession();
MyBean myObject = new MyBean();
myObject.setProperty1(value);
myObject.setProperty2(value);
//request.setAttribute( "obj", myObject );
session.setAttribute( "obj", myObject );
Retrieve using the getAttribute method of the session object

Similar Messages

  • Why do I have to declare my int outside the function?

    `Hi!
    I've writen the very simple class get_results with one methode test:
    public class Get_results {
       protected int nb=0;
    public int test(int numb) {
             //int nb=0;
             nb=numb;
             return nb;
               }//End test
    }//End classthis methode will be called from a jsp file:
    <jsp:useBean id="results" scope="session" class="mypackage.Get_results" />
    <%= results.test(3) %>I don't understand why I have to declare int nb outside the function test. If I declare int nb at the beginning of the function and not right at the beginning of the class
    public class Get_results {
    public int test(int numb) {
             int nb=0;
             nb=numb;
             return nb;
               }//End test
    }//End classthe it doesn't work. I don't understand why since I only need the int nb in the test methode and nowhere else in the class.
    can anyone explane this to me?
    thanks.
    Message was edited by:
    ChristopheD
    Message was edited by:
    ChristopheD

    I get this message:
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: 2
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:372)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    java.lang.ArrayIndexOutOfBoundsException: 2
         org.apache.jsp.grammaire_002dresults_jsp._jspService(grammaire_002dresults_jsp.java:219)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:324)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    note The full stack trace of the root cause is available in the Apache Tomcat/5.0.28 logs.
    Message was edited by:
    ChristopheD

  • How to call a bean method through a javascript function

    I dont discover any problems calling the bean method in this maner:
    <%= helpdesk.data() %>
    But, when I use a Button Onclick= to call the script function and which then is going call my bean method
    an error on the page is reported!
    I have include som code which gives you the idea of what Iam searching for. And is it possible to call
    the bean method without doing from a new jsp page?
    If you have any suggestions to why it doesnt work, please let me know.
    I use Apache Tomcat 4.0
    Best regards Micah.
    <jsp:useBean id='helpdesk' scope='application'
    class='helpdesk.testdb'/>
    <html>
    <head>
    <script language="javascript">
    function broadcast()
    helpdesk.data();
    </script>
    </head>
    <body>
    <input type="button" value="Broadcast" onclick= broadcast()>
    </body>
    </html>

    It's actually quite simple:
    Beans run server-side
    Javascript runs client-side
    So you will never be able to run server-side-code thru the client...

  • How to pass javascript variable to jsp function

    i want to check which table header (that is <th> in html )is clicked and based on that a jsp funtion do a query in database and should show records in sorted way according to which column head is clicked.
    Table is created in html.
    My function is
    Vector varray = workcaseid.getWorkcaseId(Long.parseLong(MasterAccountNumber),SelectedColumn);
    <table border="1">
              <th ><label onClick="<%SelectedColumn="workcase_id";%>">Workcase Id</label></th>
              <th><label onClick="<%SelectedColumn="status_id";%>">Status</label></th>
    <tr><td>etc</td></tr>
    </table>

    im using bean for business login, following mvc model,and i think mvc is one of good design practice to use.
    <jsp:useBean id="workcaseid" scope="session"class="beanFiles.SearchWorkcaseId" />
    varray = workcaseid.getWorkcaseId(Long.parseLong(MasterAccountNumber),SelectedColumn);
    just tell me whether it is possible to pass javascript variable to jsp variable or not.i can do it by using hidden input type,using form and submit button.

  • How to call a function from Java to JSP

    Hello,
    I have a question about using tags.
    I have a java file,which has a function. Now I want to call this function into my JSP page.
    I'm using JSP 1.2 and TOMCAT 4.1 with Java2 SDK.
    I search through the web and find a method to do this.Bu it requires JSP 2.0
    But I try that in my machine(using JSP 1.2).It gives an error:
    Did you know what is the error? Or is there any method to call a function into my JSP page?
    Please, help me to solve this.
    Here are my codes(part of them)
    UserPassword.java file
    package data;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import javax.sql.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class UserPassword
         public static String verify(String username,String password){
              // some codes
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE taglib
            PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
         "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
    <taglib>
      <tlib-version>1.0</tlib-version>
      <jsp-version>1.2</jsp-version>
      <short-name>simple</short-name>
      <uri>http://jakarta.apache.org/tomcat/HRM/WEB-INF/lib</uri>
      <description>
         A  tab library for the login
      </description>
    <function>
            <description>verify username and password</description>
            <name>verify</name>
            <function-class>data.UserPassword</function-class>
            <function-signature>String verify(java.lang.String,java.lang.String)
            </function-signature>
    </function>
    </taglib>I put this file into the webapps/HRM/WEB-INF/lib folder
    Here is my JSP file.
    <%@ page language="java" %>
    <%@ page import="data.UserPassword" %>
    <%@ page session="true" %>
    <%@ taglib prefix="login" uri="/WEB-INF/lib/LoginVerify.tld" %>
    <jsp:useBean id="useraccount" class="data.UserPassword"/>
    <jsp:setProperty name="useraccount" property="*"/>
    <%
    String status = UserPassword.verify(String username,String password);
    String nextPage = "MainForm.jsp";
    if(status.equals("InvalidU")) nextPage ="InvalidUserName.jsp";
    if(status.equals("InvalidP")) nextPage ="InvalidPassword.jsp";
    if(status.equals("main")) nextPage ="MainForm.jsp";
    %>
    <jsp:forward page="<%=nextPage%>"/>
    Here is the error:
    org.apache.jasper.JasperException: XML parsing error on file /WEB-INF/lib/LoginVerify.tld: (line 18, col -1): Element "taglib" does not allow "function" here.
         at org.apache.jasper.xmlparser.ParserUtils.parseXMLDocument(ParserUtils.java:189)
         at org.apache.jasper.compiler.TagLibraryInfoImpl.parseTLD(TagLibraryInfoImpl.java:247)
         at org.apache.jasper.compiler.TagLibraryInfoImpl.(TagLibraryInfoImpl.java:183)
         at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:354)
         at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:381)Please, help me to solve this trouble.
    Thanks.

    Yes. As serlank showed, you can just call the function easily in scriptlet tags
    However the whole point of a tag library is to avoid the use of scriptlets.
    Seeing as you can't use functions, is just to do it as a standard tag.
    ie in your jsp
    <login:verify name="<%= userName %>" password = "<%= password %>" resultVar = "status"/>
    <c:choose>
      <c:when test="${status == 'InvalidU'}">
        <c:set var="nextPage" value="InvalidUserName.jsp"/>
      </c:when>
      <c:when test="${status == 'InvalidP'}">
        <c:set var="nextPage" value="InvalidPassword.jsp"/>
      </c:when>
    </c:choose>In your case, this tag in the tld would possibly look something like this.
    You would then have to write a tag handler class that would call the function you want.
    <tag>
      <name>verify</name>
      <tagclass>com.tags.login.Verify</tagclass>
      <teiclass>com.tags.login.VerifyTEI</teiclass>  (if required)
      <bodycontent>JSP</bodycontent>
    // name attribute 
    <attribute>
          <name>name</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
        </attribute>
    // password attribute
        <attribute>
          <name>password</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
        </attribute>
    // result variable to return a response from the tag.
      <variable>
        <name-from-attribute >resultVar</name-from-attribute >
        <variable-class>java.lang.String</variable-class>
        <declare>true</declare>
        <scope>AT_END</scope>
      </variable>
    </tag>Hope this helps some, and doesn't confuse too much :-)
    Cheers,
    evnafets

  • How to call PL/SQL function from JSP ?

    We have the JSP application developed using the JDeveloper 3.0. I am trying to call the PL/SQL DB function. I'm trying to use the method of ApplicationModule:
    .getTransaction().executeCommand(sCommand)
    The problem is that I can not get the function result back to JSP. The executeCommand() does not seem to accept any host variables.
    What to do ? Did anyone manage to get the feedback from DB ?
    Here is the code in the JSP page:
    <%! String res=" ";%>
    <jsp:useBean id="rsn"
    class="oracle.jbo.html.databeans.TRSRowSetNavigator"
    scope="request" >
    <%
    rsn.initialize(application,session, request,response,
    out,"theIMO_trs_bc4J_Bc4JModule.AuctionsListView");
    rsn.setReleaseApplicationResources(true);
    // this is the ID to be copied
    String copy_id = request.getParameter(TRS.LOOK_UP_PK_FIELD);
    if( copy_id != null) {
    // call the PL/SQL procedure to create copy of this auction
    String sCommand = "DECLARE a NUMBER; BEGIN :res:=Copy_Auction("
    copy_id"); END;";
    rsn.getRowSet().getApplicationModule().getTransaction().executeCommand(sCommand);
    rsn.getRowSet().getApplicationModule().getTransaction().commit();
    I receive the following error:
    Error Message: JBO-27121: SQL error during statement execution. Statement: DECLARE a NUMBER; BEGIN :res:=Copy_Auction(45); END;
    JBO Error:JBO-27121: SQL error during statement execution. Statement: DECLARE a NUMBER; BEGIN :res:=Copy_Auction(45); END;: ORA-01008: not all variables bound
    What criteria has the host variable meet to be used in the executeCommand(sCommand) method ?
    Thanks,
    Michael
    null

    I could be wrong there, but I have experienced similar problem on tru64 unix, with sticky bit not in place for the following files: $ORACLE_HOME/bin/oracle and $ORACLE_HOME/bin/oracleO. Once you restore those files via tar command (this is what happened to me), the sticky bit disappears, and you have to re-introduce it by issuing unix command: chmod 1777 on those files.
    What it does for you - it allows you to execute the sql statements as an oracle user & group!
    Otherwise, if this bit is lost, whenever you try to connect to sqlplus via user / password it hits you back with:
    ORA-01034 ORACLE not available
    ORA-27121 unable to determine size of shared memory segment
    Compaq Tru64 UNIX Error: 13:Permission denied
    This should not be a problem if you try and execute the same sql statements using listener (connecting to the server by using @ statement).
    I could be late in response to you, but maybe not for other people.

  • Help on JSP Function

    Hi,
    I am writing follow. java function inside my JSP
    <jsp:useBean
         id="inquiryBean" class = "com.bbh.actionworld.pagingcontrol.inquiry.Inquiry" scope = "session">
    </jsp:useBean>
    <%
         int sIndex = inquiryBean.getStartIndex();
         int eIndex = inquiryBean.getEndIndex();
         int pSize = inquiryBean.getPageSize();
         out.println("sIndex= " + sIndex + "eIndex = " + eIndex + "pSize = " + pSize);
    %>
    <%!
    void getNextRecords() {
    if (sIndex == 0)
    if ((sIndex > 0) && (sIndex < dataArray.length))
    sIndex = eIndex;
    eIndex = sIndex + pSize;
    out.println("after next sIndex = " + sIndex + "eIndex = " + eIndex + "pSize = " + pSize);
    inquiryBean.setStartIndex(sIndex);
    inquiryBean.setEndIndex(eIndex);
    %>
    I'm getting errors like sIndex, eIndex , pSize ,out , inquiryBean are undefined variables in function.
    Can anybody help me ?
    Thanx in advance.
    -Priya

    do the three variables have local scope.
    i.e have you declared them within a block and are trying
    to use outside that block , if so they no longer exist in
    memory.
    just a guess.

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

  • Calling JSP bean function on button OnClick

    Hi-
    A NewBie question....
    I have a .jsp page and supporting .java bean.
    I registed the bean in .jsp page using <jsp:useBean ...>
    I want to fire a function defined in that bean on the click of a button which is defined in the .jsp page
    So I am doing something like this... seems like not the correct way to do since it fires this script all the time, not just when the button is clicked.
    <input name='click1' type='Submit' value='Click1' onClick='<% testBean.click1Clicked (); %>'/>
    Thanks for your help.

    Hi Kishor-
    Thanks for the reply.
    I realize that might be the case, as u explained in your two points.
    so now I have created a hidden input field and use it's value as a way to communicate between javascript and jsp. and in bean's function I check the value of this hidden field, which will be set by the OnClick's javascript and then proceed accordingly.
    Is this the correct way to accomplish what I am trying to?
    Thanks again

  • Using a request scope object in a javascript function

    Hello,
    is there a way to obtain a reference to a request scope attribute in a javascript function?
    or after using <jsp:useBean id="myBean" ...>, how do I pass the "myBean" object to a javascript fuction?
    Thanks for any help.
    E-

    ok, thanks...this is working for a string property of a bean... but I get an 'invalid character' error when I want to create an actual reference to the bean object itself.
    here is the jist of what I need to get working... myBean has a property 'listItems' that is a Vector of listBeans.
    function buildList() {
    var myBean = <%=request.getAttribute("mybean")%> ;
    // get referenence to the Vector property listItems
    var list = myBean.getListItems();
    // now I want to iterate the list and use the properties of the list beans
    for (x = 0 ; x < list.size() ; x++ ) {
    var listBean = list[x];
    var foo = listBean.getFoo();
    // need to use foo to populate a hierarchical list
    can I do this in JavaScript??? do I need to cast the classes to the variables?

  • Calling function at onFocus statement

    may i ask that the below code is correct or not?
    <jsp:useBean id = "pc" class="common.claim" scope="request" />
    <td id=progPect><input type="text" size=5 id="progPect" value='<%=progPect.elementAt(c)%>' onFocus="<%=pc.chkBreakdown(wp.elementAt(c),ln.elementAt(c),la_no);"></td>
    and this pc.chkBreakdown function is location at class file.
    and this function does return an boolean, either true or false.
    if return value is true, then link to the other page.
    how to write the code at the onFocus statement there...plz help..

    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute"
    applicationComplete="functionName()">
    or you could trigger it on creationComplete event, or initialize event;

  • Howto call a Javabean function from javascript

    Hi,
    I want to fill some properties from an object which can be chosen from a selection box. When an object is chosen, I want to fill the propertie fields of the chosen object. How can I do this? Can I call from a 'onChange' a javabean function? or do I have to call a javascript function which calls a javabean function?
    Thanks in advance..
    Hugo Hendriks

    Actually, in a way you can call a bean method from a javascript function. But it's not really the bean method that is called for but the value it should have returned at the server side.
    Take a look at this example:
    <%@ page language="java"
    %>
    // list is a Vector containing a collection of "set & get-beans" retrieved through a db query
    <jsp:useBean id="list" class="java.util.Vector" scope="request" />
    <%
    Iterator itr = list.iterator();
    MyBean mb = new MyBean();
    %>
    <head>
    <script>
    var limit = <%=list.size()%>;
    function fillTextArea(theButton){
    for(a=0;a<limit;a++){
    <%
    while(itr.hasNext()){
    mb = (MyBean)itr.next();
    %>
    if(this.name=="bt1")
    document.theForm.ta.value += "<%=mb.getValue1()%>";
    else
    document.theForm.ta.value += "<%=mb.getValue2()%>";
    <%
    %>
    </script>
    </head>
    <body>
    <form name="theForm">
    <textarea name="ta" cols="50" rows="20"></textarea>
    <br>
    <br>
    <input type="button" name="bt1" value="click me" onclick="javascript:fillTextArea(this)">
    <input type="button" name="bt2" value="...or me" onclick="javascript:fillTextArea(this)">
    </form>
    </body>
    </html>
    The result of this will be a javascript function containing code for each element in the vector but that will be accessable in the client side.
    Of course this could render in large jsp pages being returned if the list vector is large, but sometimes this could be preferred against making a new servlet request each time.
    /Rickard

  • Passing values to JavaBean function using jsp scriplet

    Hi,
    I have a JavaBean funtion that is SaveData(parameters)
    which save the values from HTML form.
    Now i want a code for pass the values from HTML form to SaveData() function using jsp scriptlet.
    I used the code
    <jsp:useBean id="JDBC" class="bean.JDBCBean" scope="application"></jsp:useBean>
    <%=JDBC.saveData(phonenumber,manufacturer,model,email,country,newsletter)%>
    Here
    JDBCBean -> Bean Name
    phonenumber,manufacturer,model,email,country,newsletter ->HTML form's text values
    But it didnt work properly.
    Anyone help me to correct this.

    Hi,
    i have the same code like above
    I have to pass the parameters with form name under the following code.
    <jsp:useBean id="JDBC" class="bean.JDBCBean" scope="application"></jsp:useBean>
    <%=JDBC.saveData(registration.phonenumber.value,id_type.value,id_style.value,registration.email.value,registration.scountry.value,player_type.values)%>
    Here
    registration -> HTML form name
    But i got the error for
    package registration does not exist
    out.print(JDBC.saveData(registration.phonenumber.value,id_type.value,id_style.value,registration.email.value,registration.scountry.value,player_type.values));
    How to i correct this?
    Anyone help me......

  • Global variable for function in JSP?

    Hi,
    In my JSP file I have a variable (sName) which I would like to use in a function. Is that possible? Do I have to declare it differently?
    Many thanks
    Simone
    Here the code fragement:
    <jsp:useBean id="s" class="ServiceRegistryClient"></jsp:useBean>
    <% Vector sName = s.getServiceNames(); %>
    <input type="Submit" name="callService" value="Call Service" onclick="callService()">
    <script language="javascript">
    function callService() {
    alert("Text" + sName.elementAt(0));
    }</script>

    Here's a sample jsp showing what I mean. It just posts back to itself:
    <HTML>
    <HEAD>
    <TITLE>Crappy JSP</TITLE>
    <%
    String element = null;
    java.util.StringTokenizer temp = null;
    String row = null;
    // get enumeration of parameters
    java.util.Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
      element = String.valueOf(names.nextElement());
      // get button name / row
      temp = new java.util.StringTokenizer(element, "_");
      if (temp.countTokens() == 2) {
        element = temp.nextToken(); // name
        row = temp.nextToken();  // row
      } else continue;
      // my button?
      if (element.trim().equals("callService")) {
           out.print("ROW NUMBER == " + row);
           break;
    java.util.Vector sName = new java.util.Vector();
    java.util.Vector sDescription = new java.util.Vector();
    java.util.Vector sLocation = new java.util.Vector();
    final int count = 3;
    for(int x = 0; x < count; x++) {
      sName.add("Name " + x);
      sDescription.add("Description " + x);
      sLocation.add("Location " + x);
    %>
    </HEAD>
    <BODY>
    <FORM action="../timesheet/Sample.jsp">
    <TABLE>
    <% for (int i = 0; i < count; i++) { %>
    <TR>
    <TD>
    <%= sName.elementAt(i) %>
    </TD>
    <TD>
    <%= sDescription.elementAt(i) %>
    </TD>
    <TD>
    <%= sLocation.elementAt(i) %>
    </TD>
    <TD>
    <input type="submit" name="callService<%= "_" + i %>" value="Call Service">
    </TD>
    </TR>
    <% } %>
    </TABLE>
    </FORM>
    </BODY>
    </HTML>

  • Function call without scriptlet

    Hi,
    I want to call a function without using a scriptlet:
    Look at the following code:
    <jsp:useBean id="jspSession" class="com.test.JspSession" scope="page"/>
    <%
    jspSession.verifySession();
    %>
    can I call the function jspSession.verifySession() using a taglib tag?
    Thanks
    Bernhard

    Two methods:
    1 - write your own custom tag which would be something like:
    <myTag:verifySession session="jspSession"/>
    2 - Exploit the naming features of Javabeans and write the method as
    public boolean isVerifySession()
    or
    public String getVerifySession()
    You could then invoke it as
    <jsp:getProperty name="jspSession" property="verifySession"/>
    or using JSTL
    <c:out value="${jspSession.verifySession}"/>
    Ok, so its a hack, an exploitation, and get methods shouldn't really have side effects like this implies, but it works...

Maybe you are looking for