ServletContext or HttpSession??

Hi,
I'm a new comer to servlets and I'm developing an interface to an old xBase database.
I intend to use connection pooling and want to set up one pool manager for the application.
I have heard of different methods for doing this and was planning on either
(a) inititalizing in the first page (jsp) by using the <jsp:useBean> tag with 'scope=application'
or
(b) using the init() method of a non http serving servlet which I configured to load on startup in the web.xml file for the app.
The main question I have is how would the initialized pool manager be available to the other servlets/jsp pages in the application....?
Do I put a reference to it into the session or do I use the ServletContext and store it using setAttribute()..?
all help appreciated as I'm a little confused,
Niall.

Good question.
When you declare a variable in a JSP via the jsp:useBean tag with a scope of application, the object is actually stored in the ServletContext object of the webapp. You may retrieve this value with the following code.
In the servlet,
    PoolManager poolManager = getServletContext().getAttribute("poolManager") ;NOTE:This call will return a valid poolManager object if it is executed AFTER a JSP has been called that has the jsp:useBean tag defined earlier AND the servlet is in the same WebApp as the JSP.
You may notice that I called getAttribute() with the same name as I used before in the jsp:useBean example. That is because the attribute stored in the ServletContext is keyed off that name. To ensure you only have one instance of your pool, keep the name the same on each JSP so you don't accidentally declare multiple connection pool objects.
Anything else, let me know.
Mark

