Accessing application methods from EL

Hi all,
I do not consider myself a newbie but I wonder sometimes when I can't solve these problem; Tomcat can be such a bugger to configure, especially when they change the schemas on every release.
Anyway. I have a couple custom tags in my header.jspf file. I use the <c:import> action to include it in all documents on that virtual host.
This is how I originally achieve this task:
<c:import url="http://home.localhost/templates/header.jspf">
     <c:param name="newsData" value="http://home.localhost/news/news_2004-06-27.xml" />
     <c:param name="menuData" value="<%= application.getRealPath("WEB-INF/home-menu.xml") %>" />
</c:import>Now I have decided to make everything xHTML compliant i.e. I no longer want to use and can not use <% ... %> scriptlet tags any more.
I do not know however, how to call methods such as application.getRealPath(...) from, EL for example?
How can I accomplish this?
I'm hoping for something like:
<c:import url="http://home.localhost/templates/header.jspf">
     <c:param name="newsData" value="http://home.localhost/news/news_2004-06-27.xml" />
     <c:param name="menuData" value="${application.getRealPath("WEB-INF/home-menu.xml")}" />
</c:import>I think instead of using application I have to use servletContext, but I do not know if a attribute key/value exists that represents the servlet-path.
Any and all help appreciates.
Kind Regards,
Darren Bishop

Hey evnafets,
Thanks for your comback.
I had actually exhaustively tried everything, including your suggestion
${pageContext.servletContext.realPath}I solved it in the end with the following:
<jsp:scriptlet>
     pageContext.setAttribute("menuData", application.getRealPath("WEB-INF/home-menu.xml"));
</jsp:scriptlet>
<c:import url="http://home.localhost/templates/header.jspf">
     <c:param name="newsData" value="http://home.localhost/news/news_2004-06-27.xml" />
     <c:param name="menuData" value="${menuData}" />
</c:import>I previously did not know that JSP scripting syntax had been changed to XML elements. It works fine but I do not like it at all... effectively Java code still remains in the page which I am not happy about; wanted clean XML code, I suppose with my definition of clean not beingthe above.
I am familiar with JSTL functions, but I can be quite stubborn if it seems that the functionality should already exist; why does the application/servletContext not have an attribute REAL_PATH or something. Then you can concatenate anything you want on the end.
Again, thanksfor reply.
Regards,
Darren B

