Hello,
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();
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
if(context.getAttribute("errorfile")==null)
{
readfile=new PreReadError();
context.setAttribute("errorfile",readfile);
}
str=(String)(((PreReadError)context.getAttribute("errorfile")).getTable("Error1"));
System.out.println(str);
}
}
file "error.txt" likes:
Error1:Not found
Error2:Redirect
Error3:Bye
I run it,it show:
Not found
Then I modify "error.txt",likes:
Error1:Bad Request
Error2:Redirect
Error3:Bye
And I run it,it should show:
Not found
But it show:
Bad Request
I want to know why? The second time, context.getAttribute("errorfile") should not null,it should not execute statements:
readfile=new PreReadError();
context.setAttribute("errorfile",readfile);
I want to read data from error.txt once in the servlet,but it read data every time.How to correct it?
Any idea will be appreciated!
Thanks!!!
Edward