JSP 2.0 & Beans

Hi All,
I just learnt that with JSP 2.0, we do not have to specify the useBean or getProperty tags. We can simple get the job done through........
${key.property}... but this has really started me thinking about the necessity of having getters and setters within beans. What's the point... Because I was under the impression that even validation should not take place within beans. It should be taken care of within a seperate validation file. So provided that the getters and setters just simply return the variable; why bother having them in the first place ?
I am sure this is simply a misunderstanding on my part, therefore I would appreciate an explanation. Thanks.

Thank you very much, but with your permission, I'd just like to clarify that I am aware that getters and setters are NORMALLY used for encapsulation, ie desktop applications. But this is not what I am woried about. My problem is with beans. I'd just like to know whether the MVC "pattern" allows this behaviour within them. The only problem I am facing is that I was under the impression that this was not allowed for beans.
So could you simply re-confirm that beans do not demand both getters and setters to be present for every data variable and that it is possible to have some sort of processing ( which I thought was only allowed with servlets ) such as validation within beans.
Much appreciated.

Similar Messages

  • Questions/answers from jsp to java bean

    Hi
    This is what i need to do .
    I am showing some questions, say 4 of them , and radio buttons(yes/no) as answers in the JSP.
    Now how do i transfer these questions and their answers from jsp to java bean .
    I did try hashmap ,but not quite working .
    any help?
    thanks

    Name each radiobutton differently, and then provide 1 property and accessor methods for each of your four answers in the JavaBean, with the same name as specified in the HTML FORM.
    So in the HTML:
    <input type="radio" name="answerOne" value="true"...>
    and then have a property named answerOne with accessor methods in the javaBean...

  • JSP using a bean to do output?

    One thing I haven't seen much mention of is the possibility of using a Java Bean to
    do some output for a JSP. I'm porting a page I wrote a while back that uses a
    JHTML page to call a servlet which is just a thin wrapper around a bean which
    actually writes the HTML output (the bean is actually a network client to a server
    that generates the HTML page). The natural line of attack seems to be to have a
    JSP call the bean which will write the output, but I haven't seen mention of that
    technique anywhere and wonder why I'm so strange in thinking of this. The bean
    method to do the output currently takes a PrintWriter as a parameter to output to,
    but that can be changed to something similar if desired.
    Can anyone give me a snippet of code that would best implement taking the output
    stream for a JSP page and passing it to a bean for output?
    Thanks
    Steve

    eh? It sounds like your bean is doing all the output? If that's the case, then why do you want to use a JSP? - use a servlet as you already are.
    If you have a bean declared in the page and you just want to pass it the page's output stream to output part of the pages content, then use this:
    <jsp:useBean id='myBean' class='com.mycompany.MyBeanClass'/>
    <%
      PrintWriter beanOut = new PrintWriter(out);
      myBean.writeContent(beanOut);
      beanOut.close()
    %>
      ...where writeContent is your method that takes a PriontWriter. out is a JspWriter, which extends Writer, so you need to create a PrintWriter from it. You may or may not need to close/flush the PrintWriter deppending upon your bean implementation.

  • Issue with passing parameters from JSP to Backing bean

    hi ,
    I have an issue in passing parameters from my JSP to backing bean. I want to fetch the parameter from my URL in backing bean .This is how i am coding it right now. But the parameter companyID returns me null.
    URL http://localhost:8080/admin/compadmin.jsp?companyID=B1234.
    In my backing bean
    FacesContext context = FacesContext.getCurrentInstance();
    String companyID = (String)context.getExternalContext().getRequestParameterMap().get("CompanyID");
         public void setCompanyID(String companyID)
              this.companyID=companyID;
         public String getCompanyID()
              return this.companyID;
    faces-config.xml :
       <managed-bean-name>admincontroller</managed-bean-name>
              <managed-bean-class>com.admin.controller.AdminController</managed-bean-class>
              <managed-bean-scope>request</managed-bean-scope>
              <managed-property>
                   <property-name>companyadminbean</property-name>
                   <property-class>com.admin.model.AdminBean</property-class>
                   <value>#{companyadminbean}</value>
                         </managed-property>
                        <managed-property>
                                 <property-name>companyID</property-name>
                              <value>#{param.companyID}</value>
                             </managed-property>Please let me know if iam missing something.Appreciate your help in advance
    Thanks

    Thanks very much for your input. I made changes to my bean accordingly. Actually the method getAdminType() is a not a getter of a property. It's just a method which iam calling in AdminController bean constructor to verify whether the person is System Admin or Client admin. So now the issue is inspite of making changes still the link "Copy Users" shows up for Client admin too which is incorrect.
    My Administrator bean:
    public class Administrator {
      boolean GSA=false;
      boolean SA=false;
      public Administrator(){}
    public boolean isGSA()
        return GSA;
      public boolean isSA()
        return SA;
      public void setGSA(boolean value)
        this.GSA=value;
      public void setSA(boolean value)
        this.SA=value;
    }My backing bean:
    public class AdminController {
    private AdminBean adminbean = new AdminBean();
    public AdminController(){
    int userID=1234;
    this.getAdminType(userID);           
    public void getAdminType(int userID)
             Administrator admin = new Administrator();
             if (userID<0) return;
             try{
                 if(Rc.isGlobalSystemAdmin(userID)){
                      admin.setGSA(true);
                              }else if(Rc.isClientSystemAdmin(userID)){
                      admin.setSA(true); // i could see these values setup correctly in the admin bean when i print them
                 adminbean.setAdmin(admin);
                  } catch (Exception e){ }
    Admin Bean:
    public class AdminBean {
    private Administrator admin; 
    public Administrator getAdmin()
                        return this.admin;
              public void setAdmin(Administrator admin)
                        this.admin = admin;
    faces-config.xml
    <managed-bean>
              <managed-bean-name>admincontroller</managed-bean-name>
              <managed-bean-class>com.controller.AdminController</managed-bean-class>
              <managed-bean-scope>request</managed-bean-scope>
              <managed-property>
                   <property-name>adminbean</property-name>
                   <property-class>com.model.AdminBean</property-class>
                   <value>#{adminbean}</value>
             </managed-property>
         </managed-bean>
         <managed-bean>
              <managed-bean-name>adminbean</managed-bean-name>
              <managed-bean-class>com.model.AdminBean</managed-bean-class>
              <managed-bean-scope>request</managed-bean-scope>
              <managed-property>
                   <managed-property>
                   <property-name>admin</property-name>
                   <property-class>com.model.Administrator</property-class>
                   <value>#{admin}</value>
                             </managed-property>
         </managed-bean>     My JSP:<h:outputLink id="ol1" value="/companyadmin/copyusers.jsp">
               <h:outputText id="ot1" value="Copy Users" rendered="#{adminbean.admin.isGSA}" /><f:verbatim><br/></f:verbatim>
               </h:outputLink>    so now the issue is thelink copy users is displayed even #{adminbean.admin.isGSA} is FALSE. please advise.
    Thanks
    Edited by: twisai on Oct 15, 2009 7:06 AM

  • Help me to control the transactions from jsp to java bean

    Please anyone can guide me how to control the transactions from jsp to java bean. I am using the Websphere studio 5.1 to develop the database application. I would like to know two method to handle the database. First, I would like to know how I can control the transactions from jsp by using java bean which is auto generated for SQL statement to connect to the database. Following code are jsp and java bean.....
    // call java bean from jsp
    for (i=0;i<10;i++)
    addCourse.execute(yr,sem,stdid,course,sec);
    I write this loop in jsp to call java bean..
    here is java bean for AddCourse.java
    package com.abac.preregist.courseoperation;
    import java.sql.*;
    import com.ibm.db.beans.*;
    * This class sets the DBModify property values. It also provides
    * methods that execute your SQL statement and return
    * a DBModify reference.
    * Generated: Sep 7, 2005 3:10:24 PM
    public class AddCourse {
         private DBModify modify;
         * Constructor for a DBModify class.
         public AddCourse() {
              super();
              initializer();
         * Creates a DBModify instance and initializes its properties.
         protected void initializer() {
              modify = new DBModify();
              try {
                   modify.setDataSourceName("jdbc/ABAC/PreRegist/PRERMIS");
                   modify.setCommand(
                        "INSERT INTO informix.javacourseouttemp " +
                        "( yr, sem, studentid, courseid, section ) " +
                        "VALUES ( :yr, :sem, :studentid, :courseid, :section )");
                   DBParameterMetaData parmMetaData = modify.getParameterMetaData();
                   parmMetaData.setParameter(
                        1,
                        "yr",
                        java.sql.DatabaseMetaData.procedureColumnIn,
                        java.sql.Types.SMALLINT,
                        Short.class);
                   parmMetaData.setParameter(
                        2,
                        "sem",
                        java.sql.DatabaseMetaData.procedureColumnIn,
                        java.sql.Types.SMALLINT,
                        Short.class);
                   parmMetaData.setParameter(
                        3,
                        "studentid",
                        java.sql.DatabaseMetaData.procedureColumnIn,
                        java.sql.Types.CHAR,
                        String.class);
                   parmMetaData.setParameter(
                        4,
                        "courseid",
                        java.sql.DatabaseMetaData.procedureColumnIn,
                        java.sql.Types.CHAR,
                        String.class);
                   parmMetaData.setParameter(
                        5,
                        "section",
                        java.sql.DatabaseMetaData.procedureColumnIn,
                        java.sql.Types.SMALLINT,
                        Short.class);
              } catch (SQLException ex) {
                   ex.printStackTrace();
         * Executes the SQL statement.
         public void execute(
              String userid,
              String password,
              Short yr,
              Short sem,
              String studentid,
              String courseid,
              Short section)
              throws SQLException {
              try {
                   modify.setUsername(userid);
                   modify.setPassword(password);
                   modify.setParameter("yr", yr);
                   modify.setParameter("sem", sem);
                   modify.setParameter("studentid", studentid);
                   modify.setParameter("courseid", courseid);
                   modify.setParameter("section", section);
                   modify.execute();
              // Free resources of modify object.
              finally {
                   modify.close();
         public void execute(
                   Short yr,
                   Short sem,
                   String studentid,
                   String courseid,
                   Short section)
                   throws SQLException {
                   try {
                        //modify.setUsername(userid);
                        //modify.setPassword(password);
                        modify.setParameter("yr", yr);
                        modify.setParameter("sem", sem);
                        modify.setParameter("studentid", studentid);
                        modify.setParameter("courseid", courseid);
                        modify.setParameter("section", section);
                        modify.execute();
                   // Free resources of modify object.
                   finally {
                        modify.close();
         * Returns a DBModify reference.
         public DBModify getDBModify() {
              return modify;
    I would like to know that how can I do for autocommit from jsp. For example, the looping is 10 times which mean I will add 10 records to the db. If the last record is failed to add to db, "how can I rollback the perivious records?" or guide me to set the commit function to handle that case. Thanks a lot for take your time to read my question.

    Hello.
    The best method is using a session bean and container managed transactions. Other method is using sessions bean and the user transaction object (JTA-JTS).
    so, JDBC has transaction management too.
    good luck.

  • How can share data between jsp pages using beans??

    any one can give me code for 2 jsp pages with bean that share data for them

    <jsp:usebean name="yourBeanName" type="com.whatever.foo" scope="session"/>
    this will look for a bean named yourBeanName in the scope specified by the scope attribute. If none was found, the container will instantiate one with the no arg constructor for your bean and place it into the proper scope.
    if your bean had a method getName(), you could then on your jsp do:
    <%=yourBeanName.getName()%> to print the results of the method to the page. there are other ways to do the actual placing of the output on the page, but this is the most direct.

  • JSP and Java Beans with Database Problem

    hellow, this is my first posting and i hope to help me as fast as you can...
    my problem is simplly i cant get any data from the database (whatever the database it is, i test it with MS Access and MySQL server) when i use a bean, But if i put my connection statement in the JSP file thair is no problem... ???? !!!!
    for example i have a class "Authentication" that have a method to test if the username and password is correct or not and return 1 if true, 0 if false, -1 if thair are some problem in connecting DB.
    now if i create a normal java application that uses this method, it's work and no problems, BUT if i used a JSP page to use this method it's return allways -1

    T1 class:
    package VX;
    import java.sql.*;
    import java.util.*;
    import javax.swing.*;
    public class T1
    //public MBJDBConnection(String driver,String url)
    public T1()
    JDBC_DRIVER = "com.mysql.jdbc.Driver";//driver;
    DATABASE_URL = "jdbc:mysql://localhost:3306/rawafed?user=root;password=0000";//url;
    //=======DB CONNECTION===========================================
    private static String JDBC_DRIVER;
    private static String DATABASE_URL;
    protected Connection connection;
    protected Statement statement;
    //===========End DBC==============================================
    public int update(String sqlUpdate)
         int i=0;
              //connectDB();
              try{
                   i=statement.executeUpdate(""+sqlUpdate);
                   catch(Exception e)
                        System.out.println("Error Inserting Statement Or Connection Not Opened");
              //disconnectDB();
         return i;
    public ResultSet select(String sqlQuery)
              //connectDB();
              ResultSet rs;
              try
              {//open try
              rs=statement.executeQuery(""+sqlQuery);
                   return rs;
              }//end try
              catch(Exception e2)
                   //System.out.println("Error Selecting Statement Or Connection Not Opened");
              }//end catch
              //add to array list
         //return resultList;
         return null;
    //------Methods-------
    public void connectDB()
    //===========================Connection===================
    try
    Class.forName(JDBC_DRIVER);
    catch(Exception e)
    System.out.println("Error : FOR NAME");
    try
    connection = DriverManager.getConnection(DATABASE_URL, "root", "0000");
    catch(Exception e)
    System.out.println("Error : DB URL");
    try
    statement = connection.createStatement();
    catch(Exception e)
    System.out.println("Error : CREATE STATEMENT ERROR");
    public void disconnectDB()
    try
    statement.close();
    connection.close();
    catch(Exception e2)
    System.out.println("Error : CAN'T CLOSE DB");
    T2 Class
    package VX;
    // class Person.
    //Required Class : EDC.EDCDB
    import java.sql.*;
    public class T2
         public T2()
              //initialization
         //........................ Attributes .........................
         private String user;
         private String password;
         private T1 db=new T1();
         private ResultSet rs;
         //......................... Methods .........................
         public String getAdmin(String u,String p)// 0: Failure, 1:Success and he is Administrator, 2: success and he is a regular employee 3: SUCCESS AND HE IS agent
              try
              user=u;
              password=p;
              rs=db.select("SELECT emp_id,password FROM Employee WHERE emp_id="+user+" AND password="+password+" AND Rank_ID=1");
              if(rs.next())
                   return ""+1;
              else
                   rs=db.select("SELECT emp_id,password FROM Employee WHERE emp_id="+user+" AND password="+password+" AND Rank_ID=2");
                   if(rs.next())
                        return ""+2;
                   else
                        rs=db.select("SELECT emp_id,password FROM Employee WHERE emp_id="+user+" AND password="+password+" AND Rank_ID=3");
                        if(rs.next())
                             return ""+3;
                        else return ""+0;
              catch(Exception e){System.out.println("Error \n"+e.getMessage());return ""+e.getMessage()+"\n"+(-1);}
         public int getCard(String u,String p)// 0: Failure, 1:Success and he is Administrator, 2: success
              user=u;
              password=p;
              try
              db.connectDB();
              rs=db.select("SELECT Card_ID,password FROM Card WHERE Card_ID='"+user+"' AND password='"+password+"'");
              if(rs.next())
                   return 1;
              return 0;
              catch(Exception w)
                   return -1;
              finally
                   //System.out.println("Done");
                   db.disconnectDB();
         public int getAny()
              return 1;
    }//end class
    This is a tested class and it's work OK
    import VX.T2;
    public class T3
         public static void main(String [] args)
              System.out.println("System Started...");
              try
                   T2 t2=new T2();
                   System.out.println(t2.getCard("1","a"));
              catch(Exception e)
                   System.out.println("Opsssss ...");
    Now this is the JSP Code that OK and Run without any problems
    <%@ page contentType="text/html; charset=windows-1256" language="java" import="java.sql.*" errorPage="" %>
    <!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>
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
    <title>test</title>
    </head>
    <body>
    <%
    //Mazin B. Jabarin 20210464
    //Testing JSP - MySQL Server Driver
    String connectionURL = "jdbc:mysql://localhost:3306/EDCDB?user=root;password=0000";
    Connection connection = null;
    Statement statement = null;
    ResultSet rs = null;
    %>
    <%
    try{
    Class.forName("com.mysql.jdbc.Driver");
    connection = DriverManager.getConnection(connectionURL, "root", "0000");
    statement = connection.createStatement();
    rs = statement.executeQuery("SELECT * FROM a");
    while (rs.next()) {
    out.println(rs.getString("id")+"<br>");
    rs.close();
    catch(Exception e)
    out.print("Error : "+e.getMessage());
    %>
    </body>
    </html>
    Now this JSP File always returns (-1) ???? !!!!!!!
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" import="VX.T2" import="java.util.*" errorPage="" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title>Untitled Document</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <%
    try
    T2 t2=new T2();
    out.println("Result Still : "+t2.getCard("1","a"));
    catch(Exception w)
    out.println("<BR> Error In Execution ??? "+w.getMessage());
    %>
    </body>
    </html>
    ++++++++++++++++++++++++++++
    any one can help me please :(
    i use tomcat as web-application
    and i install jdk 1.5
    also JBulder 7
    (now i supposed that the JBulder make some conflict, so i uninstalled it but still Not Working) ...
    before one year i was working just like this way and it was working
    but now i dont know what is the problem
    i am really need help.

  • JSP, Data Web Bean, BC4J: Setting the where clause of a View Object at run time

    Hi,
    I am trying to develop a data web bean in which the where clause of a View Object will be set at run time and the results of the query then displayed.
    My BC4J components are located in one project while the coding for the data web bean is in another project. I used the following code bu t it does not work. Could you please let me know what I am doing wrong?
    public void populateOSTable(int P_EmpId)
    String m_whereString = "EmpView.EMP_ID = " + P_EmpId;
    String m_OrderBy = "EmpView.EMP_NAME";
    oracle.jbo.ApplicationModule appModule = null;
    ViewObject vo = appModule.findApplicationModule("EMPBC.EMPAppModule").findViewObject("EMPBC.EMPView");
    vo.setWhereClause(m_whereString);
    vo.setOrderByClause(m_OrderBy);
    vo.executeQuery();
    vo.next();
    String empName numAttrs = vo.getAttribute(EmpName);
    System.out.println(empName);
    Thanks.

    <BLOCKQUOTE><font size="1" face="Verdana, Arial">quote:</font><HR>Originally posted by JDev Team (Laura):
    Here is how I have usually done mine:
    1. In the JSP, use a RowsetNavigator bean to set the where clause and execute the query.
    2. Use a custom web bean to process the results of the query (print to HTML).
    for example:
    <jsp:useBean class="oracle.jbo.html.databeans.RowsetNavigator" id="rsn" scope="request" >
    <%
    // get the parameter from the find form
    String p = request.getParameter("p");
    String s = request.getParameter("s");
    // store the information for reference later
    session.putValue("p", p);
    session.putValue("s", s);
    // initialize the app module and view object
    rsn.initialize(application,session, request,response,out,"wt_bc_WT_bcModule.wtjoinView");
    // set the where clause string
    String theclause = "presname = '" + p + "' AND slideno=" + s;
    // set the where clause for the VO
    rsn.getRowSet().getViewObject().setWhereClause(theclause);
    rsn.getRowSet().getViewObject().executeQuery();
    rsn.getRowSet().first();
    %>
    </jsp:useBean>
    <jsp:useBean class="wt_bc.walkthruBean" id="wtb" scope="request" >
    <%
    // initialize the app module and VO
    wtb.initialize(application,session, request,response,out,"wt_bc_WT_bcModule.wtjoinView");
    wtb.render();
    %>
    In this case, the render method of my custom web bean mostly gets some session variables, and prints various content depending on the session variable values.
    Hope this helps.
    </jsp:useBean><HR></BLOCKQUOTE>
    Laura can you give the code of your walkthru bean? i wna't to initialize a viewobject, set the where clause and give that viewobject back to initialize my navigatorbar.
    Nathalie
    null

  • Help with Login Form (JSP DB Java Beans Session Tracking)

    Hi, I need some help with my login form.
    The design of my authetication system is as follows.
    1. Login.jsp sends login details to validation.jsp.
    2. Validation.jsp queries a DB against the parameters received.
    3. If the query result is good, I retrieve some information (login id, name, etc.) from the DB and store it into a Java Bean.
    4. The bean itself is referenced with the current session.
    5. Once all that's done, validation.jsp forwards to main.jsp.
    6. As a means to maintain state, I prefer to use url encoding instead of cookies for obvious reasons.I need some help from step 3 onwards please! Some code snippets will do as well!
    If you think this approach is not a good practice, pls let me know and advice on better practices!
    Thanks a lot!

    Alright,here is an example for you.
    Assume a case where you don't want to give access to any JSP View/HTML Page/Servlet/Backing Bean unless user logging system and let assume you are creating a View Object with the name.
    checkout an example (Assuming the filter is being applied to a pattern * which means when a resource is been accessed by webapplication using APP_URL the filter would be called)
    public doFilter(ServletRequest req,ServletResponse res,FilterChain chain){
         if(req instanceof HttpServletRequest){
                HttpServletRequest request = (HttpServletRequest) req;
                HttpSession session = request.getSession();
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                String method = request.getMethod();
                String auth_type  = request.getAuthType();
                if(session.getAttribute("useInfoBean") != null)
                    request.getRequestDispatcher("/dashBoard").forward(req,res);
                else{
                        if(username != null && password != null && method.equaIsgnoreCase("POST") && (auth_type.equalsIgnoreCase("FORM_AUTH") ||  auth_type.equalsIgnoreCase("CLIENT_CERT_AUTH")) )
                             chain.doFilter(req,res);
                        else 
                          request.getRequestDispatcher("/Login.jsp").forward(req,res);
    }If carefully look at the code the autherization is given only if either user is already logged in or making an attempt to login in secured way.
    to know more insights about where these can used and how these can be used and how ?? the below links might help you.
    http://javaboutique.internet.com/tutorials/Servlet_Filters/
    http://e-docs.bea.com/wls/docs92/dvspisec/servlet.html
    http://livedocs.adobe.com/jrun/4/Programmers_Guide/filters3.htm
    http://www.javaworld.com/javaworld/jw-06-2001/jw-0622-filters.html
    http://www.servlets.com/soapbox/filters.html
    http://www.onjava.com/pub/a/onjava/2001/05/10/servlet_filters.html
    and coming back to DAO Pattern hope the below link might help you.
    http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
    http://java.sun.com/blueprints/patterns/DAO.html
    http://www.javapractices.com/Topic66.cjp
    http://www.ibm.com/developerworks/java/library/j-dao/
    http://www.javaworld.com/javaworld/jw-03-2002/jw-0301-dao.html
    On the whole(:D) it is always a good practice to get back to Core Java/J2EE Patterns.and know answers to the question Why are they used & How do i implement them and where do i use it ??
    http://www.fluffycat.com/java-design-patterns/
    http://java.sun.com/blueprints/corej2eepatterns/Patterns/index.html
    http://www.cmcrossroads.com/bradapp/javapats.html
    Hope that might help :)
    REGARDS,
    RaHuL

  • New to Jsp. Jsp and java bean not running

    hi
    i have created a simple jsp file and using a java bean. but it is showing errors. my file directory structure in tomcat4.1 is:
    aptechsamples:
    index.jsp
    WEB-INF/classes:
    myPackage:
    Counter.class
    i have no web.xml file i dont know how to use it or not. i need it or not.
    the index.jsp file:<html>
    <head><title> A Simple JSP Bean </title></head>
    <body>
    <%@ page language ="java" %>
    <%@ page import ="mypackage.Counter" %>
    <jsp:useBean id="id_counter" scope="session" class ="Counter"/>
    <jsp:setProperty name="id_counter" property="count" param="count" />
    <jsp:getProperty name="id_counter" property="count" />
    </body>
    </html>the Counter.java file is: package mypackage;
    public class Counter{
         String msg;
         public Counter(){
              msg = "Hello World";
         public String getCount(){
              return msg;          
         public void setCount(String c){
              msg = c;
    }please help me and tellme what the hell is wrong with it or me. im getting an error:
    exception
    org.apache.jasper.JasperException: Cannot create bean of class Counter

    Java is already telling you what is wrong: it cannot create an instance of your Counter class. The reason being: it can't find it.
    What do you mean by "myPackage"? Before you can use any class in your JSP's or servlets, they MUST be stored in a package. If you don't know what that is, I highly suggest you lookup "java package" and "java classpath" using google.
    Let's say your Counter class is in a package mypackage (so it starts with the line package mypackage;). Then you have to store the .class file as:
    WEB-INF/classes/mypackage/Counter.class
    If done correctly, the error message should disappear.

  • Drop-down in JSP using a bean as back-end

    Hi everyone,
    I like to create a dynamic drop-down (reading from a database) using JSP but accessing a bean. My code on the bean is:
    public void DepartmentName() {
    try
    stmt1 = tConnection.createStatement();
    rs1 = stmt1.executeQuery ("select DEPT_NAME from DEPARTMENT");
    while ( rs1.next() )
    String DptName = rs1.getString("DEPT_NAME");
    System.out.println(DptName);
    Can anybody tell me how to call this DepartmentName bean in JSP? So far my JSP looks like this...
    <table width="100%"><tr>
    <form action="next.jsp" method="POST">
    <input type="hidden" name="type" value="listemp">
    <td width="100">
    <b>Department</b></td>
    <td wifth="100">
    <SELECT name=cust multiple size=4>
    <option>??????? HELP ???????????</option>
    </SELECT>
    </td>
    <td><input type="submit" value="Submit" name="dept">
    </td></tr></table>
    Many thanks.

    First you need to modify your bean to return some sort of data structure of String objects. How about a Vector? Then you could call Vector.elements() on the return statement of the DepartmentName() method, like this...
    public Enumeration DepartmentName()
      Vector myVector = new Vector(0);
      while(rs.next())
        myVector.add(rs.getString(1));
      return myVector.elements();
    }Then in your JSP you'll need to use the JSP useBean tag
    <jsp:useBean id="myBean" class="com.myco.myapp.MyBean" scope="page|request|session|application" />And before the option tag call the bean and get the enumeration of String objects, then loop through them like this:
    while(enum.hasMoreElements())
      out.println(((String) enum.nextElement()));
    }

  • What's the difference between using java directly in JSP and java bean

    What is the difference if I use java code directly in JSP or use java bean in JSP?
    Which class to use for receiving the passed parameter from html or java script? Any difference for java code and java bean in the way receiving the passed data?
    How can I pass string from jsp to html or java script?

    1 Cleaner pages
    2 you have to write the class and use set and get methods
    3 What do you mean when saying passing string from jsp to html??, do you mean the value you can use <%=variablename%>

  • JSP called database Bean - works in forte ide- not outside ide

    I am obtaining my Connection object from a Java bean so that I can change database connections (like development to production) by just changing the bean out. Inside forte for java 3.0 with its built in tomcat, it works fine. I have the same version of tomcat that I fire up outside of the ide. I used the ide to create a WAR file and I expand it under webapps so the external tomcat can see it. The initial jsp page works fine (so tomcat can see it fine).
    Now when I click a button that performs a form method=get action=\"operation.jsp\"> ... , the operation.jsp executes the following code:
    <jsp:useBean id="db" scope="request" class="dbConnectBean" />
    <%
    Connection adxcon = db.getDbConnection();
    Statement adxstmt = adxcon.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
    ... %>
    The dbConnectBean code looks like:
    public class dbConnectBean extends Object implements java.io.Serializable {
    public class dbConnectBean extends Object implements java.io.Serializable {
    private PropertyChangeSupport propertySupport;
    private Connection dbConnection;
    public dbConnectBean() {
    propertySupport = new PropertyChangeSupport ( this );
    public Connection getDbConnection() {
    setDbConnection();
    return dbConnection;
    public void setDbConnection() {
    this.dbConnection = dbConnection;
    try {
    Class.forName("org.gjt.mm.mysql.Driver");
    catch (Exception e) {
    System.out.println("Can't load JDBC Driver");
    return;
    try {
    dbConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/cs_dev?user=foo&password=bar");
    catch (Exception e) {
    System.out.println("Can't get connected: " + e.getMessage());
    return;
    return;
    Outside of the ide, when I click to perform the form action above, I get:
    Error: 500
    Location: /AddressBook/operation.jsp
    Internal Servlet Error:
    javax.servlet.ServletException
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:459)
         at _0002foperation_0002ejspoperation_jsp_3._jspService(_0002foperation_0002ejspoperation_jsp_3.java:140)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:119)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:177)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:318)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:391)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.tomcat.core.ServletWrapper.doService(ServletWrapper.java:404)
         at org.apache.tomcat.core.Handler.service(Handler.java:286)
         at org.apache.tomcat.core.ServletWrapper.service(ServletWrapper.java:372)
         at org.apache.tomcat.core.ContextManager.internalService(ContextManager.java:797)
         at org.apache.tomcat.core.ContextManager.service(ContextManager.java:743)
         at org.apache.tomcat.service.http.HttpConnectionHandler.processConnection(HttpConnectionHandler.java:210)
         at org.apache.tomcat.service.TcpWorkerThread.runIt(PoolTcpEndpoint.java:416)
         at org.apache.tomcat.util.ThreadPool$ControlRunnable.run(ThreadPool.java:498)
         at java.lang.Thread.run(Thread.java:484)
    Any ideas??

    Error 500 signifies the following;
    "500 (Internal Server Error)
    500 (SC_INTERNAL_SERVER_ERROR) is the generic 'server is confused' status code. It often results from CGI programs or (Heaven forbid!) servlets that crash or return improperly fromatted headers."
    Check your headers.
    I wouls suggest that you do not Run your Servlets and JSPs through the Forte IDE. Download and install Tomcat 4 on your desktop (if you havent already) and test them there. You only need to mount the directories for the particular web app.
    You can use this guide on how to install and setup your Tomcat 4 and your development environment. http://www.moreservlets.com/Using-Tomcat-4.html
    Hope this helps

  • First use of jsp and java bean and "Unable to compile class for JSP" error

    Hi,
    I am trying to create my first jsp + java bean and I get a basic error (but I have no clue what it depends on exactly). Tomcat seems to cannot find my class file in the path. Maybe it is because I did not create a web.xml file. Did I forgot to put a line in my jsp file to import my bean?
    Thank you very much for your help.
    Here is my error:
    An error occurred at line: 2 in the jsp file: /login.jsp
    Generated servlet error:
    [javac] Compiling 1 source file
    /usr/local/tomcat/jakarta-tomcat-5/build/work/Catalina/localhost/test/org/apache/jsp/login_jsp.java:43: cannot resolve symbol
    symbol : class CMBConnect
    location: class org.apache.jsp.login_jsp
    CMBConnect test = null;
    I only have this in my directory:
    test/login.jsp
    test/WEB-INF/classes/CMBConnect.java
    test/WEB-INF/classes/CMBConnect.class
    Do I need to declare another directory in classes to put my class file in it and package my bean differently?
    Here is my login.jsp:
    <%@ page errorPage="error.jsp" %>
    <jsp:useBean id="test" type="CMBConnect" scope="session" />
    <html>
    <head>
    <title>my test</title>
    </head>
    <body>
    <h3>Login information</h3>
    <b><%=session.getValue("customerinfo.message")%></b>
    <form> ....... </form>
    </body>
    </html>
    and here is my CMBConnect.java:
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    public class CMBConnect
    public CMBConnect () { }
    public String openConnection(String id, String password) {
    String returnText = "";
    try {
    Connection con = null;
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    con = DriverManager.getConnection("jdbc:oracle:thin:@myserver.abc.com:1521:TEST", id, password);
    if(con.isClosed())
    returnText = "Cannot connect to Oracle server using TCP/IP...";
    else
    returnText = "Connection successful";
    } catch (Exception e) { returnText = returnText + e; }
    return returnText;
    Thanks again!

    Thanks for you help
    I created the package and I get this error this time:
    javax.servlet.ServletException: bean test not found within scope
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:822)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:755)
         org.apache.jsp.login_jsp._jspService(login_jsp.java:68)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:94)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:268)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:277)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:223)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:856)

  • ClassCastException When we use JSP with Normal Bean in WebLogic 5.1

              Hai Everybody...
              We have an application where JSP files are using the Normal Java beans(Nothing
              but a Java Class).Here all jave beans are in a folder ..\myserver\classfiles\
              and the jsp files are in ..\myserver\public_html\..... .
              This combination is throwing a ClassCastException when the JSP try to Intantiate
              the bean....It doesn't give error alway..Initially it works fine and all of a
              sudden it throws this error..
              Plse..If anybody can help us Do So....
              sijo
              

    That is correct; WLS 5.1 does not support the updating of these helper classes.
              In WLS 6.0, you can package everything up as a web application or enterprise
              application and redeploy the whole thing (including the helper classes)...
              Alex wrote:
              > But, Robert, that means the JavaBean classes cannot be updated without
              > restarting the server.
              >
              > I tried putting them in the servlet directory. With the result that they
              > often work, but sometimes I get the same ClassCastException as sijo. Where
              > should JavaBean classes that are used from JSP (and maybe other servlets) be
              > put in order to be able to update them?
              >
              > "Robert Patrick" <[email protected]> escribió en el mensaje
              > news:[email protected]...
              > > The Java Beans being used by the JSP pages need to be placed into the
              > > WEBLOGICCLASSPATH (i.e., -Dweblogic.class.path=...) and not in the working
              > directory
              > > where the JSP-generated classes are created (i.e., \myserver\classfiles is
              > typically
              > > the working directory for the JSPServlet and \myserver\serverclasses is
              > the
              > > appropriate place for the Java Beans used by the JSPs)...
              > >
              > > sijo wrote:
              > >
              > > > Hai Everybody...
              > > >
              > > > We have an application where JSP files are using the Normal Java
              > beans(Nothing
              > > > but a Java Class).Here all jave beans are in a folder
              > ..\myserver\classfiles\
              > > > and the jsp files are in ..\myserver\public_html\..... .
              > > >
              > > > This combination is throwing a ClassCastException when the JSP try to
              > Intantiate
              > > > the bean....It doesn't give error alway..Initially it works fine and all
              > of a
              > > > sudden it throws this error..
              > > >
              > > > Plse..If anybody can help us Do So....
              > > >
              > > > sijo
              > > >
              > > >
              > >
              

  • JSP, tags or beans or what?

    Hi,
    I have not used jsp's for almost 3 years now but need to return to them. Can anyone advise what the best/most modern way to include POJO output code in a JSP. I am confused as to all the different terminologies. In my mind simplicity is best so let me explain a bit more:
    I have a POJO :
    public class _displayDrivers {
        *public static String get()* {
            ObjectContainer db = null;
            String out = "";
            try {
                db = Db4o.openFile("somefile.yap");
                List<Pilot> pilots = db.query(new Predicate<Pilot>() {
                    public boolean match(Pilot pilot) {
                        return pilot.getPoints() == 100;
                Pilot proto = new Pilot(null, 0);
                ObjectSet result = db.queryByExample(proto);
                out = listResult(result);
            } catch (Exception ex) {
            } finally {
                db.close();
                *return out;*
        public static String listResult(ObjectSet result) {
            String o = "";
            while (result.hasNext()) {
                o += "<br />" + result.next().toString();
            return o;
    }And I want to be able to simply, with no fuss, be able to 'dump' the String returned into a JSP sort of like this :
    <body>
        <% jspCode "_displayDrivers", "get", "(any parameters here)" %>
    </body>Nice an neat and easy. and most importantly I can give the graphic designers an 'API' of tags. I have looked at Tag Libraries but these seem overly complicated. I just want to call a method of a class! And beans look way dated.
    What is the most up to date way of doing this?
    Many thanks
    H
    Edited by: inabind on Aug 12, 2009 10:35 AM

    The best and most modern way is for that POJO to stop generating HTML. Instead it should return the list as a List, via a name suitable for a JavaBean such as getPilots. Then you can use JSTL to iterate through the list and display it in whatever way you choose.
    That way the JSP is in charge of the view (what the output looks like to the user) and the POJO is in charge of the data and the two don't interfere in each other's responsibilities.

Maybe you are looking for