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();
}

Similar Messages

  • Servlet Reloading Problem!

    JSP + Bean is OK!
    But, Servlet + Bean occur a reloading problem.(Reloading does not happen)
    For example,
    1) TestClass.java (Bean)
    public class TestClass {
    private String txt;
    public TestClass() {
    txt = "Test!!"; ---(1)
    public String getTxt() {
    return txt;
    2) Test.java (Servlet)
    public class Test extends HttpServlet {
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    TestClass testClass = new TestClass();
    PrintWriter out = res.getWriter();
    out.println(testClass.getTxt());
    In above examples, though I change txt String(number (1)) Bean reloading does not occur. So old txt String shows.
    In Tomcat, such problem does not happen.
    Is this a problem of OC4J?
    Thanks.
    null

    Well, only servlets are supposed to be reloaded, not their dependent classes.
    If you are using Tomcat 4.x, then there might be an explanation. It seems that Tomcat 4.x will simply reload the entire web app context if it detects that a servlet (not a JSP!) has changed. Just define a servlet context listener to see that.
    Regards,
    Vadym

  • 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 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

  • Is WL cluster servlet-context ?

    Hi
              I wish to use servletContext object to cache
              value objects on a server which is in a clustered env.
              Is WL cluster servlet-context? Will I face any problems if I use servlet-context for caching purpose?
              Your feedback on this query is greatly appreciated.
              Thanks
              Jery
              

    Jery,
              ServletContext is not serializable. Use HTTPSessions to store your value objects.
              Jery Vincent wrote:
              > Hi
              >
              > I wish to use servletContext object to cache
              > value objects on a server which is in a clustered env.
              >
              > Is WL cluster servlet-context? Will I face any problems if I use servlet-context for caching purpose?
              >
              > Your feedback on this query is greatly appreciated.
              >
              > Thanks
              > Jery
              

  • 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 Compilation Problem !

    Hi,
    I am just starting to learn servlets and I got problem in compiling them. I got compilation error in
    import javax.servlet.*;statement. Seems that the compiler cannot find the servlet package. I got J2EE 1.4 beta installed on my machine but there is no servlet.jar package. I am using J2SDK 1.4.1_02, J2EE 1.4 beta and Tomcat 4.1.24.
    Can anyone help me with my servlet compilation problem?
    Thanks in advance!
    Josh

    servlet.jar is here :
    <tomcatdir>\common\lib
    add it to your compiler classpath

  • Servlet chaining problem..

    import java.io.*;
        import javax.servlet.*;
        import javax.servlet.http.*;
        public class Deblink extends HttpServlet {
          public void doGet(HttpServletRequest req, HttpServletResponse res)
                                       throws ServletException, IOException {
            String contentType = req.getContentType();  // get the incoming type
            if (contentType == null) return;  // nothing incoming, nothing to do
            res.setContentType(contentType);  // set outgoing type to be incoming type
            PrintWriter out = res.getWriter();
            BufferedReader in = req.getReader();
            String line = null;
            while ((line = in.readLine()) != null) {
              line = replace(line, "<BLINK>", "");
              line = replace(line, "</BLINK>", "");
              out.println(line);
          public void doPost(HttpServletRequest req, HttpServletResponse res)
                                        throws ServletException, IOException {
            doGet(req, res);
          private String replace(String line, String oldString, String newString) {
            int index = 0;
            while ((index = line.indexOf(oldString, index)) >= 0) {
              // Replace the old string with the new string (inefficiently)
              line = line.substring(0, index) +
                     newString +
                     line.substring(index + oldString.length());
              index += newString.length();
            return line;
    What is pre request fo above code to work.
    I had tried this many time but it is not working, what will be calling servlet look like

    And can you explain why your title is "Servlet chaining problem"?

  • 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.

Maybe you are looking for

  • Problem with JTextPane and StateInvariantError

    Hi. I am having a problem with JTextPanes and changing only certain text to bold. I am writing a chat program and would like to allow users to make certain text in their entries bold. The best way I can think of to do this is to add <b> and </b> tags

  • Does iPad change the resolution of a high res photo?

    I read that if I use the Camera Connection Kit to load photos directly from my camera to the iPad, that the iPad "modifies/reduces" the resolution of the jpeg (if they were taken with a high res camera). Anyone know if this is really true? And if yes

  • 403 error after installing SuPHP

    Hi all, I've installed SuPHP on  my machine to develop website locally. However, When I visit either my localhost or a virtualhost on my machine I get a 403 forbidden error. I have checked my permissions and they are ok. However, I have PHP myadmin i

  • ORA-29855: error occurred in the execution of ODCIINDEXCREATE routine

    I am receiving the following error from FME(safe software) when creating a spatial index. I have ruled out several of the common causes as reported in this forum because the procedure works for dataset with 300,000 rows of less but fails with the ful

  • Bridge issues with opening photos in photoshop

    Today I shut down my computer and when I opened it I can't open pictures from bridge to photoshop.  It only gives me preview as an option.  I have a Mac.  I reset preferences and that didn't fix it.  Any suggestions.