Similar Messages

  • Access native methods from an applet

    hi all
    I am developping a applet which has to access the native method which is c++ code. but it does not work at all, even though it can be compiled well.
    it returns
    java.lang.ExceptionInInitializerError
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
         at java.lang.reflect.Constructor.newInstance(Unknown Source)
         at java.lang.Class.newInstance0(Unknown Source)
         at java.lang.Class.newInstance(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission loadLibrary.MemoInfo)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkLink(Unknown Source)
         at java.lang.Runtime.loadLibrary0(Unknown Source)
         at java.lang.System.loadLibrary(Unknown Source)
         at InfoShow.<clinit>(InfoShow.java:24)
         ... 11 more
    who can give me some suggestions on accessing native method from applet! thx
    regards
    beginner

    you don't have access to native code from an applet unless you've modified your policy file or you're using a signed applet.

  • Accessing a method from within another method

    I am having trouble accessing a method from inside a method in the same class.
    here is my code:
    public String getAns(int ans){
    answer = ans;
    ranswer = number1 * number2;
    if(answer != ranswer){
    return "No. Please try again";
    }else{
    return "Very good!";
    genQues();
    when i run this i get an Unreachable code error pertaining to genQues();
    is this allowed in Java and is there a more practical way to go about this?
    Thank you in advance

    next time use the correct code tags to post your code.
    Think of your problem like this though.
    You write
    if( something )
    then return some value;
    else
    then return some other value.
    The returns end the method here, returning the value.
    So, if the method ended at one of these 2 statements, how do you think it'll reach genQues(); ?
    Hope this helps.

  • Error while accessing EJB method from JSP

    Hi,
    I am trying to access a bean from a JSP and have the foll. code piece:
    String url = "t3://localhost:7001";
    public Context getInitialContext() throws Exception {
    Properties p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory");
    p.put(Context.PROVIDER_URL, url);
    return new InitialContext(p);
    String getStackTraceAsString(Exception e)
    // Dump the stack trace to a buffered stream, then send it's contents
    // to the JSPWriter.
    ByteArrayOutputStream ostr = new ByteArrayOutputStream();
    e.printStackTrace(new PrintWriter(ostr));
    return(ostr.toString());
    %>
    <%
    String op="";
    try {
    // Contact the AccountBean container (the "AccountHome") through JNDI.
    Context ctx = getInitialContext();
    out.println("initial context got !!");
    DemoHome home = (DemoHome) ctx.lookup("demo.DemoHome");
    out.println("home got !!");
    %>
    <p>
    <%
    Demo ac = null;
    try {
    ac = (Demo) home.create();
    out.println("create called!!");
    if (ac==null)
    out.println("ac is null!");
    catch (Exception ee) {
    out.print("exception 1");
    %>
    <p>
    <%
    try {
    out.println("going to call method!");
    if (ac!= null)
    op = ac.demoSelect(); /* FAILURE POINT */
    else
    out.println("ac is null->error!!");
    out.println(ac.demoSelect());
    out.println("string got!!");
    out.println(op);
    catch (Exception e) {
    getStackTraceAsString(e);
    e.printStackTrace();
    out.println("error 2");
    catch(Exception e)
    out.println("error 3!");
    It gives an error on trying to access the method "demoSelect".
    e.printStackTrace gives the output:
    java.lang.RuntimeException: javax.ejb.EJBContext.getEnvironment is deprecated in EJB 1.1. EJB 1.1 compli
    ant containers are not required to implement this method. Use java:comp/env instead.
    <<no stack trace available>>
    JSP output is as foll.-->
    getting initial context initial context got !! home got !!
    create called!!
    going to call method! error 2
    What is wrong???
    pls help!

    Greetings,
    Hi,
    I am trying to access a bean from a JSP and have the
    foll. code piece:
    <%
    String op="";
    try {
    // Contact the AccountBean container (the "AccountHome") through JNDI.
    Context ctx = getInitialContext();
    out.println("initial context got !!");
    DemoHome home = (DemoHome) ctx.lookup("demo.DemoHome");
    out.println("home got !!");Though it doesn't seem to be the problem in this case, good EJB coding practices dictate that your code should be narrowing the home reference before calling any of it's methods (i.e. create(...) )... WebLogic may allow handling of its protocol objects in their native state, but other vendors do not... your application is not portable without narrowing.
    It gives an error on trying to access the method "demoSelect".
    e.printStackTrace gives the output:
    java.lang.RuntimeException: javax.ejb.EJBContext.getEnvironment is deprecated inThe error is not in your JSP, but in the bean... it seems your bean is attempting to acquire its "environment properties" in the pre-1.1 style, when...
    EJB 1.1. EJB 1.1 compliant containers are not required to implement this
    method. Use java:comp/env instead. ...instead, it should be looking them up in its JNDI namespace.
    What is wrong???
    pls help! Regards,
    Tony "Vee Schade" Cook

  • How to access application module from ActionForm Execute?

    I've got a very simple ADF/UIX/Struts application where I'm trying to create a simple Login function. I have a /loginAction data action pointing to a login.uix page forward. The login.uix page has a <struts:form> on it with a user and a password field. There is a LoginBean with the corresponding get/set values. I have an ADF model created with a boolean login(String username, String password) function exposed as a client method.
    Eventually, when I have this basic part working, then I'll actually be using an ActionForward mapping to dispatch to different home pages, based on the particular login account (the name of the forward will be stored in the authentication table).
    I've tried overriding Execute(), since that is where you can return the appropriate ActionForward mapping, but that does not have a DataActionContext passed in -- so I can't get to the application module.
    I've also looked at processComponentEvents, but that doesn't have any ActionForward results nor a way to pass back ActionErrors (in case the login fails).
    How do I call my login client method when a user has entered a username/password and pressed the Submit button?

    Here is another solution as provided by Oracle Support in response to a TAR that I opened:
    I had described my need to access a login() function defined in my Application Module, returning true/false if the login succeeds/fails. Here is the reply, posted with permission:
    I have gotten the following information back from one of the development folks pertaining to the question you asked.
    His suggestions are as follows:
    1) Expose the method as a client method on the App module
    2) On the pageflow create a new DataAction
    3) Drag and drop the logon method from the AppModule operations node and drop it onto the new data Action
    3) Edit the set-property values that are created in the Struts metadata for this new DataAction to use the correct expressions to get the logon info to pass to the middle tier.
    e.g.
    <action path="/authenticateUser" className="oracle.adf.controller.struts.actions.DataActionMapping" type="AuthenticateUserAction" name="DataForm"
    unknown="false">
    <set-property property="modelReference" value="authenticateUserUIModel"/>
    <set-property property="methodName" value="authenticateUserUIModel.authenticateUser"/>
    <set-property property="resultLocation" value="${requestScope.methodResult}"/>
    <set-property property="numParams" value="2"/>
    <set-property property="paramNames[0]" value="${param.logonUsername}"/>
    <set-property property="paramNames[1]" value="${param.logonPassword}"/>
    <forward name="fail" path="/logon.do"/>
    <forward name="success" path="/menu.do"/>
    </action>
    So in this case the values of the logonUsername and logonPassword fields in the form that submitted to this DataAction are passed as the two parameters that my authenticateUser method on the AppModule requires.
    I have also overriden the data action class to customise the findForward() method to route the user depending on if the method call worked or not.
    And here's the code for the customized FindForward in the DataAction:
    protected void findForward(DataActionContext actionContext) throws Exception
    HttpServletRequest request = actionContext.getHttpServletRequest();
    HttpSession session = request.getSession();
    String target = "fail";
    //Get the result of the Model Method call
    JUCtrlActionBinding method = actionContext.getCustomMethod();
    boolean successfulLogon = ((Boolean)method.getResult()).booleanValue();
    if (!successfulLogon)
    // If the logon fails we need to do the following
    // 1. Increament the counter once this exceeds 3 any logon will fail
    // 2. Create an error message to display on the logon screen
    // note this is a non specific error to prevent hackers from
    // knowing that they at least got the username right or from
    // knowing that there is a Max attempts value if they are trying
    // an automated attack
    Integer attempts = (Integer)session.getAttribute("logonAttempts");
    int intAttempts = 0;
    if (attempts != null)
    intAttempts = attempts.intValue();
    session.setAttribute("logonAttempts", new Integer(++intAttempts));
    //The error message comes out of the ApplicationResources.properties file.
    actionContext.getActionErrors().add("general",new ActionError("logon.error.logonFailed"));
    this.saveErrors(actionContext.getHttpServletRequest(),
    actionContext.getActionErrors());
    else
    //If connection was OK do we need to save the username in a cookie?
    String remember = (String)request.getParameter("logonRemember");
    int cookieLife = 0; //Expire
    if ( remember != null && remember.length()>0 )
    cookieLife = 2592000;
    String name = (String)request.getParameter("logonUsername");
    Cookie userCookie = new Cookie("CARA_USER_COOKIE",name);
    userCookie.setMaxAge(cookieLife);
    actionContext.getHttpServletResponse().addCookie(userCookie);
    target = "success";
    actionContext.setActionForward(target);
    I hope this helps anyone looking to implement something similar. It also illustrates the "preferred" way of executing a client method and working with the result.

  • Accessing Application Scope from an EJB

    I'm not sure of the best way of doing this:
    The set up:
    We have a rather large J2EE application that is composed of only servlets and JSPs at the moment (When the application began development EJB was in its infancy and not feasible for the development of the app). Some of the new deployments of the app involve distributed webserver over 4 JVMs and 2 machines. When a user connects the servers load balancing decides which particular JVM they should be connected to. We perform large data caching into the servlet application scope to avoid having to access the database every time a change is made by a user to certain tables in our database. The data caches are stored in hashtables in the servlet application scope.We seem to have no way to determine what other JVMs are running or which JVM a user is currently connected to.
    The problem:
    Apparently the application scope is for a particular JVM. This means that when a user makes a change to a data cache the change doesn't effect users in the other 3 JVMs of the application, only the users who, due to load balancing, happened to be connected to the same JVM as the one where the change was made.
    Our possible solution:
    We were thinking that we could set up a queue (such as MQSeries from IBM) and any time a change is made to one of these data caches put a message on the stack saying that the particular table had been updated. Then a MDB would be listening asynchronously and digest the message from the Queue and recache the tables from the database.
    So here are my questions:
    1. Would this work? Would putting a MDB in the EJB Container give each JVM the MDB in the first place, or would this mean it would pick one of the JVMs to deploy the MDB on and still not fix our problem.
    2. If this does work, how do I access the hashtables stored in the Servlet Application scope from the MDB. I can't seem to find any method available to the MDB (or any EJBs for that matter) that can access the servlets Application scope.
    3. Is this the best way to do this? Or is there a better way to share data between seperate JVMs that I don't have a URL to (It's all ambiguous and handled by the server as to which JVM actually gets the connection.)
    Just in case this is needed:
    We are running IBM WebSphere 5 Application Server and the database could be anything from DB2 to Oracle.
    Thanks in advance for any possible help.

    You wont get any api for directly accessing Servlet application objects from any ejb. I dont think MDB either solves your problem directly. Indirectly you can place a request to some servlet (should be there for each JVM and web application ) and update your application scope variable. I would suggest you to cache the data in database if the size of cache is large. otherwise any open caching tools may help you.

  • ACCESSING APPLICATION SCOPE FROM FILTERS

    HI
    Is there any way to access the application scope from inside security filters? i have a class that implements the Filter interface and i'm trying to access the application scope in the doFilter method.
    The FacesContext Object is null, and i'm only able to access the session scope using request.getSession()
    I want to check for global application properties that are saved in the application scope.
    Thanks

    thank you BalusC it's working

  • Access Application Class from Model Class in BSP

    Hello,
    I am developing a BSP Application based on MVC. Is there any way, I can access the Application Class's Attribute from a Method in the Model Class?
    Thanksin Advance.
    Regards
    Gladson

    Hello,
    I solved it by passing the application class attribute to the model method, from the controller class.
    Regards
    Gladson

  • Access page method from template

    Hi,
    I'm using JDev11/ADF and I need to implement this scenario : A have a page fragment based on a page template. This page has a backing bean with a class exteded from a generic class. I have some generic buttons in the page template. Theses buttons need to call a method in the base backing bean class through the page's backing bean. I read Frank's solution to access the page's binding from the template :
    [http://thepeninsulasedge.com/frank_nimphius/2007/11/23/adf-faces-rc-implementation-strategies-for-global-buttons-in-page-templates/]
    but is there a way to access a method in the page's bean from the template (A listener for instance ?)...
    tks.

    Hi,
    what is missing is a method attribute like in declarative components. This however does not exist for templates yet. So there is no other solution yet than to invent some kind of contract.
    Frank

  • How to access application state from stateless web service?

    I have a beginner J2EE question. After reading through J2EE tutorial, I still don't know how to create an application that would run on J2EE server, and which would have a web service interface to other world, and which would have several threads running, which would connect to other enterprise applications via TCP? Because if I understand it correctly, web service requires a stateless session bean, which means that it can't access any stateleful session bean (except always create one and remove it instantly). So there seems to be no way to store application state and have running threads.
    I'm asking this because .NET seems to have a very simple Application dictionary, which can save all application objects, including threads, and it is very easy to access this Application state from a stateless web service. Isn't there any similar functionality in J2EE? And if not, how it should be done in Java world then?
    I guess that the Connector architecture could be the solution, but it is not documented in the tutorial.

    There's nothing in the J2EE spec that says that you have to use Web Services. Web Services by definition are stateless.
    If your requirements are that you have to use a session bean along with a Web Service, then the architecture needs to be rethought, because it doesn't seem to me that Web Services are what you want.
    That said, you can use a hybrid. You can expose some of the functionality of your application as Web Services while the remaining is implemented in a classic J2EE type framework that is stateful.
    I would also think that you could store your application state via entity beans. You could save and load them when the web service is accessed. An entity bean doesn't require a database... just some form of persistence (could be an XML file for instance).
    You need to decide which components of J2EE make sense when and where.

  • Cannot Access Application Module from View Project (Swing)

    I recently started a new application workspace as a Swing project with Business Components. Jdev created 2 projects by default, a Model and a View. The model works fine, all the business components are funtctioning and the DB connection is good. When i try to create a reference to the application module in my View project i constantly get 'Class Not Found' exceptions no matter what i do. I am using the jbo.client.Configuration.getRootApplicationModule('amName', 'amConfig') method.
    What am i missing? How do i instantiate my application module from my View project?
    Thanks a lot.

    Just had to add the Model to the classpath...

  • Access AM method from backing bean - best practice

    Hello,
    I need to call an appModule method from a backing bean. What is better?
    1. Resolve bindings.AMDataControl.dataProvider, get AM and invoke the method directly
    or
    2. Create method action in page definition, resolve OperationBinding from it's binding expression and execute the operationBinding
    I don't need to have a button on the page for this method.
    Rado

    Good question Rado.
    With a "flexible" framework like Oracle ADF, I also ask myself sometimes what would be the preferred approach to do things.
    See also these forum threads:
    - about "ADF Faces: Passing values from a managed bean to ADF BC module"
    http://forums.oracle.com/forums/thread.jspa?threadID=486742
    - about : "ADF Faces: getting selected row data in multi select table ..."
    http://forums.oracle.com/forums/thread.jspa?threadID=503248
    regards
    Jan Vervecken

  • No access to method from within the same class

    Hey there.
    First I have to excuse my English for I'm german and just learning...
    Ok, my problem is as follows. I have a class called JDBC_Wrapper it includes the method sendQuery(String query). When I call this method from within another class (where 'wrapper' is my instance of JDBC_Wrapper) it works fine. For example:
    wrapper.sendQuery("SELECT * FROM myDataBase");
    But then I have written a method called getNumRows() into my JDBC_Wrapper class.
    This method should send a query through sendQuery(Strin query) but when calling getNumRows() it says: "java.sql.SQLException: [FileMaker][ODBC FileMaker Pro driver][FileMaker Pro]Unbekannter Fehler." (Unbekannter Fehler -> Unknown Exception). What could that be?
    I'm using jdk2 sdk 1.4.2 with BlueJ. My database is Filemaker Pro 6. The ODBC/JDBC connector works fine.
    BerndZack

    This is within my JDBC_Wrapper class:
    public ResultSet sendQuery(String query)
            if(connected)
                try
                    Statement s = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                    ResultSet rs = s.executeQuery(query);
                    return rs;
                catch(Exception e)
                    System.out.println(e);
            else
                //System.out.println("There is no connection to the datasource!");
            return null;
    public int getNumRows()
            try
                ResultSet r;
                r = this.sendQuery("SELECT COUNT(*) FROM " + table_name); // At this line the error occurs
                r.next();
                return (int)r.getInt(1);
            catch(Exception e)
                System.out.println(e.getMessage());
                return -1;
    }When I call sendQuery() from within another class it works, but calling getNumRows()
    throws an exception.

  • Accessing a method from an outside Class

    I am working on a program that will create an array list and hashmap of 3 shapes--squares,triangles and circles. I have created classes for each shape as well as a class that creates arrays of these shapes (called ShapeGenerator).
    Now I need to create a class that will call ShapeGenerator to create the shapes and then put them into an arraylist and hashmap. Right now I just can't get seem to call the methods from ShapeGenerator to create the arrays. What follows is the code I've written. Any guidance would be appreciated. Thanks in advance...
    public class ShapeMaker{
         public ShapeMaker(){
    public ShapeGenerator[] makeShapes(){
         ShapeGenerator[] myShapeGenerator = new ShapeGenerator();
         myShapeGenerator.createSquares(5);
         return createSquares;
    public static void main(String[] args){
         ShapeMaker mySM = new ShapeMaker();
         mySM.makeShapes();
         System.out.println("I made a Shape");
    }

    ShapeGenerator[] myShapeGenerator = new ShapeGenerator();
    new ShapeGenerator will return a single instance of ShapeGenerator - Not an array.
    to create a new ShapeGenerator:
    ShapeGenerator sg=new ShapeGenerator();
    then your method call:
    Object squares[]= sg.createSquares(5);
    or you could just do:
    Object squares[]=new ShapeGenerator().createSquares(5);
    makeShapes() should then return an array of Object (or even better do you have a base Shape class?)
    So we finally end up with something like:
    public class ShapeMaker{
    public ShapeMaker(){
    public Object[] makeShapes(){
    ShapeGenerator myShapeGenerator = new ShapeGenerator();
    return myShapeGenerator.createSquares(5);
    public static void main(String[] args){
    ShapeMaker mySM = new ShapeMaker();
    mySM.makeShapes();
    System.out.println("I made a Shape");
    Excuse any typos but I have not tried to compile this as I don't have a myShapeGenerator etc and I'm too tired (or lazy) to write one.
    Good luck.

  • Access Application Services from Web Dynpro DC

    Hi Experts,
    We created a CAF DC which has an application service called ClientAppService, with a method findClientsById. We also created another DC, a Web Dynpro DC, which makes use of the model generated by the CAF DC. We have programmatic access to the application service through
    ClientAppServiceProxy.findClientsById()
    , but when running the DC which makes this call we receive the following error:
    com.sap.caf.rt.exception.CAFBaseRuntimeException: Query with name findClientsById does not exist
    We've managed to call Application Services before, but that was when the Web Dynpro was in the same DC as the CAF services. Any ideas on how to fix this?
    Thanks,
    JP

    Hi Smith,
    One of the possible reasons of this error is may be your CAF project is not properly deployed in the Server in which you have deployed your WebDynpro project. So during the execution of the WebDynpro project while it tries to invoke this findby from the Application Service of your CAF project it fails to find a match. May be by mistake you have deployed your CAF Application Service first and added the findBy method later. So if your properly deploy your total CAF project in the same server in which you have deployed your WebDynpro project it may resolve your problem.
    Thanks and Regards
    Avijit

Maybe you are looking for