Servlet Context in a Nutshell??????

I am a newcomer to Servlets and relatively new to Java. I have not found a very clear explanation of what a servlet "Context" is and can therefore only assume that its so simple as to not need further explanation.
Here goes;
1. You write your Servlet code, compile it.
2. If you add this Servlet to the classes directory of a web-app called "MyWebApp" then the context for that particular servlet is "/MyWebApp"
3. Adding it to the classes directory of other web apps gives a different "context" for each one.
4. You can add a servlet to a web-app ("context") by adding the servlet URI to the deployment descriptor of the web-app????????(THis one I am really not sure of)
Summary: The context of a particular servlet is the name of the particular web-app within which it resides or is referred to
Maybe some of you experts out there could shed some light on this and I could create a document explaing context a post it on the web sowmwhere for other poor beginners like myself.
Thanks in advance.

Well, some experts will wanna kill me for told that, but, lets go....
Comparing with the JVM, a context is like a class path (of course they have many differences). In other worlds the context is a directory (or war file) where the web server (for example TOMCAT) wiil search your .class files (or.war, .jar, etc...)
All context are "pointed" to a dir, for example you can point the context /myapps to a dir of your OS (for example /home/your_username or in a windows system - C:\Program Files.
Then when you acces this context at the browser, the browser will show this directory hierarchy. For you execute your servlet you need to create a WSDL (the descritor file). This file is nothing more than a XML document (that had rules) and link a servlet at a context, (for example the servlet Hello can pointed to the path /hello, and then, this servlet is "install" at the context /myapps). After this, you can access your servlet at the path http://computer_address/myapps/hello.
Note: Step by step, you need:
1) create the web application strucuture directory (the WEB-INF, classes, etc...)
2) write the servlet
3) write the web.xml
4) compile the servlet
5) create a context - point the context to the web app structure "father"
6) install this servlet at the context
7) access the servlet
I hope this help you to understand some things, but for learning I recomended the Tomcat manual!!!! Good Luck.
Giscard

