Can beans access ServletContext?

I want to use my web deployment descriptor (web.xml) to store database connection parameters. Unfortunately, the only way that I know how to access the ServletContext is through the request.getServletContext() method. Since my bean classes don't have a handle on the request object, how can I access the ServletContext to get this information?
Any good practice advice from anyone?

Right but I have a bean that I want to have access the servletcontext. From the bean class itself. (not the setProperty tag in JSP).

Similar Messages

  • Can a bean access ServletContext?

    Hi!
    Please help me!
    I put initial beans to ServletContext in my servlets init() method.
    How can I get this beans (app scope) from another bean (session scope)?
    Can I reach ServletContext from a class that is not a servlet?
    Thaks!

    Please help me!
    I put initial beans to ServletContext in my servlets
    init() method.
    How can I get this beans (app scope) from another bean
    (session scope)?
    Can I reach ServletContext from a class that is not a
    servlet?Not in a normal JavaBean. You can do it with custom tags, but I guess that is not what you want.
    What you would have to do is create a setter method for the Bean:
    //This is part of the bean in session that requires access to one in servlet context
    public class SessionBeanClass ...
      private ServletBeanClass otherBean;
      public void setOtherBean(ServletBeanClass sbc) { otherBean = sbc; }
      public void getSomethingThatReliesOnOtherBean()
        if (otherBean == null) throw IllegalStateException("This Something can not be done until an object of type ServletBeanClass is assigned.");
        // rest of method
    }Then in the servlet you would need to assign the correct value, preferrably when the bean is first created.
    // somewhere in your servlet
        SessionBeanClass sessionBean = new SessionBeanClass();
        sessionBean.setOtherBean((ServletBeanClass)getServletContext().getAttribute("otherBean"));Or if you are using a JSP:
    <jsp:useBean id="sessionBean" class="my.package.SessionBeanClass" scope="session">
      <jsp:setProperty name="sessionBean" property="otherBean" value="${servletContext.otherBean}"/>
    </jsp:useBean>

  • Can servlet access Serializable Bean ?

    This is my bean below.. My jsp pages can access this bean but my servlet cannot... Do I need to make remove the Serializable interface that I am implementing right now so servlet can access ? Can serlvet access beans ?
    import java.io.*;
    import java.sql.*;
    import javax.sql.*;
    import java.util.*;
    * Re-usable database connection class
    public class ConnectDB implements Serializable{
    // setup connection values to the database
    static final String DB_DRIVER = "";
    static final String myURL = "";
    static final String USERNAME = "";
    static final String PASSWORD = "";
    static Connection con = null;
         public ConnectDB(){}
         /* Returns a connection the file that calls the method*/
         public static Connection getConnection()
              try
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                   con = DriverManager.getConnection("......");
              catch (Exception e)
                   e.printStackTrace();
              finally
              return con;
         /*Closes Connections*/     
         public static void closeConnection(Connection con)
              try
                   if (con != null)
                   con.commit();     
                   con.close();
              catch (Exception e)
                   e.printStackTrace();
    }

    A Servlet is just a Java class and so can access beans. Also, a JSP is translated to a servlet before execution so you already have a servlet accessing the bean.
    Can you post relevant code and error message?

  • Remote Delta link setup problem with Bean / Access Service

    Hello,
    I am trying to setup Remote Delta Link (RDL) between two portals. (Both portals same version - EP 7.0 EHP1 SP 05 - are in the same domain)
    I already have the Remote Role Assignment working without any issues.
    The following have been done successfully:
    1. Same user repository has been setup for both the portals
    2. Setup trust between producer and consumer (SSO working fine)
    3. Producer added and registered succesfully on consumer
    4. Permissions setup on producer and consumer
    4. pcd_service user with required UME actions setup
    I am able to see all the remote content in the Consumer portal.
    When I try to copy the remote content and paste it as local content, I am getting the following error:
    Could not create remote delta link to object 'page id'. Could not connect to the remote portal. The remote portal may be down, there may be a network problem, or your connection settings to the remote portal may be configured incorrectly.
    After increasing the log severity, I am able to see the following in Default Trace:
    com.sap.portal.fpn.transport.Trying to lookup access service (P4-RMI) for connecting to producer 'ess_int' with information: com.sap.portal.fpn.remote.AccessServiceInformation@31c92207[connectionURL=hostname.mycompany.com:50004, shouldUseSSL=false, RemoteName=AccessService]
    com.sap.portal.fpn.transport.Unable to lookup access service (P4-RMI) with information: com.sap.portal.fpn.remote.AccessServiceInformation@31c92207[connectionURL=hostname.mycompany.com:50004, shouldUseSSL=false, RemoteName=AccessService]
    AbstractAdvancedOperation.handleDirOperationException
    [EXCEPTION]
    com.sap.portal.pcm.admin.exceptions.DirOperationFailedException: Could not retrieve the bean / access service to connect with producer
    Could not retrieve the bean / access service to connect with producer
    Like you can see above, there is some bean / access service which is not retrieved successfully. I am not sure if this is a permission problem on the consumer.
    I have checked that the P4 ports are configured correctly (standard - not changed) and I am able to telnet from producer to consumer (and vice versa) on the P4 port.
    I am stuck at this point and am not able to find any information on this.
    I would really appreciate if some one can point me in the right direction.
    Thank you for reading.
    - Raj

    Hi Raj,
    Please check your config of the P4 port on the producer.  Is it really 50004 (check SystemInfo of the producer)?
    I do think there's a problem with the P4 communication since RDL requires P4 connection.
    Do you have load balanced consumer-producer connection? Please refer to this blog for further details
    Little known ways to create a load balanced Consumer – Producer connection in a FPN scenario
    Regards,
    Dao

  • Can anyone explain error: can not access a member .. with modifiers ""

    Can anyone explain why this would occur:
    javax.faces.FacesException: Can't instantiate class: 'com.package.MyBean'.. class com.package.MyBean : java.lang.IllegalAccessException: Class java.beans.Beans can not access a member of class com.package.MyBean with modifiers ""

    also if the class is not defined as public
    myClass()
    public myClass()
    i got this when building my custom class loader and it took me sometime to figure this out since my editor generates my class templates I didn't even think to check something as basic as not having a public class - hopefully this saves someone else some trouble

  • JMX - Accessing ServletContext in an MBean implementation

    How do you access the ServletContext from a class that implements an MBean interface? My application stores logs in application scope (ServletContext) and I need to access those logs from my MBean implementation.
    public class Stats implements StatsMBean {
    // How do I access ServletContext here?
    }Any ideas?

    How aboutpublic class Stats implements StatsMBean {
      private ServletContext context;
      public Stats(ServletContext context) {
        this.context = context;
      // some methods that can now use the "context" variable.
    }

  • Can we access the session scoped variable by simply using its name

    The Java EE 6 Tutorial contains a "Duke's Bookstore Case Study Example”. I could not understand following statements of this case study:
    *bookdetails.xhtml*
    {code}
    <h:outputText value="#{selected.title}"/>
    {code}
    *BookstoreBean.java*
    {code}
    public String details() {
    context()
    .getExternalContext()
    .getSessionMap()
    .put(
    "selected",
    getFeatured());
    return ("bookdetails");
    {code}
    I want to know can we access the session scoped variable in bookdetails.xhtml by simply using its name as done above?

    It is basic Expression Language (EL) functionality, it isn't even specific to JSF. And it isn't specific to the session scope either, you can put beans in any scope (page, request, session, application, flash, conversation, whatever custom scope you create) and reference it using EL by only its name. The thing that you have to take care of is that the bean lives in SOME scope, which can be achieved using JSF specific annotations or configuration files, through CDI or by manually putting the bean in a specific scope through Java code. It's flexible, which is the nature of the Java platform.

  • Reflection problem: can not access a member of class java.lang.IllegalAcces

    package org.struts.ets.utility;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Field;
    import java.lang.reflect.InvocationTargetException;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import org.struts.bean.FieldTrouble;
    import org.struts.bean.GenericDAOBean;
    public class DynamicObjectCreation
         public static void main(String... args)
              FieldTrouble ft = new FieldTrouble();
              try
                   Class<?> c = ft.getClass();
                   //Class<?> c = FieldTrouble.class;
                   /*Class<?> c = null;
                   try
                        c = Class.forName("org.struts.bean.FieldTrouble");
                   } catch (ClassNotFoundException e)
                        e.printStackTrace();
                   Field f = c.getDeclaredField("var1");
                   //f.setInt(ft, 42); // IllegalArgumentException
                   f.set(ft, new String("A"));
                   System.out.println(ft.getVar1());
                   // production code should handle these exceptions more gracefully
              } catch (NoSuchFieldException x)
                   x.printStackTrace();
              } catch (IllegalAccessException x)
                   x.printStackTrace();
    }// If I put FieldTrouble.java in any other package than the current package I am running this code from. I get the following error:
    java.lang.IllegalAccessException: Class org.struts.ets.utility.DynamicObjectCreation can not access a member of class org.struts.bean.FieldTrouble with modifiers ""
         at sun.reflect.Reflection.ensureMemberAccess(Unknown Source)
         at java.lang.reflect.Field.doSecurityCheck(Unknown Source)
         at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
         at java.lang.reflect.Field.set(Unknown Source)
         at org.struts.ets.utility.DynamicObjectCreation.main(DynamicObjectCreation.java:35)
    I tried all possible ways of creating class as:
    Class<?> c = ft.getClass(); OR
    Class<?> c = FieldTrouble.class; OR
                   /*Class<?> c = null;
                   try
                        c = Class.forName("org.struts.bean.FieldTrouble");
                   } catch (ClassNotFoundException e)
                        e.printStackTrace();
    Edited by: ..-__Kris__-.. on Feb 21, 2008 10:26 AM
    Edited by: ..-__Kris__-.. on Feb 21, 2008 10:26 AM

    Any hidden performance or memory issue here?
    Let us consider an object:
    public class SomeObject
         private String fieldA;
         private String fieldB;
         private String fieldC;
         private String fieldD;
         private String fieldE;
         //... say 50 declared fields....
         public SomeObject()
         public SomeObject(String fieldA, String fieldB)
              this.fieldA = fieldA;
              this.fieldB = fieldB;
    // getters and setters..     
    }When I create an object using the constructor with only two fields initialized such as the following code above, and look at what is happening to other fields as shown in the code below, I see that they are also AVAILABLE, now this is important, but they are set to null. What I wanted to know was, if I created an object with many fields, as many as 50 (getDeclaredFields = 50), and used a constructor with only two input fields to initialize an object, I still have 48 other fields available but set as NULL's. When I create more than 100,000 of these objects in a list and send to a .jsp page, I am unable to understand if this has more memory load than when you use a list of another object which has actually has only two declared fields in it. Each of this new object will have only two declared fields, when I say getDeclaredFields() it would return 2.
    This is where I am unable to figure out if this has anything to do with performance or memory, rather, what is the difference between the many possible ways you can initialize an object when there are too many fields which you probably won't use? Either create a new constructor with only two input arguments OR a generic constructor with all fields as input arguments but all those fields which you won't use assigned NULL's OR create another new object with only two declared fields
    SomeObject someObj = new SomeObject("abcd","cdef");
              Field[] fields = someObj.getClass().getDeclaredFields();
              System.out.println("Number of available fields: " + fields.length);
              for(int i = 0 ; i < fields.length ; i++)
                   try
                        fields.setAccessible(true);
                        System.out.println("Field " + i + ", with value: " + fields[i].get(someObj));
                        fields[i].get(someObj);
                   } catch (IllegalArgumentException e)
                        e.printStackTrace();
                   } catch (IllegalAccessException e)
                        e.printStackTrace();
              }Edited by: ..-__Kris__-.. on Mar 23, 2008 5:04 PM
    Edited by: ..-__Kris__-.. on Mar 23, 2008 5:05 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Concurrent entity beans access

    I have failed to come up with a workable solution for concurrent entity bean access on the SUN reference implementation together with cloudscape.
    I have created a test case and a webpage which describes my problem. If anyone can come up with a working solution (must work on the RI) I would be very thankful.
    Please have a look at
    http://www.offermanns.de/~rolf/ejb-concurrency/
    and tell me what you think.
    -Rolf

    Hi,
    I thought that this is a problem. But this isn't just
    about this pattern. It is a general question about how
    to get concurrent access to entity beans to work on
    the RI.Entity Beans are the shared components , same instance is being shared between all the concurrent users so if the same component is a part of the longer transaction then the component can lead to the data corruption and to avoid that you have to set the ISOLATION Level for the concurrent running long transactions.Remember the Entity beans are shared components and are shared between all the cliens not like the Sessoin BEans where different clients can get different instances.
    I tried to alter the cloudscape setting to SERIAZABLE,
    but that won't help. (from the cloudscape log, it
    seems, that the container switches back to READ_COMMIT
    before every transaction.You dont have to change the setting in the Cloudscape,you require add the Isolation-level tag in the deployment descriptor.These can take the values as
    1)READ_COMMITED
    2)READ_UNCOMMITTED
    3)REPEATABLE_READ
    4)SERIALIZABLEI hope this will help.
    Regards
    Vicky

  • ORB JNDI and Initializing Bean Access problem

    Hello,
    I am using JBuilder 7 with Mobileset 3 and Borland Enterprise Server 5.0.2.
    I am trying to run one of the sample applications that came with mobileset, I am doing the following:
    I am firstly starting the Server Side application:
    1. Start the Enterprise Server Management Agent (this starts the OSAgent on 14000)
    2. Run the BookStoreServer (this initialises the BookStoreServlet container, starts the web server and partition server)
    If at this point I continue to follow the instructions for the sample and start the client, the client throws an EOFException when it first tries to read a stream that the server is supposed to have sent back.
    Because this happens I started to look at the code on the server in detail and realised that there was a BookSearchClient which acts as a bridge for the BookStoreServlet and BookSearch session bean but this wasn't started (Which I think explains why the clients throws the EOFException).
    When I try and start the BookSearchClient in the server application I was first getting org.omg.CORBA.OBJECT_NOT_EXIST but now (and I don't know why) I am receiving the following:
    -- Initializing bean access.
    javax.naming.NameNotFoundException. Root exception is org.omg.CosNaming.NamingContextPackage.NotFound: IDL:omg.org/CosNaming/NamingContext/NotFound:1.0
    at org.omg.CosNaming.NamingContextPackage.NotFoundHelper.read(NotFoundHelper.java:72)
    at org.omg.CosNaming._NamingContextExtStub.resolve(_NamingContextExtStub.java:406)
    at com.sun.jndi.cosnaming.CNCtx.callResolve(CNCtx.java:440)
    at com.sun.jndi.cosnaming.CNCtx.lookup(CNCtx.java:492)
    at com.sun.jndi.cosnaming.CNCtx.lookup(CNCtx.java:470)
    at javax.naming.InitialContext.lookup(InitialContext.java:347)
    -- Failed initializing bean access.
    at javax.naming.InitialContext.lookup(InitialContext.java:347)
    at com.borland.samples.micro.mobilebookstore.bookstore.javaclient.BookSearchClient.<init>(BookSearchClient.java:53)
    at com.borland.samples.micro.mobilebookstore.bookstore.javaclient.BookSearchClient.main(BookSearchClient.java:172)
    I have been stuck on this for days now and am really stuck, if anyone can help that'll be excellent.
    Regards and Thanks
    John

    hi John,
    I have been stuck on this problem for 2 weeks. My servlet is tryng to lookup the home class to the session bean and crashes at runtime.
    =com.sun.jndi.cosnaming.CNCtx@d35f5f--
    What ejb-jar*.xml (if any) did you set to allow the JNDI lookup of the session bean?
    I am very keen to know!
    many thanks in advance
    Steve Gauci
    ---- code
    JNDIName = "java:comp/env/ejb/SimpleRoster";
    objref = initContext.lookup(JNDIName);
    System.out.println("after lookup of " + JNDIName);
    if (objref == null) {
    System.out.println("JNDI:" + JNDIName + ": objref=" + objref);
    System.out.println("objref found for :" + JNDIName + ": objref=" + objref);

  • I downloaded 11.1 but now can't access the store, can only view my library. I've reinstalled but still get a blank, white screen when I try to go to the itunes store. How can I get to the store for purchases?

    I downloaded 11.1 but now can't access the store, can only view my library. I've reinstalled but still get a blank, white screen when I try to go to the itunes store. How can I get to the store for purchases?

    In iTunes prefs>Store - is the Store check box unchecked?
    Did you repair pemissions with Disk Utility?
    MJ

  • How can I access my iCloud account on the web from my phone

    how can I access my iCloud account on the web from my phone
    iPhone 5 iOS 8.3
    I have iCloud turned on, location services on, find my phone works but when I try to access iCloud via Safari on the phone it takes me to a page Apple.com,
    iCloud then three options
    set up iCloud on my phone (i have)
    Install Find my phone, it is installed and it works from my MBP
    or install find my friends, I don't need that I have no friends.
    my calendars and contacts and bookmarks and all are all sync'd and working on the phone, but i thought if I typed in iCloud.com on the phone in Safari I would go to my iCloud web page that looks like this on my Mac.
    Is that NOT how iCloud should/would look on my phone via Safari?
    This is maybe a dumb question after 3+ year of iPhone'ing
    thank you for clarifying or helping me to understand
    jojoguitar_mmn_usa

    I've been playing with a Galaxy here at work and here's what I've found so far - please feel free to jump in and suggest alternative methods to configure or access the various icloud components.
    So the original Q: Can you access your icloud account on Android?
    Not entirely: the website can't be used from an android browser (not properly - even with Dolphin HD and posing as different browsers it won't load correctly.  So Find my iphone is out, so is the address book or looking at your e-mail or calendar just in a browser window
    I was able to setup my e-mail using the IMAP settings published here:
    http://support.apple.com/kb/HT4864
    Be sure to setup the account manually - and note if you have trouble using SSL try TLS (that worked for me)
    Address book is a no go so you'll have to use iTunes to sync all your contacts over to Gmail - if you still have an iPad it means managing contacts in two places though .  Same goes for your calendar - transfer it to Gmail and forget about iCloud's calendar.  Nice instructions here: http://howto.cnet.com/8301-11310_39-20064060-285/how-to-switch-from-iphone-to-an droid/
    iWork is an Apple proprietary bit so don't expect much there.
    So in my case, if I'm really going to make the switch to a Galaxy from my iPhone it really means I'm going to have to switch to using google as the backend.  The timing to swap over to a galaxy/android phone is not the greatest - given that I'd have to give up my Apple addiction (syncing photos and itunes and losing access to my device tracking).  Plus I still have an iPad and a mac and like living in the Apple ecosystem.  I think I'll wait and see what the new iPhone looks like before I commit

  • When I plug in my Ipod touch to my computer a warning appears "The program cant start because MSVCR80.dll is missing."  I can not access my Itunes library.  Also, an "error 7 Windows error 126" appears as well.  Any ideas?

    When I plug in my Ipod Touch to my computer I can not access my Itunes library.  The following message appears "The program cant start because MSVCR80.dll is missing."  Also, another message appears as well - "Error 7  Windows error 126" as well as APSDaemon.exe.
    I have NO IDEA what the heck to do.
    Any ideas?
    Thanks!

    Issues installing iTunes or QuickTime for Windows
    solving MSVCR80
    iTunes 11.1.4 for Windows: Unable to install or open
    Troubleshooting issues with iTunes for Windows updates

  • TS4002 I bought iPad and I can not access, A message appears asking me account and password when i return to the person who I purchased it from him, he told me that he forgot the account and password I want a solution to the problem, because in this way I

    I bought iPad and I can not access, A message appears asking me account and password when i return to the person who I purchased it from him, he told me that he forgot the account and password
    I want a solution to the problem, because in this way I will not benefit from the iPad

    There is no solution.  You have to provide the ID and password.  There is no way around it.  If the person you bought it from can't provide it, return it and get your money back.

  • Can't access recent Emails from mail tile in window 8.1

    Can't access recent Emails from mail tile in window 8.1.  Everything working fine until yesterday.  I can get my Emails by going to google Chrome and accessing my gmail but I like just hitting the mail tile in 8.1.  Also  is the start
    of something bad onmy computer?

    Hi,
    Could you please explain a bit for the " mail tile " mentioned here?
    If you mean to access e-mail with the Mail APP, and have issues when using it, we may first take a try with the
    Apps troubleshooter.
    More information regarding mail APP troubleshooting, please check the below TechNet Wiki:
    Troubleshooting the Modern Mail App on Windows 8
    Troubleshoot problems with an app
    If any further help needed, please feel free to update here.
    Best regards
    Michael Shao
    TechNet Community Support

Maybe you are looking for