String & Int in Bean

Hi,
i'm building a webapp to simply allow the user to enter his or her details which will be submitted with all the details stored in the bean. When deciding to either make properties such as age or telephone number as string or int in a bean, i read somewhere that it is a rule of phumb to set these properties as Strings as they are easier to validate. If that is the case, if i create a property of String age with it's corresponding getter and setter method i.e
public void setAge(String n) {
    age = n ;
public String getAge()
   return age;
doing something like the above would not convert the value into an int which is what i would like to do. Therefore, i was thinking of doing the following in my bean class:
package beans ;
public class Person
private int age ;
// Constructor
public Person() {
    age = 0 ;
public void setAge(int n) {
    age = n ;
  public void setAge(String s) {
    try {
      age = Integer.parseInt(s) ;
    catch (NumberFormatException e) {}
  public int getAge() {
    return age ;
  }doing the above would i think be more convenient. Would that be the better way do you think?
cheers

BigDaddyLoveHandles wrote:
raychen wrote:
There's nothing wrong with what you are doing, however.I disagree. First that code doesn't belong in a bean. An then it has to be dupilcated across every bean and every "int" property. Plus I disagree with the way it swallows formatting errors.BigXXXXXwhatever...... what do you mean by that code does not belong in the bean. I've seen my example duplicated in many exampls and in books. I'm not to concerned if it has to be duplicated in every bean and int, it's not what i was asking.
In terms of the fomatting errors, what errors? Do i need to correct something?
Thanks for your input raychen.
Edited by: nvidia1 on Jan 6, 2009 12:19 AM

Similar Messages

  • HELP ON java.lang.String,int

    Im very new to java.please help!!!
    im having this error after compiling this:-
    public boolean setBookname(String newName)
              if (newName >0)
                   BookName = newName;
              else
                   return false;
    A:\Book.java:30: operator > cannot be applied to java.lang.String,int
              if (newName >0)
    ^
    1 error
    Process completed.
    thank u!

    The OP should read about IllegalArgumentException.Indeed. And a few other things as well...
    http://java.sun.com/docs/books/tutorial/
    http://java.sun.com/learning/new2java/index.html
    http://javaalmanac.com
    http://www.jguru.com
    http://www.javaranch.com
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

  • JTextField(Document, string, int)

    Dear friends,
    Could you just tell me how can I fix the size of the JTextField,
    such as just accept the maximum number of digits or characters in JTextField...
    I cant create the Document....
    Could anyone give me a tips?

    I found the best way to do this is to subclass PlainDocument as follows:
    public class MyTextDoc extends PlainDocument
        int maxCharacters;
        public MyTextDoc(int maxChars) {
            maxCharacters = maxChars;
        public void insertString( int offs, String str,  AttributeSet a )
                    throws BadLocationException {
            if( (getLength() + str.length()) <= maxCharacters)
                super.insertString(offs, str, a);
            else
                Toolkit.getDefaultToolkit().beep();
    }I then use this document in the constructor for all my JTextFields.
    I'm not sure what you mean by "I cant create the Document...."
    Cheers
    Gary

  • JSP Strings, Ints converting

    I'm sure this sort of thing has been asked but i cant find it in the forums.... I'm trying to read in a string from a form and then convert it to an int so that i can use it in a select statement so i can compare it to a field declared as "Number" in the Access Database.
    String sess = request.getParameter("num"); //num comes from form
    int eventNum = Integer.parseInt(sess);
    //connected ot the database
    String query = "SELECT * FROM EVENT WHERE event_id = 'eventNum' ";
    ResultSet result = stmt.executeQuery(query);
    //event_id is a number in the database
    Its saying "Data type mismatch in criteria expression"
    Thanking you in advance,
    Brian

    Since you are building a string as query, you don't need to convert it
    String sess = request.getParameter("num"); //num
    String query = "SELECT * FROM EVENT WHERE event_id ='eventNum' ";
    ResultSet result = stmt.executeQuery(query);This error "Data type mismatch in criteria" comes from event_id = 'num'
    event_id is numeric, so it should not contain quotes in the sql statement
    this will do it:
    String query = "SELECT * FROM EVENT WHERE event_id =" + sess

  • String - int

    i want to convert a string var into int var?
    how is that possible in jsp?
    thank you!

    int intvar = Integer.parseInt(StringVar);

  • Error  executeUpdate(String,int)

    i try execute follow source and obtain error:
    Exception in thread "main" java.lang.NoSuchMethodError
    at ProbaInsertId.getKey(ProbaInsertId.java:54)
    at ProbaInsertId.main(ProbaInsertId.java:19)
    import java.util.*;
    import java.io.*;
    import java.sql.*;
    public class ProbaInsertId
    public static void main(String args[])
         getKey();
    public static void getKey(){
         int key = 0;
              String nume="zzz";
              String prenume="fff";
              try{
                   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
              catch(Exception e) {
                   e.printStackTrace();     
                   System.out.println("Eroare incarcare driver!\n" + e);
              Connection conn = null;
              try{
              conn = DriverManager.getConnection( "jdbc:microsoft:sqlserver://mother:1433;DatabaseName=db", "mihai", "mihai");
    String sqlQueryInsert = "INSERT INTO proba (nume, prenume) " +
                             "VALUES(nume, prenume)";
    Statement sqlStatementInsert = conn.createStatement();
                   sqlStatementInsert.executeUpdate(sqlQueryInsert,sqlStatementInsert.RETURN_GENERATED_KEYS);
    ResultSet rs = sqlStatementInsert.getGeneratedKeys();
    if( rs.next() ){
         key = rs.getInt(1);
                        System.out.println(key);
                        sqlStatementInsert.close();
                        conn.close();
              catch(Exception e) {
                   e.printStackTrace();     
                   System.out.println("Eroare select 2!\n" + e);

    Sounds like that JDBC driver doesn't support getting auto-generated keys. - MOD

  • Can't set bean1's int property with bean 2's int property

    Using JDeveloper 3.2.3 (with JSP 1.1), the following fails to compile:
    <jsp:useBean id="user" type="pkg.User" scope="session"/>
    <jsp:useBean id="user2" type="pkg.User"/>
    <jsp:setProperty name="user2" property="id" value=" <jsp:getProperty name="user" property="id"/> "/>
    The compile error is...
    Error in attribute list: Unable to convert constant to property type: int
    The pkg.User id property is an int. If I change the code to set a String property it works fine!
    The workaround is to do the following:
    <jsp:setProperty name="user2" property="id" value=" <%= user.getId() %> "/>
    However, I prefer the XML syntax.
    Environment:
    JDeveloper 3.2.3 (build 1018)
    Windows 2000
    null

    Unfortunately, this is the major limitation of using cooperating beans in a JSP. The JSP tag translation mechanisms just don't handle passing non-String parameters between beans very well. I have half a mind to write a tag extension where you can pass in a source bean and property and a destination bean and property and the tag will generate the code to set the destination property based on the source property.
    Unless someone already has one out there, I may just do this and pass it around. Something like:
    <jfh:passObject
    source="bean1" source_property="id"
    dest="bean2" dest_property="id"
    />Of course, I would have to worry about ClassCastExceptions if the source property and destination property are not convertible, but it would be useful nonetheless to be able to pass around Java objects without having to write the code into the JSP.
    Ideas, thoughts?
    John H.

  • How can write string in jsp on beans..

    Hello.
    My English ability very poor sorry....
    I am developing jsp using beans..
    I want to see value on beans....
    but I can't see....
    I want to check my values...
    plz help me....
    how can I view my String , int... on the beans....

    Write a "getter" method for each variable you want to be able to read in the JSP.
    example:
    public class yourBean
    // ... some code, contructor, etc...
    private String yourVariable;
    public void setYourVariable(String s)
    yourVariable = s ;
    public String getYourVariable()
    return yourVariable ;
    You can retrieve the value in your jsp with any of these ways:
    1) use the <jsp:getProperty> tag
    2) <%= yourBean.getYourVariable() %>
    3) <% String s = yourBean.getYourVariable() %>
    }

  • Convert an int to a String

    Hi,
    when i try to do the following its an error
    int totalmarks;
    String Totalmarks;
    Totalmarks = totalmarks.toString();
    could any one tell me how to do it correctly
    Thank you

    A lot of alternatives, but you can't do new String(int..).
    1. Integer.toString(totalmarks)
    2. String.valueOf(totalmarks) will call Integer.toString(totalmarks)
    3. ""+totalmarks will use the StringBuffer and append "" and totalmarks which again will call String.valueOf(totalmarks) which again will call Integer.toString(totalmarks)

  • How to store multiline string literal in to java bean shell variable

    Hello Experts
    How to store multiline string literals in java bean shell like we use triple quote for jython variable
    Using Jython
    str=""" helllo
    welcome to my world"""
    above syntax is working but not for java bean shell like below
    String str=""" hello
    welcome to my world""";
    So how to do this in java bean shell. I came to this scenario while storing logs to a variable. I believe there is no solution for storing multiline strings to java bean shell variable.
    <@
    String str="<%=odiRef.getPrevStepLog("MESSAGE")%>";
    @>
    Any suggestion will be highly appreciated.
    Thank You.

    maddythehunk wrote:
    Im trying this but its not working...
    while(billingQueryParamsItr.hasNext()) {
         billingQueryParam = (BillingQueryParam) billingQueryParamsItr.next();
         System.out.println("****** Param Name-->"+billingQueryParam.getParamName());
         String[0] name = billingQueryParam.getParamName(); // giving error ; expected
         //billingItemActionForm.setParamName(billingQueryParam.getParamName());
    Declare the array outside of the loop. Fill the array as you iterate. And stop putting your error messages inside of comments in the code.

  • Passing values to form bean string array from dynamic added textboxes

    Hi,
    I am unable to pass values to form bean string array from a jsp in which I have incorporated dynamically adding of textboxes in javascript.
    I have given add/delete row option in the jsp. If there is single row, this is working fine. But after adding a row, I am not able to either do any validations on added textboxes or pass the values to the String array form bean variable.
    code snippet:
    var cell6 = row.insertCell(4);
    var element5 = document.createElement("input");
    element5.type = "text";
    element5.className = "formtext1";
    element5.size = "5";
    element5.value = "00.00";
    element5.name= "qty"; // this is a string array of the form bean.
    element5.onchange=function() {checkNumeric(this);};
    cell6.appendChild(element5);
    <html:text styleClass="formtext1" property="qty" value="" size="5" styleId="qty" onchange="checkNumeric(this)"/></td>
    form bean declaration
    private String[] qty; Please help.
    Edited by: j2eefresher on Jan 12, 2010 11:23 PM

    Shivanand,
    There's no need to post that much code when you could create a very short test case that demonstrates only the problem you are having.
    You're using &NAME. notation on something that isn't a page or application item. You can't reference PL/SQL variables that way (or any other way) outside the PL/SQL scope. For your situation, you could create a page item named P55_DOCID and assign it a value in the PL/SQL process (:P55_DOCID := DOCID;), then reference &P55_DOCID. in HTML areas like the success message.
    Scott

  • Bean not remain in my session?

    i made this code for 2 pages, wanting to use a bean in both sites...the problem is it is created on the index page, but when i try to recall it on the 2nd, it creates it again...any tips on this? here's the code of the pages:
    index.jsp
    <jsp:useBean id="bean" scope="session" class="bean.initiate" />
                        <% int c =bean.start(10,3); %>
    <HTML>
    <HEAD>
    <TITLE>Construct Ballots</TITLE>
    </HEAD>
    <BODY>
    <H1>Construct Ballots</H1>
    <FORM NAME="form1" ACTION="ShowBallot.jsp" METHOD="POST">
    <INPUT TYPE="HIDDEN" NAME="buttonName">
    <label>
    <input type="text" name="amount">
    </label>
    <INPUT TYPE="BUTTON" VALUE="Make Ballots" ONCLICK="button1()">
    </FORM>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
    function button1()
    document.form1.buttonName.value = "Constructing Ballots..."
    form1.submit()
                   -->
    </SCRIPT>
    </BODY>
    </HTML>
    ShowBallot.jsp
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <jsp:useBean id="bean" scope="session" class="bean.initiate" />
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <HEAD>
    <TITLE>Determining Which Button Was Clicked</TITLE>
    </HEAD>
    <BODY>
    <p><%= request.getParameter("buttonName") %>
    <% String a= request.getParameter("amount"); %>
    <%int input= Integer.parseInt(a); %></p>
    <p><%int g=bean.confirm();%> </p>
    <p>This is one example of a ballot constructed:</p>
    <p><%=g %> </p>
    <p>  </p>
    </BODY>
    </html>

    How do you know it creates the bean again?
    The code looks ok to me.
    What does the bean.initiate class do?
    One way of confirming if it is the same session is to use
    Session id = <%= session.getId() %>
    It should be the same on both pages

  • BC4J, JSP, accesing a remote app module deployed as an 8i EJB session bean

    hi everybody,
    i am reposting this question since the thread went somewhat off-topic ...
    i have successfully deployed my Jdev 3.2 developed app module to my remote 8.1.7 db server as an EJB session bean
    i am able to test it via the Business Components Tester ...
    i am also able to test it from my wizard-generated Business Components JSP App using DataWebBeans ...
    but when i try to access it from a JSP data tag page I get the following error:
    Excepcisn:
    javax.servlet.jsp.JspException: JBO-28300: Piggyback read error
    void periodoswebtags_html.PeriodoView_Browse._jspService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
    void oracle.jsp.runtime.HttpJsp.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
    void oracle.jsp.app.JspApplication.dispatchRequest(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
    void oracle.jsp.JspServlet.doDispatch(oracle.jsp.app.JspRequestContext)
    void oracle.jsp.JspServlet.internalService(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
    void oracle.jsp.JspServlet.service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
    void javax.servlet.http.HttpServlet.service(javax.servlet.ServletRequest, javax.servlet.ServletResponse)
    void oracle.lite.web.JupServlet.service(oracle.lite.web.JupRequest, oracle.lite.web.JupResponse)
    void oracle.lite.web.MimeServletHandler.handle(oracle.lite.web.JupApplication, java.lang.String, int, oracle.lite.web.JupRequest, oracle.lite.web.JupResponse)
    void oracle.lite.web.JupApplication.service(oracle.lite.web.JupRequest, oracle.lite.web.JupResponse)
    void oracle.lite.web.JupHandler.handle(oracle.lite.web.JupRequest, oracle.lite.web.JupResponse)
    void oracle.lite.web.HTTPServer.process(oracle.lite.web.JupRequest, oracle.lite.web.JupResponse)
    boolean oracle.lite.web.HTTPServer.handleRequest(oracle.lite.web.JupInputStream, oracle.lite.web.JupOutputStream)
    boolean oracle.lite.web.JupServer.handle(oracle.lite.web.JupInputStream, oracle.lite.web.JupOutputStream)
    void oracle.lite.web.SocketListener.process(java.net.Socket)
    void oracle.lite.web.SocketListener$ReqHandler.run()
    and the JBO-28300 error is undocumented ... :(
    i have included a library containing the <mybcs>CommonEJB.jar and <myappmodule>EJBClient.jar files into my JSP projects
    the JSP data tag page is a wizard-generated trivial browse page
    TIA,
    p

    hi everybody,
    just fixed ... :) ...
    i added the following libraries to my JSP data tag project and everythig works fine ...
    Oracle XML Parser 2.0
    JBO Runtime
    SQLJ Runtime
    HTH,
    p

  • Stateless Sessions Bean - CMT

    I have an application running under Oracle 9ias and has been configured to use the external transaction controller. I am running into a problem with transactions and was hoping someone can help me out.
    The scenario is as follows
    Stateless Session Bean A {
    int addAttachment(String data) {
    uow = session.getActiveUnitOfWork();
    Attachment attachment = uow.registerNewObject(new Attachment());
    attachment.setData(data);
    uow.assignSequenceNumber(attachment);
    return attachment.getId();
    Stateless Session Bean B {
    void getAttachments() {
    int id = beanA.addAttachment("sfsf");
    uow = session.getActiveUnitOfWork();
    Attachment attachment = uow.readObject(id, Attachment.class);
    The call from getAttachments() to read the object fails. It doesn't find the object.
    Since both of these are running within the same transaction (the transaction attribute on both methods are set to "Required") shouldn't getAttachments() on Bean B be able to see the object that was created in Session Bean A?
    By setting the transaction level on the addAttachment() to RequiresNew works but that isn't what I want as everything should be in one transaction.

    If keeping method names a reasonable length were not an issue, the method “registerNewObject” might be better called “registerThisNewObjectAsIfItWasAClone”. The “registerNewObject” method registers the new object as if it was a clone. At commit time, TopLink creates another instance of the object to be the cache version of that business object. You use “registerNewObject” in situations where you do not need a handle to the cache version of the object after the unit of work commits and you do not want to work with clones of new objects. You also use “registerNewObject” in situations where you must pass a clone into the constructor of a new object and then need to register the new object.
    You use registerNewObject when you have to pass clones into a constructor -- i.e., where there clones will be associated with the new object created by the constructor... But generally you use registerObject for new Objects.
    - Don

  • Session Bean Destroy property

    When a user logs out y proyect and go back to the sign up page, the sessionbean that contains the profile (int) stays with the same value, i have 6 variables (strings, int, integer, etc) in session bean, every time i use logout button i have to initialize the variables in session bean at once, i used sessionbean1.destroy(); but it doesnt work, anybody can tell me if im using well this?

    The comments for the session bean's destroy method say:
         * <p>This method is called when this bean is removed from
         * session scope.  Typically, this occurs as a result of
         * the session timing out or being terminated by the application.</p>
         * <p>You may customize this method to clean up resources allocated
         * during the execution of the <code>init()</code> method, or
         * at any later time during the lifetime of the application.</p>
         */This says that the web app automatically calls destroy() when the user session times out due to inactivity, or when the web application invalidates the session, such as, for example, by calling session.invalidate().
    So, this does not appear to meet your needs as you want the variables to be nulled out when the user logs out (which does not necessarily end the session).
    One other approach would be to create a session bean method, such as logout() that clear out the 6 variables.
    Then have your logout button call this method, such as getSessionBean1().logout().
    Another approach is to create a Java class, such as User with 6 properties.
    Instantiate a User in the session bean when the user logs in
    User user = new User();
    and set user to null when the user logs out.

Maybe you are looking for

  • REGARDING TABLE FOOTER IN SMARTFORMS

    hi i hav to pritn 6 items in page1 and 13 items in page2 and so on. but while calculating total for fields if pages exceed more than one i hav to fill with constant value'total' for corresponing fields in table in all pages except in last page in las

  • Spontaneous Crack in screen with out physical damage.

    I am very discouraged to even post in this forum in the first place but none the less. Here is my situation. I purchased my Sony Xperia from a Tmobile retailer. The phone has been amazing and up until this point ive had no problems. I always have my

  • Regarding Maintenance view

    Hi guys. we have created Maintenance view for addon table in 46C. so was Created Function group ZMXXXXX having below structure. ZMXXXXX -Func module     Table frame ZMXXX     TableProc ZMXXX -Dictionary objects -Dynpro -Include   LSVIXXXX   LSVIXF01

  • Is it possible to sum up amounts in report scripts?

    Hi - is this possible? If so, can you give me an example? I have not been able to find a commend for this. I am using Essbase 6.5 I have a cost center with many accounts. I need to pull that cost center and sum up the accounts into one number. the ac

  • Transports from BI Dev to BI QA

    Hi Frinds,   In general what are the  transports in the BI Dev environment which should be moved to create a BI QA client ? Any inputs greatly accpeted . Thanks in advance,