Similar Messages

  • How can I get the servlet Context from a WebService Implementation?

    I have made a webservice endpoint, using the conventional way (WSDL->wsimport->Java interface->implementation) . I need to get the servlet context below the implementation class. I haven't found any way to get the servletContext though. Any clues? Any help will be greatly appreciated.

    yes  i can found the words's unicode form Cmaps where may be at the type of tounicde and another Cmaps table just like "Adobe-GB1-GBK-EUC" ,but when the word dont have either of them how can i do? when i write a chinese word "一",it just the winansi encoding ,  there is not Cmap for me to use to change the "G208f" to the word "一"'s unicode value.
                   best wishes      thank you very much

  • Is it possible to create a file in servlet context? pls help me

    Is it possible to create a file in servlet context? pls help me

    Surely it is possible.File file = new File(path, name);

  • How to set a new attribute in th Servlet Context from an external app.

    Hi,
    I need to do an external application that can access to the servlet context to recover/modify some attributes. Anybody know how can I do it?.
    I've revised some mBeans thinking that they can serve me the servlet context, but I have not viewed anything related.
    Best Regards
    Antonio

    I'd say your best bet is adding another servlet and mapping to your application that presents a REST interface to this information. You could return application-scope data in a small XML document, and you could send attribute names and values with request parameters.
    It's not practical to dynamically change the actual init-params of the servlet context.

  • Servlet Context problem.

    have two classes, one is a servletcontextlistner implementation and another one is the actual servlet that will call the first class.
    I am trying to have a counter in a servlet that keeps track of how many users have used the servlet. I like to store that in a servletcontextlistener and then call the counters value in the servlet. and also update that counters value.
    how can I do this ? are there any good examples that you know ? please help, as i have been stuck on this for manny hours.
    ServletContextListner implementation.
    public class counterContextListener implements ServletContextListener{
    String initialValue = "0";
    public counterContextListener(){}
    public void contextDestroyed(ServletContextEvent event){}
    public void contextInitialized(ServletContextEvent event){
    ServletContext context = event.getServletContext();
    context.setAttribute("countername", initialValue);
    public static String getCounterValue(ServletContext context) {
    String value = (String)context.getAttribute("countername");
    if (value == null) {
    value ="0";
    return(value);
    }//getCounterValue
    } // end of class
    Servlet
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws
    ServletException, IOException{
    con = null;
    res.setContentType("text/plain");
    ServletInputStream sis = req.getInputStream();
    DataInputStream dis = new DataInputStream(sis);
    String username = dis.readUTF();
    dis.close();
    PrintWriter out = res.getWriter();
    System.out.println("The user has come:"+username+" " +count_users);
    //Using servlet context to get the current counter
    ServletContext context = getServletContext();
    String counter = getCounterValue(context); // passing context object.
    Error
    C:\Program Files\Apache Group\Tomcat 4.1\webapps\mudServlet>javac mudServletTTT.java
    mudServletTTT.java:36: cannot resolve symbol
    symbol : method getCounterValue (javax.servlet.ServletContext)
    location: class mudServletTTT
    String counter = getCounterValue(context);
    ^

    Why would you make the Context Listener also responsible for keeping track of the counts?
    1st of all, you are doing this inside the Servlet:
    String counter = getCounterValue(context); // passing context object.
    But the servlet does not have a mehtod called getCounterValue. You need to call the CounterContextListener's method, which means you have to create one:
      CounterContextListener ccl = new CounterContextListener();
      String counter = ccl.getCounterValue(context);Second, why give the counter context listener two jobs that it doesn't need? You should make a new object - a Counter class:
    public class Counter {
      private int count;
      public Counter() { this(0); }
      public Counter(String initialValue) {
        this(Integer.parseInt(initialValue);
      public Counter(Integer initialValue) {
        this(initialValue.intValue());
      public Counter (int initialValue) {
        count = initialValue;
      public Integer getCount() { return new Integer(count); }
      public void increment() { addCount(1); }
      public void decriment() { addCount(-1); }
      public void addCount(int amountToAdd) {
        count = count + amountToAdd;
    }Then in your context listener, all you do is add one of these to the context:
    public class CounterContextListener implement ServletContextListener {
        public void contextInitialized(ServletContextEvent sce) {
            ServletContext context = sce.getServletContext();
            Counter counter = new Counter();
            context.setAttribute("counter", counter);
        public void contextDestroyed(ServletContextEvenet sce) {
        }In your servlet, you get the counter from the context, get the count, and increment it if you want to:
    public void MyServlet exctends HttpServlet {
        public void doPost( ... ) ... {
            ServletContext context = this.getServletContext();
            Counter counter = context.getCounter();
            int count = counter.getCount();
            counter.increment();
    }

  • I want to use static variable instead of using variable in servlet context

    Hi all,
    In my web application i have to generate a unique Id.
    For this, At the application startup time i am connecting to the database and getting the Id and placing it in the servlet context.
    Every time i am incrementing this id to generate a unique id.
    But, now i want to place this id in a static variable which is available to all the classes.
    why i want to do this is to reduce burden on servlet context.
    my questing is, is this a best practice ? If not please give me your valuable suggestion.
    thanks
    tiru

    There isn't a problem with this as long as you want to share the value of that variable with all requests. If this is read-only except when it is first set then you're fine. The only real issue will be how to initialize and/or reinitialize the variable. When the servlet is started, how will you get the value for the variable? If the servlet is shutdown and restarted (a possibility in any application server) how will you re-read the variable? You need to answer these questions to decide the best route. It may be as simple as a static initializer or it may be more complex like a synchronized method that is called to see if the variable is set.

  • How to set the servlet context path manually in Tomcat web server.

    I tested some servlets by putting them in the folder , which the tomcats examples application uses (ie Tomcat 4.1\webapps\examples\WEB-INF\classes\) and it appeared to be working fine.
    I was calling the servlet like this : http://localhost:2006/examples/servlet/TestServlet
    But when I installed my own WAR file in the server , the servlet is not working now. now the new location of my servlets is : Tomcat 4.1\webapps\MyApp\WEB-INF\classes\
    and I'm trying to call the servlet like this : http://localhost:2006/MyApp/servlet/TestServlet
    The error , what i'm getting is :
    description :The requested resource (/MyApp/servlet/TestServlet) is not available.
    Some body please tell where I'm making the mistake ? I believe this may have something to do with the servlet context path setting. If anybody has any idea , how to set the path..will be much appreciated.

    Thanx for your reply , at first I was not using any web.xml(since not mandatory) but even after using the web.xml file the error is coming . Please have a look into the contents of the web.xml file and let me know if you find any problem...
    <?xml version="1.0" encoding="ISO-8859-1"?>
    <!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
    <servlet>
    <servlet-name>TestServlet</servlet-name>
    <servlet-class>TestServlet</servlet-class>
    </servlet>
    </web-app>
    one more thing I would like to tell you here. I was just looking into the configuration of Iplanet web server..I found that , there are options to set the servlet container path (like : - Prefix: /servlet
    Servlet Directory: /ecomm/iplanet/nes60/product/docs/container )
    so from here I came to know that "container " is the folder where we should put our servlets and it has URI as "servlet" but yet I'm not able to find any option in the Tomcat Web server to set the servlet container to any different directory.
    If you have any idea please let me know.

  • Getting hold of the servlet context within a filter

    How can I get hold of the servlet context from within a filter?

    The Filter has a FilterConfig that contains the ServletContext.
    class myFilter implements Filter {
       private FilterConfig config;
      public void init(FilterConfig filterConfig)
              throws ServletException {
            this.config = FilterConfig;
        public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
                  throws java.io.IOException,
                         ServletException {
              ServletContext context = this.config.getServletContext();
    }

  • Can we create a session from application(Servlet Context)

    hi i m newbie in J2ee ,
    we can easilly create session from request object ,so can we create a
    session from application object(Servlet context),
    by which objects we can create a session.? plz help me

    hi i m newbie in J2ee ,
    we can easilly create session from request object ,so can we create a
    session from application object(Servlet context),
    by which objects we can create a session.? plz help me

  • Design pattern of servlet context

    hi all
    can u please tell me what design pattern is used in servlet context.
    thanks

    http://www.google.com/search?hl=en&client=netscape-pp&rls=com.netscape%3Aen-US&q=design+pattern+for+servlet+&btnG=Search

  • Data sharing with cross servlet context

    Hello,
    Is it possible to share data between two servlet context?
    I tried to use RequestDispatcher to forward to another JSP from one context to other context. Before forwarding, I set some object in the destination context, and retrieved from the destination JSP, but it just raised ClassCastException ....
    // assume the current context is /test1
    ServletContext sContext = getServletContext().getContext("/test2");     
    RequestDispatcher dispatcher = sContext.getRequestDispatcher("/index.jsp");
    sContext.setAttribute("mybean", myBeanObj);
    dispatcher.forward(request, response);
    from the /test2/index.jsp, I tried to retrieved the value :
    MyBean bean = (MyBean)pageContext.getServletContext().getAttribute("mybean");
    and it raised "java.lang.ClassCastException"
    Please help !!
    Eric

    try {
    What about setting from a servlet that is loaded on startup and never called?
    catch () {
    Then what is the context for ;-)
    finally {
    What would be the best way to pass "global" constants among servlets?
    Thanks in advance.

  • Error creating servlet context

    Hello, there!
              I am trying to run a web app on WebLogic. The application contains some
              EJBs, several JSP's and a controller servlet. I have the EJB's
              deployed, and both webApp and servlet (and its initArgs) registered in
              "weblogic.properties". However, when I start weblogic, there is a
              message saying that "error creating servlet context for the web
              application". It seems that weblogic is looking for a file called
              "weblogic.xml" and trying to create servlet context from it. How to
              create this "xml" file? If it has to be created manually, what are the
              required tags?
              Thanks!
              Jeff
              

    Search your WL install directory for weblogic-web-jar.dtd.
              Cameron Purdy
              "Jeff Wang" <[email protected]> wrote in message
              news:[email protected]..
              > Hello, there!
              >
              > I am trying to run a web app on WebLogic. The application contains some
              > EJBs, several JSP's and a controller servlet. I have the EJB's
              > deployed, and both webApp and servlet (and its initArgs) registered in
              > "weblogic.properties". However, when I start weblogic, there is a
              > message saying that "error creating servlet context for the web
              > application". It seems that weblogic is looking for a file called
              > "weblogic.xml" and trying to create servlet context from it. How to
              > create this "xml" file? If it has to be created manually, what are the
              > required tags?
              >
              > Thanks!
              >
              > Jeff
              >
              

  • Getting servlet context in a web service

    Hi,
    I have a problem but have no solution to it and am not sure of the approach.
    I am creating a web service. Some parameters will be passed to this web service. I need to capture these parameters and put it in a hash table so that it is available to another applicatins servlet context i.e.
    there will be two calls .
    first the web service is invoked and the parameter is stored in the hash table of the applications servlet context.
    Next when the application is invoked it shud refer to the hash table and get the data in the hash table that was stored by the web service and process it.
    How can this be achieved?

    Well, some experts will wanna kill me for told that, but, lets go....
    Comparing with the JVM, a context is like a class path (of course they have many differences). In other worlds the context is a directory (or war file) where the web server (for example TOMCAT) wiil search your .class files (or.war, .jar, etc...)
    All context are "pointed" to a dir, for example you can point the context /myapps to a dir of your OS (for example /home/your_username or in a windows system - C:\Program Files.
    Then when you acces this context at the browser, the browser will show this directory hierarchy. For you execute your servlet you need to create a WSDL (the descritor file). This file is nothing more than a XML document (that had rules) and link a servlet at a context, (for example the servlet Hello can pointed to the path /hello, and then, this servlet is "install" at the context /myapps). After this, you can access your servlet at the path http://computer_address/myapps/hello.
    Note: Step by step, you need:
    1) create the web application strucuture directory (the WEB-INF, classes, etc...)
    2) write the servlet
    3) write the web.xml
    4) compile the servlet
    5) create a context - point the context to the web app structure "father"
    6) install this servlet at the context
    7) access the servlet
    I hope this help you to understand some things, but for learning I recomended the Tomcat manual!!!! Good Luck.
    Giscard

  • Servlet Context

    Could anyone please clarify me the meaning of the following line:
    "if the app is distributed, there's one ServletContext per JVM!"
    The above line I've quoted from head first book page no. 159. One thing has been cleared that, there's one ServletContext per web app, but still not able to grab the above quoted part specifically.
    Thanks in advance.

    For example, in online stores UI(view) might be designed in Java and gateway might be in some other language, this is called distributed.No doubt this is an example of distributed application, but in current context you are going out of track.
    In core there will be only one ServletContextWhy and how? If different parts of an application developed using different languages (assuming technology) are deployed in different platforms using different run times, then how they can have same servlet context?
    Here is the explanation:
    Usually any web application will have only one servlet context. However, in case of large applications to handle high number of concurrent users, typically web application is deployed in clustered environment. It means, same web application is deployed (and cloned) in multiple application server nodes. Each application server node has its own JVM (run time). In this scenario each application server will have different servlet context. That is why in your book it is written - If web application is distributed, there is one servlet context per JVM.
    Thanks,
    Mrityunjoy

  • Refreshing servlet context data

    I am binding few lists to the servlet context as they are required application wide,when init() method of one of the servlets is called.
    Now I have requirement to refresh this data on daily basis without restarting the server.How this can be done?

    If it's daily then you can create a java.util.TimerTask and apply it to a java.util.Timer to run every 24 hours.
    Cheers,
    Anthony

Maybe you are looking for

  • Billing doc thru mutlipe deliveries

    Hi all, How to create a single billing doc with multiple deliveries and multiple sales orders. could any one give me the details. thanks

  • Installing Oracle 8.1.6 on Red Hat Linux 7.0

    I have installed Oracle on Win NT quite a few times. I am trying to get my hands dirty with Oracle on Linux. I have religiously followed all the steps in the installation guide except for changing kernel parameters and recompiling, as I was not very

  • 2 iphones, 1 itunes

    My husband and I both have the iPhone 3G and use my computer to link to iTunes. Can he buy apps that I have already downloaded if we use the same account or do I need to set up a new account for him? Also, his phone is currently set up under my accou

  • Billing Document- Condition types- report -reg

    Hi experts, 1. I see a billing document in VF03, 2. I select a line item and click on pricing button. 3. I get all the pricing condition types and the corresponding values against them.        Pls let me know how do I get the values of "Net Value Bef

  • Java is not working when I try to access a "portal" in my company's intranet.

    Nothing loads, but if I run the same page on internet explorer, it loads and I see a little popup saying that Java is being used. == URL of affected sites == http://maconomy.rgl.com/cgi-bin/Maconomy/MaconomyPortal.rglprod.RGLUS.exe/Framework/maconomy