HttpSession question....

Hi all,
How can I get the current HttpSession and pass it as a parameter to a method, from within a jsp?
Something like :
Class.method(HttpSession);same about HttpServletRequest?
Can someone point me to a tutorial or something?
many thanks in advance....
mike

HttpSession session = request.getSession(true);
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Session-Tracking.html
MeTitus

Similar Messages

  • Question on HttpSession

    I am new to web technology
    Is the HttpSession
    from the time user logsinto an application to the time user logsout of an application
    or
    from the time user opens a browser to the time the user closes the browser.
    Thanks.

    Thanks for the response.
    when is the request.setParameter() used and when to
    use the request.setAttribute()?
    is it when next JSP page needs some values from the
    current page the setParameter() used?
    not sure of setAttribute()
    Thanks.The method getParameter("someString") is used to pull query string values off the URL or values from a form submition. This method can be used for both an HTTP GET or POST. So you could retrieve a user's username and password from a form submition using this method.
    The getAttribute/setAttribute are used to store objects in the respective scope (page, request, session, or application). For example, say you have a servlet that get some database information that you want to display - you construct a POJO with all the info you want, set the object in the request, then you can forward to another servlet or JSP and all subsequent components can retrieve that object using the getAttribute method. This is the most common way of passing dynamic data to JSP for display purposes.
    Attribute is an Object (usually set by the jsp/servlet authors) and
    Parameter is a String (usually sent from the browser)

  • Noob question about HttpSession's

    Hey all, I've been scripting in jsp for awhile but most recently started using struts.
    I have a class (User) created with values for Username, First name, Last name, etc.
    When a user logs into the application I want to hold these values in a Session, so that I can use my getter and setter methods on it.
    I have a class that stores the object in the session
    session.setAttribute("User", ValidUser);
    [ValidUser being an Object of type User]
    Now in a jsp I'd like to use something like
    mypack.User myNewUser = (mypace.User)session.getAttribute("User");
    and then be able to use
    myNewUser.getUsername();

    Thanks, that works, but is there a better way to store information in a session?
    For instance a way that I can get around declaring a User variable on every page.
    like:
    session.getAttribute("User").getUsername();
    Or should I be declaring this object as a bean with a scope of session?
    and then use
    <%@ taglib uri="/tags/struts-bean" prefix="bean" %>
    <bean:write name="myUserBean" property="Username">
    I'm just looking for the cleanest way to do it, thanks.

  • How do i get a list of httpsessions currently active in container

              what is the object that i can interact with to get a listing of active httpsessions
              within my application context (servlet container) at any given time? i know i
              can setup a listener, is this the only way? is there now direct api?
              thanks
              

    I replied to this question in another email thread...
              "Vinod Mehra" <[email protected]> wrote in message
              news:<[email protected]>...
              > Here is a jsp to give you an idea. Unfortunately the session timeout
              > (max-inactive-interval) is not exposed in the runtime mbean. So you will
              > have to hardcode it for now. If you want it be exposed please ask support
              > for a patch.
              >
              > <%@ page import="weblogic.management.runtime.ServletSessionRuntimeMBean,
              > weblogic.management.MBeanHome,
              > weblogic.management.Admin,
              > java.util.Date,
              > java.util.Set,
              > java.util.Iterator,
              > weblogic.servlet.security.ServletAuthentication,
              > weblogic.management.runtime.WebAppComponentRuntimeMBean"
              %>
              > <pre>
              > <%!
              > private static final long TIME_OUT = 10; // seconds
              > %>
              > <%
              > // login as system user
              > // FIXME: don't hardcode username/passwords
              > ServletAuthentication.weak("system", "gumby1234", request, response);
              >
              > MBeanHome home = Admin.getInstance().getMBeanHome();
              > if (home != null) {
              > Set mbeanSet = home.getMBeansByType("ServletSessionRuntime");
              > Iterator mbeanIterator = null;
              > mbeanIterator = mbeanSet.iterator();
              > while (mbeanIterator.hasNext()) {
              > ServletSessionRuntimeMBean runtime =
              (ServletSessionRuntimeMBean)mbeanIterator.next();
              > WebAppComponentRuntimeMBean parent = (WebAppComponentRuntimeMBean)
              runtime.getParent();
              > out.print("ContextPath: " + parent.getContextRoot() +
              > " LastAccessedTime: " + new
              Date(runtime.getTimeLastAccessed()));
              > if (hasSessionExpired(runtime)) {
              > out.println(" <b>Invalidating expired session!!</b>");
              > runtime.invalidate();
              > } else {
              > out.println(" Session is still good");
              > }
              > }
              > }
              > %>
              > <%!
              > private boolean hasSessionExpired(ServletSessionRuntimeMBean runtime) {
              > return (runtime.getTimeLastAccessed() < (System.currentTimeMillis() -
              TIME_OUT * 1000));
              > }
              > %>
              >
              > hth,
              > Vinod.
              >
              "Randheer Gehlot" <[email protected]> wrote in message
              news:[email protected]...
              >
              > Vinod,
              > This class "ServletSessionRuntimeMBean" does'nt give you list of
              all
              > the active sessions in memory. Is there any class which holds list of all
              active
              > sessions in memory ?
              >
              > Thanks..
              > "Vinod Mehra" <[email protected]> wrote:
              > >If you have session monitoring turned on ...
              > >
              > >weblogic.xml:
              > >
              > > <container-descriptor>
              > > <session-monitoring-enabled>false</session-monitoring-enabled>
              > > </container-descriptor>
              > >
              > >... then you should be able to lookup the runtime mbeans
              > >(ServletSessionRuntimeMBean).
              > >
              > >This is what the admin console also uses.
              > >
              > >--Vinod.
              > >
              > >"ke" <[email protected]> wrote in message news:[email protected]...
              > >>
              > >> what is the object that i can interact with to get a listing of active
              > >httpsessions
              > >> within my application context (servlet container) at any given time?
              > > i
              > >know i
              > >> can setup a listener, is this the only way? is there now direct api?
              > >>
              > >> thanks
              > >
              > >
              >
              

  • Struts and HttpSession

    Hi guys, i think this is not te correct forum to ask about struts, but i realy need some help with that, i need to get the ID of a Http session and use this ID inte action class of struts for others task, can anyone help me on how to get the http session id from struts 2
    thanks in advance

    Use HttpSession.getId() [1]. Make it a point to read the documentation, you'll get more than enough help there and you'll learn as well.
    [1] http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpSession.html#getId()
    People on the forum help others voluntarily, it's not their job.
    Help them help you.
    Learn how to ask questions first: http://faq.javaranch.com/java/HowToAskQuestionsOnJavaRanch
    (Yes I know it's on JavaRanch but I think it applies everywhere)
    ----------------------------------------------------------------

  • How do I ensure HttpSession state is NOT persisted across server failures?

              I need to PREVENT the data in the HttpSession from being restored if the server crashes.
              I can't seem to find any documentation explicitly documentating how to ensure this.
              Any help would be greatly appreciated.
              Thanks,
              Andrew
              (p.s. this applies to WL5.1sp8 and WL6.1sp2)
              

    WebLogic doesn't serialize and restore sessions when the server is
              shutdown/crashes
              for "memory" sessions. That should not happen. Check the value of
              session.getClass()
              to verify the perisistentStoreType.
              --Vinod.
              "Andrew Larson" <[email protected]> wrote in message
              news:[email protected]...
              >
              > It is set to memory, but it appears to serialize and restore most of the
              sessions
              > when the server is shutdown/crashes. It there a way to set the
              persistence to none?
              > (e.g. in memory, not replicated, and only for the lifetime of the JVM)
              >
              > "Vinod Mehra" <[email protected]> wrote:
              > >What's your persistentStoreType (in weblogic.xml) set to?
              > >
              > >It seems you want persistentStoreType="memory" (which is the default).
              > >
              > >Is that what you are looking for?
              > >
              > >--Vinod.
              > >
              > >
              > >"Andrew Larson" <[email protected]> wrote in message
              > >news:[email protected]...
              > >>
              > >> Yes, in both instances (crash or graceful shutdown) I need session
              state
              > >cleared away.
              > >> This doesn't seem to be happening.
              > >>
              > >> Help please!
              > >> TIA
              > >> Andrew
              > >>
              > >>
              > >> "Vinod Mehra" <[email protected]> wrote:
              > >> >Oh, yes I misread your question. Do you want your sessions to be
              cleaned
              > >> >up
              > >> >even on a graceful server shutdown too?
              > >> >
              > >> >--Vinod
              > >> >
              > >> >
              > >> >"Andrew Larson" <[email protected]> wrote in message
              > >> >news:[email protected]...
              > >> >>
              > >> >> you don't seem to understand - I do NOT want session state to last
              > >> >across a server
              > >> >> crash; I want the session state to be lost, cleared away, gone,
              never
              > >> >to
              > >> >be seen
              > >> >> again.
              > >> >>
              > >> >>
              > >> >> "Vinod Mehra" <[email protected]> wrote:
              > >> >> >Use session persistent store types: replicated or file or jdbc.
              > >> >> >
              > >> >> >Please refer to the docs for details.
              > >> >> >
              > >> >> >--Vinod.
              > >> >> >
              > >> >> >
              > >> >> >"Andrew Larson" <[email protected]> wrote in message
              > >> >> >news:[email protected]...
              > >> >> >>
              > >> >> >> I need to PREVENT the data in the HttpSession from being restored
              > >if
              > >> >the
              > >> >> >server crashes.
              > >> >> >> I can't seem to find any documentation explicitly documentating
              > >how
              > >> >to
              > >> >> >ensure this.
              > >> >> >>
              > >> >> >> Any help would be greatly appreciated.
              > >> >> >> Thanks,
              > >> >> >> Andrew
              > >> >> >> (p.s. this applies to WL5.1sp8 and WL6.1sp2)
              > >> >> >
              > >> >> >
              > >> >>
              > >> >
              > >> >
              > >>
              > >
              > >
              >
              

  • OJSP Question Stateless mode !!!

    Hi,
    Why are the commit and rollback buttons disapear from the master navigationbar in the stateless mode ? What is the reason for ?
    Where should I take care in the stateless mode, I mean what datadeans are sensible to this mode ?
    Why in stateful mode, when running on a multithreads able webserver, I get always the same application instance. Isn't it suposed to be so, that the httpsession manages the application instances, so that when a second httpsession is made the application will generate a new instance ???
    Correct me if I'm wrong and please give me some advice on repairing this in the JSP framework.
    Another question, couldn't it be possible instead of reading the properties file of the JSP application, to use cookies for setting this properties at the opening of the httpsesion and after this only reading this properties values from the HttpSession environment ??? Corect me if I'm wrong ?!?!
    JDev Team, a prompt answer from you will be very apreciated.
    TIA,
    Seb.
    null

    Seb,
    Why are the commit and rollback buttons
    disapear from the master navigationbar in
    the stateless mode ? In stateless mode, everything is atomic. Transactions are automatically committed, so you do not need to explicitly commit, and there is no rollback.
    Why in stateful mode, when running on a
    multithreads able webserver, I get always
    the same application instance.In stateful mode, you do not get a new HTTP session for each thread. So all your threads use the same application instance.
    By the way, you can switch between stateful and stateless modes within the same application.
    Another question, couldn't it be possible
    instead of reading the properties file of
    the JSP application, to use cookies for
    setting this properties at the opening of
    the httpsesion and after this only reading
    this properties values from the
    HttpSession environment ???Yes, you can do this.
    Is there a docu for this javascripts beans ?No, but there is source code.
    Thanks
    Blaise

  • EJB Question Please help me

    Hi
    I am preparing for certification exam. I don't know the correct answer of these question. Please help me.
    Regards
    Arghya Banerjee
    ========================================================================
    1. While testing a BMP Entity Bean, a developer discovers that a transaction rollback does not cause a rollback of the changes made to the bean as it should. Which of the following should the developer suspect?
    A.     The ejbPassivate() method has a bug.
    B.     The ejbStore() method has a bug.
    C.     The ejbCreate() method has a bug.
    D.     The datastore does not support JTA.
    E.     The transaction does not implement javax.transaction.UserTransaction.
    Select 2 answers.
    2.     A Servlet must perform 3 operations that are independent of one another. They are time consuming with each operation consuming about 10 msec of CPU. The Servlet's response depends on the completion of all three operations. The developer decides to perform each operation on a separate worker thread to run them concurrently. Which of the following describe important parts of this implementation?
    A.     The Servlet should implement MultiThreadModel
    B.     The Servlet should implement SingleThreadModel
    C.     Access to the HttpSession must be synchronized.
    D.     The worker threads must not write to the ServletOutputStream.
    E.     The worker threads must not read from the ServletInputStream.
    Select the best answer.
    3. A client invokes the create() method on an CMP entity bean. Which of the following is a correct sequence in which the operations mentioned below are performed?
    a.     Container creates an EJBObject.
    b.     EJB home object invokes ejbCreate() on Bean instance
    c.     Bean instance is associated with EJBObject.
    d.     Container creates new bean instance.
    e.     Container calls setEntityContext() on bean instance.
    f.     Container creates the bean representation in a database.
    g.     ejbPostCreate() method is invoked on bean instance.
    A.     b -> f -> a -> c -> g
    B.     b -> a -> f -> c -> e -> g
    C.     a -> d -> c -> b -> e -> g -> f
    D.     a -> d -> c -> b -> f -> g -> e
    E.     a -> c -> e -> b -> f -> g
    Select the best answer.
    4.     A Web site is getting a lot of 'hits' and the amount of session data managed by the server is becoming too large for it to handle. Which of the following are appropriate ways to solve the problem?
    A.     Expand the capacity of the server.
    B.     Add additional servers to share the load.
    C.     Store the session data in a Cookie.
    D.     Store all session data in hidden fields on the web pages that are served.
    5. A developer wishes to make a server function available to an applet via a Servlet. The applet passes the Servlet a serialized object as an argument. How should the developer implement the Servlet?
    A.     Sub-class HttpServlet and create an ObjectInputStream from the
    ServletInputStream in the doGet() method.
    B.     Sub-class HttpServlet and create an ObjectInputStream from the
    ServletInputStream in the service() method.
    C.     Sub-class GenericServlet and create an ObjectInputStream from the
    ServletInputStream in the doGet() method.
    D.     Sub-class GenericServlet and create an ObjectInputStream from the ServletInputStream in the service() method.
    Select the best answer.
    6. While testing a CMP Entity bean, a developer discovers that a change to one of the bean's properties is not being reflected in the database that contains the bean data. What are possible causes?
    A.     The ejbStore() method has a bug.
    B.     The ejbCreate() method has a bug.
    C.     The setter for the property has a bug.
    D.     The mapping of container managed fields to database fields has a bug.
    E.     The deployment descriptor has a bug.
    F.     The ejbLoad() method has a bug.
    Select 4 answers.

    Hi Arghya ,
    From where you have taken these quetions , are they from the book.
    1. While testing a BMP Entity Bean, a developer
    discovers that a transaction rollback does not cause a
    rollback of the changes made to the bean as it should.
    Which of the following should the developer suspect?
    A.     The ejbPassivate() method has a bug.
    B.     The ejbStore() method has a bug.
    C.     The ejbCreate() method has a bug.
    D.     The datastore does not support JTA.
    E.     The transaction does not implement
    javax.transaction.UserTransaction.
    Select 2 answers.
    D,B If the Transaction is rolled back there are the possibility that either the datasource doesnot support it or the bean is updating the inconsistent data, so mostly problem in ejbStore() where there is a database update.
    2.     A Servlet must perform 3 operations that are
    independent of one another. They are time consuming
    with each operation consuming about 10 msec of CPU.
    The Servlet's response depends on the completion of
    all three operations. The developer decides to perform
    each operation on a separate worker thread to run them
    concurrently. Which of the following describe
    important parts of this implementation?
    A.     The Servlet should implement MultiThreadModel
    B.     The Servlet should implement SingleThreadModel
    C.     Access to the HttpSession must be synchronized.
    D.     The worker threads must not write to the
    ServletOutputStream.
    E.     The worker threads must not read from the
    ServletInputStream.
    Select the best answer.
    Now here what is the worker Thread should not write to output stream as if it does then there will be wrong formatting of the data, we are bothered about to improve the throughput so we have spawned three worker thread.Also there is no dependency so D is proper one
    3. A client invokes the create() method on an CMP
    entity bean. Which of the following is a correct
    sequence in which the operations mentioned below are
    performed?
    a.     Container creates an EJBObject.
    b.     EJB home object invokes ejbCreate() on Bean
    instance
    c.     Bean instance is associated with EJBObject.
    d.     Container creates new bean instance.
    e.     Container calls setEntityContext() on bean
    instance.
    f.     Container creates the bean representation in a
    database.
    g.     ejbPostCreate() method is invoked on bean
    instance.
    A.     b -> f -> a -> c -> g
    B.     b -> a -> f -> c -> e -> g
    C.     a -> d -> c -> b -> e -> g -> f
    D.     a -> d -> c -> b -> f -> g -> e
    E.     a -> c -> e -> b -> f -> g
    Select the best answer.
    Client invokes the create method on the home which inturn prepares the EJBObject and attaches the bean instance to the EJBObject and returned the reference to the client.So the option E.
    >
    4.     A Web site is getting a lot of 'hits' and the
    amount of session data managed by the server is
    becoming too large for it to handle. Which of the
    following are appropriate ways to solve the problem?
    A.     Expand the capacity of the server.
    B.     Add additional servers to share the load.
    C.     Store the session data in a Cookie.
    D.     Store all session data in hidden fields on the web
    pages that are served.
    You have to use the Load balancing tech , go for distributed technology B , the processing speed is now the criteria so you distribute the work.
    5. A developer wishes to make a server function
    available to an applet via a Servlet. The applet
    passes the Servlet a serialized object as an argument.
    How should the developer implement the Servlet?
    A.     Sub-class HttpServlet and create an
    ObjectInputStream from the
    ServletInputStream in the doGet() method.
    B.     Sub-class HttpServlet and create an
    ObjectInputStream from the
    ServletInputStream in the service() method.
    C.     Sub-class GenericServlet and create an
    ObjectInputStream from the
    ServletInputStream in the doGet() method.
    D.     Sub-class GenericServlet and create an
    ObjectInputStream from the ServletInputStream in the
    service() method.
    Select the best answer.
    I have to refer some docs for this
    6. While testing a CMP Entity bean, a developer
    discovers that a change to one of the bean's
    properties is not being reflected in the database that
    contains the bean data. What are possible causes?
    A.     The ejbStore() method has a bug.
    B.     The ejbCreate() method has a bug.
    C.     The setter for the property has a bug.
    D.     The mapping of container managed fields to database
    fields has a bug.
    E.     The deployment descriptor has a bug.
    F.     The ejbLoad() method has a bug.
    Select 4 answers.
    If there is the problem in the deployment descriptor then there ejb will not deploy at all .As the problem comes in updating I can make so no problem in the ejbCreate() also , but then many other consideration has to be taken .So I have my answer as
    A,C,D,F
    That is all I can say.
    Regard
    Vicky

  • New HttpSession always created instead of re-used

    Hi,
              I've noticed there are a lot of questions about the use of HttpSessions
              in WL 5.1 and
              I'm also having problems.
              I have a servlet that is creating an HttpSession like this;
              HttpSession session = request.getSession(true);
              The first time I call this servlet it creates a new session - however in
              this servlet's
              page I allow the user to look at what is contained in their session
              object (their envelope
              of shopping items). Every time the user invokes the servlet again by
              selecting their
              'envelope' instead of looking in their current session object a new one
              is created.
              Therefore I can't maintain state of the servlet containing the envelope
              items.
              It sounds like other folks are having this problem as well. My servlet
              is in a web application.
              My weblogic.properties file has these entries;
              weblogic.httpd.session.enable=true
              weblogic.httpd.session.persistence=false
              // I've tried it with persistence=true also
              The problems with sessions occurs on both Netscape and IE although both
              of them
              have cookies enabled.
              Any ideas what the problem is? Is there some setting in
              weblogic.properties I need to
              add to get sessions to be persistent between servlet invocations?
              Thanks,
              Susan Cline
              [email protected]
              

    And does the servlet which is run from the envelope use getSession( true )?
              or getSession( false )?
              If you're using true all the time, you're destroying the session.
              "Susan Cline" <[email protected]> wrote in message
              news:[email protected]...
              > Hi,
              >
              > I've noticed there are a lot of questions about the use of HttpSessions
              > in WL 5.1 and
              > I'm also having problems.
              >
              > I have a servlet that is creating an HttpSession like this;
              >
              > HttpSession session = request.getSession(true);
              >
              > The first time I call this servlet it creates a new session - however in
              > this servlet's
              > page I allow the user to look at what is contained in their session
              > object (their envelope
              > of shopping items). Every time the user invokes the servlet again by
              > selecting their
              > 'envelope' instead of looking in their current session object a new one
              > is created.
              > Therefore I can't maintain state of the servlet containing the envelope
              > items.
              >
              > It sounds like other folks are having this problem as well. My servlet
              > is in a web application.
              > My weblogic.properties file has these entries;
              >
              > weblogic.httpd.session.enable=true
              > weblogic.httpd.session.persistence=false
              > // I've tried it with persistence=true also
              >
              > The problems with sessions occurs on both Netscape and IE although both
              > of them
              > have cookies enabled.
              >
              > Any ideas what the problem is? Is there some setting in
              > weblogic.properties I need to
              > add to get sessions to be persistent between servlet invocations?
              >
              > Thanks,
              >
              > Susan Cline
              > [email protected]
              >
              

  • DAO question

    I am working on a slightly different variation of DAO pattern as shown by Sun:
    * I have 2 Singleton classes "MSSqlServerConnectionManager" and "OracleConnectionManager". ( For brevity I will consider only 1):
    public class MSSqlServerConnectionManager {
    public static String s_driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
    public static String s_databaseUrl;
    public static String s_userId;
    public static String s_password;
    public static Connection getConnection(  ) {
    }* I have a DAO Factory "DAOFactory":
    public abstract class DAOFactory {
    public static final int MSSQLSERVER = 1;
    public static final int ORACLE = 2;
    public static DAOFactory getDAOFactory( int whichFactory ) {
    switch (whichFactory) {
    case MSSQLSERVER:
    return new MSSqlServerDAOFactory();
    case ORACLE:
    return new OracleDAOFactory();
    default:
    return null;
    // specifies the DAOs
    }* I have 2 concrete DAO Factories for each DAO type which to get Connection call their respective ConnectionManagers:
    public class MSSqlServerDAOFactory implements DAOFactory {
    public static Connection getConnection() { returns MSSqlServerConnectionManager.getConnection(); }
    public class OracleDAOFactory implements DAOFactory { ...
    public static Connection getConnection() { returns OracleConnectionManager.getConnection(); }
    }* Then I have the DAOs (as interfaces) and their implementation for each DAO type. In each DAO method the first statement is to call the getConnection() method. For example:
    public interface CustomerDAO {
    public int insertCustomer(...);
    public class MSSqlServerCustomerDAO implements CustomerDAO {
    public int insertCustomer(...) {
    Connection conn = MSSqlServerDAOFactory.getConnection();
    }First of all is this desgin ok?
    Second the database url, user id and password are not hard-coded as users have choices in these areas. Right now after login they are available in the HttpSession. My question is at what time I needs to put them in the ConnectionManager?
    Thirdly I want my connection mangers to also be able provide connection through jndi look up. In my development environment i want to use DriverManager; In QA environment i want to use jndi. How is it possible?
    Thanks
    thanks

    ok I am confused. This is the final code I was thinking:
    public interface ConnectionManager {
      public void configure( Properties properties );
      public Connection getConnection();
      public void closeConnection( Connection );
    public class DriverManagerConnectionManager implements ConnectionManager {
      private String _driverName = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
      private String _databaseUrl;
      private String _userId;
      private String _password;
      public void configure( Properties properties ) {
        _databaseUrl = properties.getProperty("DATABASEURL");
        _userId= properties.getProperty("USERID");
        _password= properties.getProperty("PASSWORD");
    public class JNDIConnectionManager implements ConnectionManager {
      private String _jndiName;
      public void configure( Properties properties ) {
        _jndiName = properties.getProperty("JNDINAME");
    public class ConnectionManagerFactory {
      public static final int DRIVERMANAGER = 1;
      public static final int JNDI = 2;
      public static ConnectionManager getConnectionManager( Properties properties ) {
      ConnectionManager connectionManager;
      int connectionClass = new Int(properties.getProperty("CONNECTIONCLASS")).intValue();
      switch ( connectionClass ) {
        case DRIVERMANAGER:
          connectionManager = new DriverManagerConnectionManager ();
        case JNDI:
          connectionManager = new JNDIConnectionManager ();
        default:
          return null;
      connectionManager.configure( properties );
      return connectionManager;
    public abstract class DAOFactory {
      public static final int MSSQLSERVER = 1;
      public static final int ORACLE = 2;
      public static DAOFactory getDAOFactory( int whichFactory , ConnectionManager connectionManager ) {
        switch (whichFactory) {
          case MSSQLSERVER:
            return new MSSqlServerDAOFactory( connectionManager );
          case ORACLE:
            return new OracleDAOFactory( connectionManager );
          default:
            return null;
      // specifies the DAOs
    public class MSSqlServerDAOFactory implements DAOFactory {
      private ConnectionManager _connectionManager;
      private MSSqlServerDAOFactory() {}
      public MSSqlServerDAOFactory( ConnectionManager connectionManager ) {
         _connectionManager = connectionManager;
      public static Connection getConnection() { returns _connectionManager.getConnection(); }
    public class OracleDAOFactory implements DAOFactory {
      private ConnectionManager _connectionManager;
      private OracleDAOFactory() {}
      public OracleDAOFactory( ConnectionManager connectionManager ) {
         _connectionManager = connectionManager;
      public static Connection getConnection() { returns _connectionManager.getConnection(); }
    public interface CustomerDAO {
      public int insertCustomer(...);
    public class MSSqlServerCustomerDAO implements CustomerDAO {
      public int insertCustomer(...) {
        Connection conn = MSSqlServerDAOFactory.getConnection();
    }the ConnectionManagerFactory is a class which hands out ConnectionManager interface. Each type (JNDI and DriverManager) implements the ConnectionManager interface with its own class. Then I passes that ConnectionManager interface to the DAO Factory.
    Define an interface for the ConnectionFactory that
    each type will implement (JNDI and DriverManager).First of all I am assuming that ConnectionFactory you mentioned is actually ConnectionManagerFactory. Please correct me if I am wrong.
    If I understand correctly, what you are suggesting is to make ConnectionManagerFactory an interface. which will be implemented by each type. That means each type will be implementing 2 interfaces: ConnectionManagerFactory and ConnectionManager? Is it true? If yes then what is the reason?
    I think I am understanding you wrong. Please explain.
    Thanks

  • HttpSession maximum size

    Hello all,
    I was asked to research if HttpSession object has an inherited maximum size. I read the servlet spec (2.3) and there was nothing there about the maximum size of a session. Searched the forums and found some pointers but nothing concrete. I even saw a similar question with zero replies to it so if you think this is a silly or stupid question just say so. :)
    My presumption was that there is no set max size for the session object, that it depended of the capability of the server machine. Is there some vendor specific limitations (BEA vs. IBM vs. Tomcat vs. Sun) in implementation of the HttpSession interface? For one reason or other a member of my team thinks that there is some kind of limitation on the session size.
    Thanks in advance
    Dmitry

    A HttpSession has the same inheret limitations on its size as a ArrayList, a HasMap or any other Java object. Usually, the HttpSession is an ordinary Java object stored in some kind of Map global to the servlet-container. There is nothing special about it.
    General advice: dont store multiple attributes in a HttpSession. It is messy and unnecessary. Define a class that represents the state of a user session. Store one such object in each new HttpSession. Retrieve it when new request in the same sessions arrive and modify the session state object.
    As said: there is no special limitation on the size of such an object. I assume it speaks for itself that consuming large quantities of server memory for a single user is not a very wise thing.
    Silvio Bierman

  • WAS4 HttpSession.getId() != JSESSIONID cookie value

    Question: Should the session identifier value assigned to the JSESSIONID cookie by the servlet container be the exact same value returned by calling HttpSession.getId()?
    IBM's WebSphere Application Server (AEs) Version 4.0.x (WAS4) does not return the same value. The session identifier value assigned to the JSESSIONID cookie is 27 characters long, but the value returned by HttpSession.getId() only returns 23 characters. More precisely it is the last 23 characters of the 27 character value assigned to the JSESSIONID cookie.
    WAS4 is supposed to support Sun's Java Servlet Specification Version 2.2. In my opinion, it does not fully 100% support this specification because of what I just stated above.
    I would like to hear the Java Servlet Developer Community's opinion on this. Especially you Java Servlet Specification people and Sun.
    Here is the API documentation for HttpSession.getId().
    ===================================
    getId()
    public java.lang.String getId()
    Returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent.
    Returns: a string specifying the identifier assigned to this session
    ===================================
    Full HttpSession API documentation found at: http://java.sun.com/products/servlet/2.2/javadoc/javax/servlet/http/HttpSession.html
    Sun's Java Servlet Specification V2.2 documentation:
    ftp://ftp.java.sun.com/pub/servlet/22final-182874/servlet2_2-spec.pdf

    UPDATE: The value of the JSESSIONID cookie is not 27 characters long, its 30 characters long. the lenght of the value returned by HttpSession.getId() is still only 23 characters long. IBM has inserted 4 characters in the front and 3 characters in the back.
    30 != 23

  • HttpSession replication and server state saving

    The UIComponent class is not serializable, certainly because it is the StateManager which is responsible of saving its state.
    But the default server state manager of the RI stores the whole component tree in the HttpSession. That means that it won't work in clustered environments where the session has to be serialized for replication between servers.
    Will this be addressed in the final release ?

    E> This seems like a really BIG hole that Sun should fill very quickly!
    Thanks for your input. Note: spec is intentionally very vague about the
    specifics of state saving, except to say that the implementation must
    support two options: client and server. Therefore, any solution
    implemented in the Sun RI will likely be specific to that RI. Perhaps
    we can consider standardizing the approach to clustering in a future
    version of the spec.
    E> I came across this thread because I am testing the viability of using
    E> JSF in a JBoss clustered environment (and began getting serialization
    E> errors when I add the <distributable/> stanza to my web.xml file). I
    E> am probably not alone in my discomfort at having to replace a core
    E> JSF class with a "patch" just to get session replication to work. Why
    E> can't you or someone at Sun provide the resolution? All, that aside
    E> you a JSF expert at least provide detailed specifics as to how the
    E> proposed fix can be implemented by corporate JSF developers?
    Here's one very important aspect of application architecture that I'm
    surprised hasn't been pointed out before. Your application should be
    designed such that the all user state resides OUTSIDE of the JSF
    realm, and can therefore be made highly available by virtue of being
    stored in something that does support HA. JSF UI state should mostly be
    in request scope anyway. This is why we spent so much time on the
    ValueBinding API.
    E> Hope to see you at JavaOne (with more questions of
    E> course)!
    Yes, the entire Sun RI team, and several key EG members will be
    available at BOF-2220
    <http://www.javaone04.com/catalog/catalog/sessionDetail.jsp?hd=true&SESSION_ID=10589&form=searchform>.
    Tuesday 29 June 2004 7:30 pm.
    Ed (EG Member)

  • HttpSession and HttpServlet singletons?

    Hi guys,
    I have here two questions for better understanding of the HttpSession and HttpServlet classes:
    1. Is the HttpSession object existing between the server and the client and used for data exchange a kind of singleton? E.g. if I call a servlet concurrently with different parameters (as shown above), will this conflict on evaluation of the session parameters on the servlet side?
    "...MyPage.jsp?attr1=1..."
    "...MyPage.jsp?attr1=2..."
    2. Is the Servlet itself ( "public class MyServlet extends HttpServlet{..." ) also a singleton? I.e. for the above described use case also a problem?
    Thanks.

    user13612505 wrote:
    Thanks so far!
    So if I understood right:
    1.There is always only one session per client. If several servlets or several instances of the same servlet >would write an attribute with the same name to the session, this would result in an undefined result (the
    llast written value would be saved, the previos values would be lost).This is usually desirable behaviour because session attributes are normally shared by many servlets. Attributes with different significance should clearly have different names.
    The solution for this would be: different attribute names for each servlet and before calling the same
    servlet on the client side, I have to wait until the previous request to this servlet is finished.I don't really understand what you're saying here. Normally a servlet will only set a session attribute if it's to be accessed by later transactions. The whole point of session attributes is to span multiple transactions for the same client.
    If you want to store an attribute for use in the same transaction (e.g. when you forward from Servlet to JSP) store it in a request attribute, not a session attribute.
    >
    2. I don't know when the application server (I'm using glassfish) creates a new instance of a servlet. So for this problem I would also have to wait on the client side (as described above).
    No, it shouldn't matter how many instances of the Servlet are created. In general Servlets are "stateless", you don't use instance fields at all.
    Servlets are "re-entrant", that is mulitple threads may use the same servlet object to process different transactions simultaneously. So it's crucial that a servlet doesn't change any of it's fields during the course of processing a transaction, and the best way to be sure is not to have any fields at all. (You could have fields that don't change, and initialise them in the init method or constructor).

  • J2EE Question

    Hi
    I am preparing for a certification exam. I have doubt about this question. Please help me. Please let me know the correct answer
    =======================================================================
    1. Part of an application's business logic is implemented using a limited set
    of connections to a legacy system. The development team want to provide an EJB
    interface to this legacy code. The BEST approach to managing connection
    resources would be to use:
    A.     Stateful Session beans one per connection
    B.     Stateless Session beans one per connection
    C.     BMP Entity Bean one per connection
    D.     CMP Entity Bean one per connection
    Select the best answer.
    2.     When an Web module (WAR file) accesses an EJB module, what is the BEST way for a Web module to reference the EJB interfaces and client stubs?
    A.     Package the EJB interfaces and client stubs into a separate EJB Client JAR file and specify this JAR file in the MANIFEST Class-path of the Web module.
    B.     Specify the EJB JAR file in the MANIFEST Class-path of the Web module.
    C.     Package the EJB interfaces and client stubs into the Web module.
    D.     Package the EJB and Web modules into an EAR file and specify EJB jar in the Class-path property of the EAR deployment descriptor.
    Select the best answer.
    3. A developer wishes to make a server function available to an applet via a Servlet. The applet passes the Servlet a serialized object as an argument. How should the developer implement the Servlet?
    A.     Sub-class HttpServlet and create an ObjectInputStream from the
    ServletInputStream in the doGet() method.
    B.     Sub-class HttpServlet and create an ObjectInputStream from the
    ServletInputStream in the service() method.
    C.     Sub-class GenericServlet and create an ObjectInputStream from the ServletInputStream in the doGet() method.
    D.     Sub-class GenericServlet and create an ObjectInputStream from the ServletInputStream in the service() method.
    Select the best answer
    4.     A DataSource named "MyDatasource" has been created and configured (in WebSphere Application Server, Advanced Single Server Edition) to have an "idle timeout" of 30 and a "minimum pool size" of 10. If a servlet acquires a connection from that DataSource, and the servlet holds the connection for 2 minutes without using it, which statement is TRUE?
    A.     The servlet's connection will be unaffected by the idle timeout.
    B.     The pool size will be increased by 10 when some other servlet needs a connection.
    C.     After 30 seconds, WebSphere can return the connection to the connection pool
    D.     The servlet's service() method will throw a
    javax.sql.PooledConnectionException if the servlet attempts to use its
    connection
    Select the best answer.
    5.     A Web site is getting a lot of 'hits' and the amount of session data managed by the server is becoming too large for it to handle. Which of the following are appropriate ways to solve the problem?
    A.     Expand the capacity of the server.
    B.     Add additional servers to share the load.
    C.     Store the session data in a Cookie.
    D.     Store all session data in hidden fields on the web pages that are served.
    Select 2 answers.
    6.     A developer needs to create a web site that displays information about a user's BankAccount. The information is contained in a BankAccount entity bean and is guaranteed to be accurate to within 1 day of account activity. Which of the following Access beans is the BEST to use to represent the BankAccount in this scenario?
    A.     RowSet
    B.     ColumnSet
    C.     Copy Helper
    D.     Proxy Wrapper
    E.     JavaBean Wrapper
    7. A client invokes the create() method on an CMP entity bean. Which of the following is a correct sequence in which the operations mentioned below are performed?
    a.     Container creates an EJBObject.
    b.     EJB home object invokes ejbCreate() on Bean instance
    c.     Bean instance is associated with EJBObject.
    d.     Container creates new bean instance.
    e.     Container calls setEntityContext() on bean instance.
    f.     Container creates the bean representation in a database.
    g.     ejbPostCreate() method is invoked on bean instance.
    A.     b -> f -> a -> c -> g
    B.     b -> a -> f -> c -> e -> g
    C.     a -> d -> c -> b -> e -> g -> f
    D.     a -> d -> c -> b -> f -> g -> e
    E.     a -> c -> e -> b -> f -> g
    Select the best answer.
    10. While testing a BMP Entity Bean, a developer discovers that a transaction rollback does not cause a rollback of the changes made to the bean as it should. Which of the following should the developer suspect?
    A.     The ejbPassivate() method has a bug.
    B.     The ejbStore() method has a bug.
    C.     The ejbCreate() method has a bug.
    D.     The datastore does not support JTA.
    E.     The transaction does not implement javax.transaction.UserTransaction.
    Select 2 answers.
    11.     A JSP is displaying data from a JavaBean accessed through a < jsp:useBean > tag. It is an error condition if the JavaBean is not found in the request scope at runtime. What should the JSP developer do to ensure correct behavior?
    A.     Specify the real JavaBean's Java type as the value for only the class attribute of the jsp:useBean tag.
    B.     Specify the JavaBean's Java type as the value for only the type attribute of the jsp:useBean tag.
    C.     Add an isErrorPage specification in a JSP page directive.
    D.     Add an errorPage specification in a JSP page directive.
    Select 2 answers.
    12.     A Servlet must perform 3 operations that are independent of one another. They are time consuming with each operation consuming about 10 msec of CPU. The Servlet's response depends on the completion of all three operations. The developer decides to perform each operation on a separate worker thread to run them concurrently. Which of the following describe important parts of this implementation?
    A.     The Servlet should implement MultiThreadModel
    B.     The Servlet should implement SingleThreadModel
    C.     Access to the HttpSession must be synchronized.
    D.     The worker threads must not write to the ServletOutputStream.
    E.     The worker threads must not read from the ServletInputStream.
    Regards
    Arghya Banerjee

    1. B
    2. C
    3. B
    4. A (if 30 is minutes) or C (if 30 is number of seconds)
    5. B,C,D
    6.
    7. e
    10.
    11.C,D
    12.
    Let me know the answers for the rest of the questions.

Maybe you are looking for