Wrox Home  
Search P2P Archive for: Go

  Return to Index  

servlets thread: Why my context can't be keep in servlet?


Message #1 by Edward <zhangsc@n...> on Thu, 30 May 2002 10:47:03 +0800
Hello
   I have a question about context,I found I can't keep errorfile in Servlet. I want to save context in servlet,for example,I read
data from a file "error.txt",and form a hash table,and put it into the context in servlet,then I deploy it with Tomcat and not stop
Tomcat in order to making Tomcat running all the times.In servlet,I get data from hash table,it is ok. Then I only modified data in
the file "error.txt" and not modify my program,and I visit servlet again with IE to get data again from hash table,it should be
original data,but it is new data.I don't know why? Context in servlet should be kept in Web,but why my program can't keep it. My
program is follows:

//PreReadError.java
public class PreReadError
{
 Hashtable table=new Hashtable();
 public PreReadError()
 {
  String text;
  BufferedReader  input;
  String str1,str2;
  int locate;      
  try
  {
       InputStream is = this.getClass().getResourceAsStream("error.txt");
       input = new BufferedReader(new InputStreamReader(is));
       /*error.txt format,such as:
       Error1:Not found
       Error2:Redirect
       Error3:Bye*/
       while((text=input.readLine())!=null)
       {
        locate=text.indexOf(":");
        str1=text.substring(0,locate);
        str2=text.substring(locate+1,text.length());
        table.put(str1,str2); 
       }
       input.close();
   }
  catch(IOException e)
  { e.printStackTrace();
   }
 
 
 //If success,return string ,or return null
 public String getTable(String str)
 {
  String result=(String) table.get(str);
   return result;
 }
}


//GetUserIdentity.java
public class GetUserIdentity extends HttpServlet
{ 
 String str;
 String errorfile;
 ServletContext context;
 PreReadError readfile;
 
  public void init() throws ServletException 
 {
  context=getServletContext();
  if(context.getAttribute("errorfile")==null)
  {
   readfile=new PreReadError();
   context.setAttribute("errorfile",readfile);
  }
 }
 public void doPost(HttpServletRequest request,HttpServletResponse response) 
     throws ServletException,IOException
 {
  str=(String)(((PreReadError)context.getAttribute("errorfile")).getTable("Error1"));
  System.out.println(str);
 }
}


But I found a puzzle thing,when error.txt is follows:
       Error1:Not found
       Error2:Redirect
       Error3:Bye
I can get:
      Not found
Then I change the error.txt,it is follows:   

       Error1:Bad
       Error2:Redirect
       Error3:Bye
Then I click fresh option in IE tool column,then I can get:
     Not found

This is my wanted.Ok.
But After I click fresh option in IE tool column for serveral times,I found I got:
    Bad

"errorfile" has been put into the Context of Servlet.Why I will get the message which has been modified? How to correct it?
Thanks!
Edward













   

  Return to Index