Avatar billede fredand Forsker
29. januar 2003 - 16:40 Der er 9 kommentarer og
1 løsning

There is no session.getServletContext();

Hello!

I try to compile the classes in suns PetStore. But I cant compile RequestProcessor and DefaultWebController.

They both cant resolve this method getServletContext():
ServletContext context = session.getServletContext();

And when I look in the API for HttpSession at:
http://java.sun.com/products/servlet/2.2/javadoc/index.html
there is no method called getServletContext() in HttpSession.

What is missing?

--------------------------
A bit more code from DefaultWebController:
    public WebController getWebController(HttpSession session) {
        ServletContext context = session.getServletContext();

Please help!

Best regards
Fredrik
Avatar billede arne_v Ekspert
30. januar 2003 - 07:27 #1
getServletContext er ikke i HttpSession, men i HttpServlet (ja faktisk i en af
de klasser den arver fra).
Avatar billede arne_v Ekspert
30. januar 2003 - 07:28 #2
Let me try in english.

getServletContext is not in HttpSession, but in HttpServlet (actually in one
of the classes it inherit from).
Avatar billede arne_v Ekspert
30. januar 2003 - 07:31 #3
So you can just write:

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException {
        ServletContext sctx = getServletContext();

And I am very surprised if Sun PetStore does not use it this way !
Avatar billede fredand Forsker
30. januar 2003 - 12:15 #4
Hello Arne!

Thanks for your reply:

So you think they have a bugg? Absolutly not impossible, no one is perfect!

But please take a look at the code below.
If you can suggest a code-solution I would appreciate it.

Line with bugg in DefaultComponentManager:
ServletContext context = session.getServletContext();

Line with bugg in RequestProcessor:
action.setServletContext(request.getSession().getServletContext());

The code from the petstore demo is:
First
DefaultComponentManager:
/*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
*  notice, this list of conditions and the following disclaimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
* OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
* FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
* PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
* LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of
* any nuclear facility.
*/
package com.sun.j2ee.blueprints.waf.controller.web;

import java.beans.Beans;

// J2EE Imports
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
import javax.ejb.CreateException;
import javax.naming.InitialContext;

// WAF Imports
import com.sun.j2ee.blueprints.waf.controller.web.util.WebKeys;
import com.sun.j2ee.blueprints.servicelocator.web.ServiceLocator;
import com.sun.j2ee.blueprints.servicelocator.ServiceLocatorException;
import com.sun.j2ee.blueprints.waf.util.JNDINames;
import com.sun.j2ee.blueprints.waf.exceptions.GeneralFailureException;
import com.sun.j2ee.blueprints.waf.exceptions.AppException;
import com.sun.j2ee.blueprints.waf.controller.web.WebController;
import com.sun.j2ee.blueprints.waf.controller.web.util.WebKeys;
import com.sun.j2ee.blueprints.waf.controller.ejb.EJBControllerLocalHome;
import com.sun.j2ee.blueprints.waf.controller.ejb.EJBControllerLocal;

import com.sun.j2ee.blueprints.util.tracer.Debug;


/**
* This implmentation class of the ComponentManager provides
* access to services in the web tier and ejb tier.
*
*/
public class DefaultComponentManager implements ComponentManager, java.io.Serializable {

    protected ServiceLocator sl = null;

    public DefaultComponentManager() {
        sl = ServiceLocator.getInstance();
    }

    public WebController getWebController(HttpSession session) {
        ServletContext context = session.getServletContext();
        WebController wcc =  (WebController)context.getAttribute(WebKeys.WEB_CONTROLLER);
        if ( wcc == null ) {
            try {
                String wccClassName = sl.getString(JNDINames.DEFAULT_WEB_CONTROLLER);
                wcc = (WebController) Beans.instantiate(this.getClass().getClassLoader(), wccClassName);
                wcc.init(context);
            } catch (ServiceLocatorException slx) {
                throw new RuntimeException ("Cannot create bean of class WebController: " + slx);
            } catch (Exception exc) {
                throw new RuntimeException ("Cannot create bean of class WebController: " + exc);
            }
        }
        return wcc;
    }

    public EJBControllerLocal getEJBController(HttpSession session) {
        EJBControllerLocal ccEjb = (EJBControllerLocal)session.getAttribute(WebKeys.EJB_CONTROLLER);
        if (ccEjb == null) {
            try {
                EJBControllerLocalHome home = (EJBControllerLocalHome)sl.getLocalHome(JNDINames.EJB_CONTROLLER_EJBHOME);
                ccEjb = home.create();
            } catch (CreateException ce) {
                throw new GeneralFailureException(ce.getMessage());
            } catch (ServiceLocatorException slx) {
                throw new GeneralFailureException(slx.getMessage());
            }
        }
        return ccEjb;
    }

    /**
    *
    * Create the WebController which in turn should create the
    * EJBClientController.
    *
    */
    public void sessionCreated(HttpSessionEvent se) {
        HttpSession session = se.getSession();
        sl = ServiceLocator.getInstance();
        session.setAttribute(WebKeys.COMPONENT_MANAGER, this);
    }

    /**
    *
    * Destroy the WebClientController which in turn should destroy the
    * EJBClientController.
    *
    */
    public void sessionDestroyed(HttpSessionEvent se) {

    try{
        HttpSession session = se.getSession();
        WebController wcc = getWebController(session);
        if (wcc != null) {
            wcc.destroy(session);
        }
  }
  catch(Exception exe){
  // ignore the exception
  }
    }
}
----------------------------------------
RequestProcessor:
/*
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
*  notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
*  notice, this list of conditions and the following disclaimer in
*  the documentation and/or other materials provided with the
*  distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any
* kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND
* WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY
* EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES
* SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN
* OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR
* FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR
* PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF
* LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of
* any nuclear facility.
*/
package com.sun.j2ee.blueprints.waf.controller.web;

import java.util.Collection;
import java.util.HashMap;

// J2ee Imports
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import com.sun.j2ee.blueprints.waf.util.JNDINames;

// BluePrints/WAF imports
import com.sun.j2ee.blueprints.util.tracer.Debug;
import com.sun.j2ee.blueprints.waf.controller.web.util.WebKeys;
import com.sun.j2ee.blueprints.waf.event.Event;
import com.sun.j2ee.blueprints.waf.event.EventException;
import com.sun.j2ee.blueprints.waf.event.EventResponse;
import com.sun.j2ee.blueprints.waf.controller.web.action.HTMLAction;
import com.sun.j2ee.blueprints.waf.controller.web.action.HTMLActionException;
import com.sun.j2ee.blueprints.waf.controller.web.ComponentManager;

/**
* This is the web tier controller for the sample application.
*
* This class is responsible for processing all requests received from
* the Main.jsp and generating necessary events to modify data which
* are sent to the WebController.
*
*/
public class RequestProcessor implements java.io.Serializable {

    private HashMap urlMappings;
    private HashMap eventMappings;

    public RequestProcessor() {}


    public void init(ServletContext context) {
        urlMappings = (HashMap)context.getAttribute(WebKeys.URL_MAPPINGS);
        eventMappings = (HashMap)context.getAttribute(WebKeys.EVENT_MAPPINGS);
    }

    /**
    * The UrlMapping object contains information that will match
    * a url to a mapping object that contains information about
    * the current screen, the HTMLAction that is needed to
    * process a request, and the HTMLAction that is needed
    * to insure that the propper screen is displayed.
    */

    private URLMapping getURLMapping(String urlPattern) {
        if ((urlMappings != null) && urlMappings.containsKey(urlPattern)) {
            return (URLMapping)urlMappings.get(urlPattern);
        } else {
            return null;
        }
    }

    /**
    * The EventMapping object contains information that will match
    * a event class name to an EJBActionClass.
    *
    */

    private EventMapping getEventMapping(Event eventClass) {
        // get the fully qualified name of the event class
        String eventClassName = eventClass.getClass().getName();
        if ((eventMappings != null) && eventMappings.containsKey(eventClassName)) {
            return (EventMapping)eventMappings.get(eventClassName);
        } else {
            return null;
        }
    }

    /**
    * This method is the core of the RequestProcessor. It receives all requests
    *  and generates the necessary events.
    */
    public void processRequest(HttpServletRequest request) throws HTMLActionException, EventException, ServletException {
        Event ev = null;
        String fullURL = request.getRequestURI();
        // get the screen name
        String selectedURL = null;
        int lastPathSeparator = fullURL.lastIndexOf("/") + 1;
        if (lastPathSeparator != -1) {
            selectedURL = fullURL.substring(lastPathSeparator, fullURL.length());
        }
        URLMapping urlMapping = getURLMapping(selectedURL);
        HTMLAction action = getAction(urlMapping);
        if (action != null) {
            action.setServletContext(request.getSession().getServletContext());
            action.doStart(request);
            ev = action.perform(request);
            EventResponse eventResponse = null;
            if (ev != null) {
              // set the ejb action class name on the event
                EventMapping eventMapping = getEventMapping(ev);
                if (eventMapping != null) {
                        ev.setEJBActionClassName(eventMapping.getEJBActionClassName());
                }
              ComponentManager sl = (ComponentManager)request.getSession().getAttribute(WebKeys.COMPONENT_MANAGER);
              WebController wcc =  sl.getWebController(request.getSession());
              eventResponse  = wcc.handleEvent(ev, request.getSession());
          }
          action.doEnd(request, eventResponse);
        }
    }

    /**
    * This method load the necessary HTMLAction class necessary to process a the
    * request for the specified URL.
    */

    private HTMLAction getAction(URLMapping urlMapping) {
        HTMLAction handler = null;
        String actionClassString = null;
        if (urlMapping != null) {
            actionClassString = urlMapping.getWebAction();
            if (urlMapping.isAction()) {
                try {
                    handler = (HTMLAction)getClass().getClassLoader().loadClass(actionClassString).newInstance();
                } catch (Exception ex) {
                    System.err.println("RequestProcessor caught loading action: " + ex);
                }
            }
        }
        return handler;
    }
}
Avatar billede arne_v Ekspert
30. januar 2003 - 12:53 #5
I got it figured out !!!!

HttpSession doe snot have a getServletContext in J2EE 1.3,
but it do have one in J2EE 1.4 !
Avatar billede arne_v Ekspert
30. januar 2003 - 12:54 #6
http://java.sun.com/j2ee/1.4/docs/api/index.html

Quote:

getServletContext
public ServletContext getServletContext()
Returns the ServletContext to which this session belongs.

Returns:
The ServletContext object for the web application
Since:
2.3
Avatar billede arne_v Ekspert
30. januar 2003 - 12:58 #7
So apperently the PetShop app you have is for J2EE 1.4.

And note that 1.4 is not even final yet.

PS: If you are confused about the "version 2.3", then that is
referring to the Servlet specification version (servel 2.3 is
part of J2EE 1.4 while Servlet 2.2 is part of J2EE 1.3).
Avatar billede fredand Forsker
30. januar 2003 - 13:56 #8
Hello!

Thanks for your help mate!

I downloaded the class files from java.sun.com and after that I could compile it.

But it is really hard to find what you want at that site, don't you agree? It would be great with a site where all new extensions.jar files would be able to download.

Best regards
Fredrik
Avatar billede arne_v Ekspert
30. januar 2003 - 14:04 #9
It is not that bad.

I still think it is way esier to find the Java jar-files you need than
to find the Windows products service packs and fixes you need at
Microsoft.
Avatar billede fredand Forsker
30. januar 2003 - 16:25 #10
Yes I do agree!
Avatar billede Ny bruger Nybegynder

Din løsning...

Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.

Loading billede Opret Preview
Kategori
Kurser inden for grundlæggende programmering

Log ind eller opret profil

Hov!

For at kunne deltage på Computerworld Eksperten skal du være logget ind.

Det er heldigvis nemt at oprette en bruger: Det tager to minutter og du kan vælge at bruge enten e-mail, Facebook eller Google som login.

Du kan også logge ind via nedenstående tjenester