Similar Messages

  • Is WL6's ServletContext and HttpSession implementation Serializable?

    As the subject stated
              Rgds,
              Raymond Mok
              

    No, they are not serializable.
              mark
              Raymond Mok wrote:
              > As the subject stated
              >
              > Rgds,
              > Raymond Mok
              

  • HttpSession

    I have an application in JHeadStart.
    On load of my application, there is a java class who gets one parameter from request:
    //DataActionContext daContext
    daContext.getHttpServletRequest().getParameter("Tipo");
    But during this application I need store this parameter, then I store this on HttpSession, but when the user load another instance of this application, the HttpSession is the same of the others.
    I need an applicationScope to store datas by application and not by Session.
    How can I do this?

    Hi!
    Try storing your data in the ServletContext, using HttpSession.getServletContext() if that's what you need. Data stored there will be accessible from every session.
    This used to be mapped to "applicationScope" in UIX.
    Sascha

  • How ServletContext and Session object differ in a Serlet

    Both ServletContext and Session allows storing objects as a name value pair set and they can be accessed across several servlets/JSP's. How do they differ?

    Hi
    The Main difference is their visibility or rather the scope of the varibles differs depending on whether they are stored in the session or the Servlet Context.
    When you say that an Object is stored in the session then it means that the Object is available to the application for duration of the particulars user's session i.e. as long as the user's session is active the Object is available though not for others who will have a different session and so will not be able to access this information.
    Whereas, when you add the Object to Servlet Context you are setting up the object to be visible throughout the application for duration of the application itself and for any component that is art of the application
    So if we have a list of Object storage/sharing mechanisms listed in descending order of object life span/visibility then we have:
    Application - ServletContext
    Session - HttpSession
    Request - ServletRequest
    Page
    Keep me posted on your progress.
    Good Luck!
    Eshwar Rao
    Developer Technical Support
    Sun microsystems
    http://www.sun.com/developers/support

  • Modifications to ServletContext, HttpSession...

    Hello all.
    Can anybody explain me motivation of having attribute management declarations (getAttribute, setAttribute, removeAttribute, getAttributesNames methods) in THREE interfaces (javax.servlet.ServletContext, javax.servlet.Request, javax.servlet.http.HttpSession)?
    I think that it could be more comfortable to extract these methods into separate interface:
    public interface AttributeContext {
    public Object getAttribute(String name);
    public void removeAttribute(String name);
    public void setAttribute(String name, Object object);
    public java.util.Enumeration getAttributeNames();
    }and
    public interface ServletContext extends AttributeContext {
    public interface ServletRequest extends AttributeContext {
    public interface HttpSession extends AttributeContext {
    }We can replace the latter three interfaces in attribute manipulation easily during development by having uniform access to attributes.
    Also I think it could be more easy for servlet container writes to work with <jsp:useBean.. scope="...">
    What is your opinion?
    Best regards,
    Stanislav V. Bernatsky.

    Good question. IS there anything like javax.servlet.Request ?
    Ora Labora.

  • Tracking session / servletcontext activity

    I'm trying to do a section in my code that will show in a webpage how many users are online, both "guests" and authenticated users.
    My user authentication is handled by simply supplying a username and password, check them against a database, and if good then their usernames get added to their httpsession as an attribute.
    I tried doing a httpsessionlistener, but i found out that as soon as the session gets created / destroyed, the listener takes over before the attributes are set, so i can't seem to use that.
    I thought that maybe a servletcontext listener is the way to go; as soon as the user logs in then the username can be saved in the servlet context and when logging out then remove the attribute.
    Is my thinking flawed, or do you know of a better way? I would appreciate your comments.

    Right now my sql_trace parameter has been set to true.If you have set this parameter at system level, then, you would probably killing database performance badly. If you set this parameter system level, each and every actions from users as well oracle background process action, records in the trace file.
    Make sure that you haven't set it system level.
    If you wanna set to a particular session, you do it either through the application or if you know the session id, you can set 10046 event for this session.
    Jaffar

  • Error 500: javax.servlet.http.HttpSession: method getServletContext()Ljavax

    I think that I have an older version of servlet class files... is there any way to solve the following issue?
    in old version, getServletContext() method isn't included in HttpSession object. is there any way to get around this problem? cuz our client has an old version... i am not sure if it's possible...
    HttpSession session = e.getSession () ;
    // Retreive our context so we can initialize the runtime settings.
    ServletContext context = session.getServletContext () ;
    i'd greatly appreciated in advance...

    sorry, in e.getSession(), "e" object comes from "HttpSessionBindingEvent"

  • Singleton VS ServletContext VS Inheritance

    I just poseted this in a reply to another thread, but I think it deservs its own.
    I'm confused on how to implemente something like a database access between two servlets, say a Login Servlet and a Registration Servlet. Both need to access cuncurrently to the database using the same connection.
    So three ways of doing this are with a Singleton Object, which handles database access. Sharing that same Object through the ServletContext and instead of having an object to handle database access, handle it in a Servlet which will then be inherited by both the Login a Registration Servlets...
    I was looking for your opinion on which would be the best way to implement this...?

    BalusC, I agree with you on all that. The thing is that I need to use a file...So I need the accesses to be handled concurrently..I do realy wish I could you a DB as it would save me all this trouble with concurrency on reads and writes...
    Here is a piece of my code:
    The object I'm using as a Singleton:
    public class Users {
         private static Users ref;
         private static final String FILENAME = "users.xml";
         private static Hashtable users = new Hashtable();
         private ReadWriteLock lock = new ReentrantReadWriteLock();
         private static XMLDecoder dec;
         private static XMLEncoder enc;
         private static int id;
         private Users() {}
         public static synchronized Users getUsers()
              if(ref == null) {
                   ref = new Users();
                   try {
                        dec = new XMLDecoder(new BufferedInputStream(new FileInputStream(FILENAME)));
                        dec.close();
                   catch(FileNotFoundException e) {
                        System.out.println("Vou criar um file novo");
                        try {
                             enc = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(FILENAME)));
                             enc.writeObject(new Hashtable());
                             id = 0;
                             enc.writeObject(id);
                             enc.close();
                        } catch(Exception ex) {ex.printStackTrace();}
              return ref;
         public Object clone() throws CloneNotSupportedException
              throw new CloneNotSupportedException();
         public User findUser(String username)
              try {
                   lock.readLock().lock();
                   dec = new XMLDecoder(new BufferedInputStream(new FileInputStream(FILENAME)));
                   users = (Hashtable) dec.readObject();
                   dec.close();
                   lock.readLock().unlock();
                   return (User)users.get(username);
              } catch(Exception e) {
                   System.out.println("There was a problem decoding XML");
                   return null;
         public boolean saveUser(String username, String password)
              try {
                   lock.readLock().lock();
                   dec = new XMLDecoder(new BufferedInputStream(new FileInputStream(FILENAME)));
                   users = (Hashtable) dec.readObject();
                   id = (Integer)dec.readObject();
                   dec.close();
                   lock.readLock().unlock();
                   User u = new User();
                   u.setUsername(username);
                   u.setPassword(password);
                   u.setId(id+1);
                   users.put(username, u);
                   lock.writeLock().lock();
                   enc = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(FILENAME)));
                   enc.writeObject(users);
                   enc.writeObject(id+1);
                   enc.close();
                   lock.writeLock().unlock();
                   System.out.println("save done");
                   return true;
              } catch(Exception e) {
                   System.out.println("There was a problem decoding XML [save fail]");
                   System.out.println(e.getMessage());
                   return false;
    }And the Login servlet
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              // TODO Auto-generated method stub
              String username = request.getParameter("login");
              String password = request.getParameter("pass");
              User usr = authenticate(username, password);
              if(usr != null)
                   HttpSession session = request.getSession(true);
                   session.setAttribute("user", usr);
                   response.sendRedirect("Home");
              else
                   response.setContentType("text/html");
                 PrintWriter out = response.getWriter();
                 out.println("<html>");
                 out.println("<head>");
                 out.println("<title>Hello World!</title>");
                 out.println("</head>");
                 out.println("<body>");
                 out.println("<h2>El username/password no es valido!</h2>");
                 out.println("<a href=\"Login\">Ententar otra vez!</a>");
                 out.println("</body>");
                 out.println("</html>");
         private User authenticate(String username, String password)
              Users tmp = Users.getUsers();
              User usr = tmp.findUser(username);
              if(usr != null)
                   if(usr.getPassword().equals(password))
                        return usr;
              return null;
         }

  • WL6.1 sp2: It seems there isnt' HttpSession.getServletContext() method

              Hi all,
              In the release notes (features & changes section) we can read that the getServletContext()
              method has been added to HttpSession but we get an NoSuchMethodError exception when
              we invoke it.
              Whats going wrong?
              TIA.
              Pablo.
              

              Thanks all,
              So, there is no way to get the ServletContext from the Session?
              We need to do it without the servlet (we use the wep app context to store global
              common data for all the users).
              Deepak Vohra <[email protected]> wrote:
              >ServletContext ctx=getServletConfig().getServletContext();
              >
              >Pablo wrote:
              >
              >> Hi all,
              >>
              >> In the release notes (features & changes section) we can read that the
              >getServletContext()
              >> method has been added to HttpSession but we get an NoSuchMethodError exception
              >when
              >> we invoke it.
              >>
              >> Whats going wrong?
              >>
              >> TIA.
              >> Pablo.
              >
              

  • How to share HttpSession between different web application ?

    I have two web application ( ie two different war files), I discovered that the jsp in the two war files are not able to share the HttpSession, may I know how to you share the HttpSession between two different web application ?

    From the api doc:
    "Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another."
    You can not share a Session object between web apps. You can create your own sessions using a database, textfile or hashmap. Do a search on the O'Rielly web site for psuedo-sessions.

  • HttpSession.setAttribute( name,object ) object- vector

    In HttpSession we have void setAttribute(name,object)
    and object getAttribute(name
    In this can i set the vector as an object in
    setAttribute(name,object) and retreive the vector by
    casting in the getAttribute(name) ?
    The code ....
    Vector v = new Vector();
    // adding elements in vector
    session.setAttribute(name,vector);
    Vector recV = (Vector)session.getAttribute(name);
    is it possible ?
    Thank you
    elango

    Yes. Session.setAttribute(), ServletContext.setAttribute(), etc. are all dictionary lookups.

  • Alternative to ServletContext.getRealPath() for unexploded WAR files in BEA

    Hi,
    at some point of my app I have this:
    HttpSession sessao = request.getSession();
    ServletContext context = sessao.getServletContext();
    String path = context.getRealPath("/resources/xml/Menu_Items.xml");
    SAXBuilder builder = new SAXBuilder();
    doc = builder.build(new File(path));which works fine in development mode but when I deploy it i get a null pointer exception.
    How can I overcome this?
    thanks in advance,
    Manuel Leiria

    Hi Manolo
    The right way to do this, ussually is:
    1) Dinamically obtain realPath of application (ej.
    c:/appserver/websapps/mywebapp)
    2) Add to realPath of app relative sub folder (ej.
    resources/xml/Menu_Items.xml)
    String appRealPath=
    super.getServletContext().getRealPath("/"); // in
    your servlet
    String filePath= appRealPath +
    "/resources/xml/Menu_Items.xml";;)Hi,
    getServletContext().getRealPath doesn't work if the war file is unexploded. Anyway, I've found a workaround using
    URL path = this.getClass().getResource("Menu_Items.xml");
    and putting the xml file in the same dir of the class file.
    Manuel Leiria

  • HttpSession Re-validation challenge

    Hi All,
    I have 2 ears deployed on a server. ear1 access the other for some services and ear2 can be accessed independently too. Session timeout...invalidates the session on ear 1 even when user is continuously hitting the ear2. All I want is to somehow reset the timeout clock in session on ear 1 by doing anything... like issuing a dummy request to the ear1 for example so that session doesn't timeout. But how do I issue a request to ear1 from ear2? I am using a ServletFilter implemented in ear2 to access the session object of ear1. I use ServletContext to share the session object accross ears..see the code below. Any quick help is greatly appreciated. Thanks a lot!
    public class AuthorizationFilter implements Filter
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
    ServletContext ear1Ctx = config.getServletContext().getContext("/EAR1");
    ServletContext ear2Ctx = config.getServletContext().getContext("/EAR2");
    Map sessionMap = (Map) ear1Ctx.getAttribute("sessionMap");
    if(sessionMap != null)
    session = (HttpSession)sessionMap.get(sessionID);
    Edited by: neel26 on Aug 12, 2008 3:46 PM
    Edited by: neel26 on Aug 12, 2008 3:48 PM

    Hi,,,,,,
    There is No Performance Issue...... Possible reasons could be.....
    (1)- As MARA is the Master Table for Materials.....
    (2)- It could be the requirement of the Program......
    Thanks
    Saurabh

  • Httpsession problem on windows 2000 nt sp3(session track)

    I set up the weblogic 6.1 sp3 on the windows nt 2000 sp3.
    I put the two jsp(t1.jsp, t2.jsp) at the default web.
    t1.jsp:
    <%
    HttpSession ses = request.getSession(true);
    out.println("id1:"+ses.getId());
    %>
    test
    t2.jsp:
    <%
    HttpSession ses = request.getSession(true);
    out.println("id2:"+ses.getId());
    %>
    When I link the t1.jsp from the localhost, the session id1 and id2 are the
    same.
    But I link the t1.jsp from the remote and use IE6 sp1, the session id are
    not the same.
    However I use Opera browser from the remote to link t1.jsp, the session id1
    and id2 are the same.
    Is this the bug for windows nt 2000 sp3 or IE6 sp1?

    I have the exact same symptoms on a Win2000 Pro development machine. fails at ifsmount,same as you...

  • How to get multiple values using HttpSession.getAttribute(java.lang.String)

    Hey Guys
    I'm trying to find a way to get multiple values using the following method
    HttpSession.getAttribute(java.lang.String)
    Here's the scenerio. Its a already written application and now i'm trying to make some changes. earlier in the jsp page a combo box was used and value was retrieved in the servlet using the getAttribute method of Session. Now I'm using a html multiple selection list and have to retrieve all the values selected in the list in the servlet. Can anyone please suggest me how to do that. HTTPRequest class has a method getParameterValues which will let me do that but i have to do is using HTTPSession.
    Thanks for your time to read this

    I'm not sure what you are trying to do. You can only use session.getAttribute to retrieve something that has already been stored in the session with a previous setAttribute. If you need to store multiple values under one attribute name using setAttribute, you can store an array, or an ArrayList or whatever type of Collection you want. The request.getParameterValues method is the only way you can retrieve form parameters than can have multiple values. If the servlet hasn't already processed these parameters and put them into the session for you, you have to use request.getParameterValues.

Maybe you are looking for

  • Apple TV, menu button on remote does not work???

    I updated the firmware usiing iTunes, but the problem is still there.

  • Web Part Error From build-in "Contacts" App

    My SP 2013 Foundations has been functioning normally for the past few months until this week. I added the built-in "Contacts" app back when the site was built. This week for some reason when I go to click "Add", I receive the following error: "Web Pa

  • When I press command F to search, I am always sent to the bottom of the page.

    After this happens, I can never go through individual results by pressing enter. I have to scroll back up through the entire page to find the highlighted words, which can take a very long time. Does anyone know why this is happening and how to fix it

  • Executing "at" command of UNIX through JSP

    Friends, 1. "at" command in UNIX execute Unix command at a scheduled time. 2. For each user there will be a table maintained internally which can be accessed by "at" with "-l" argument. 3. A mail will be sent to the owner with the output of the comma

  • Oracle 11g - ALU32UTF8 - Application Issue

    I currently migrated to 11g - and chose to use AL32UTF8 multibyte character set. This is a challange when the application using this DB is comunication with a third party application through MQ and flat files. Senacrio: A Column in a table in my DB i