日期:2014-05-18  浏览次数:20761 次

帮忙看一下代码好么?
这是个抄来的计数器的代码:
public   class   CounterServlet   extends   HttpServlet
{
public   void   doGet(HttpServletRequest   req,HttpServletResponse   res)throws   IOException,ServletException
{
ServletContext   context=getServletContext();

Integer   count=(Integer)context.getAttribute( "count ");//问题!

if(count==null)
{
count=new   Integer(1);
}
else
{
count=count+1;
}

PrintWriter   out=res.getWriter();
out.println(count);
context.setAttribute( "count ",   count);
out.close();
}
}
-----------------------------------------
在 "问题 "的代码行里,直接context.getAttribute( "count ");这样可以的吗?context原来都没有count这个属性,怎么这里可以直接getAttribute它呢???
能再讲讲有关上下文的知识吗??我现在连个感性认识都没有啊...上下文到底是个什么东西来的啊?????????最好讲个例子吧..小弟在此谢过了!!!

------解决方案--------------------
直接context.getAttribute( "count ");
it does not work! you must prepare something first...

The ServletContext is a resource that has application-wide scope and is available to the entire web application.Parameters can be stored there that all servlets and pages within the application have access to .Additionally information about the server and the web container can be retrived from the ServletContext.

1) First,you can configure any number of initialization parameters in web.xml:
<web-app>
<context-param>
<param-name> aman </param-name>
<param-value> beexk </param-value>
</context-param>
</web-app>

2) Then ,you can access context-wide initialization parameters from Servlets like this:

ServletContext ctx=getServletContext();
out.println( "hello! ");
out.println(ctx.getInitParameter( "aman "));

3) If you want get context attributes,you must set the context attribute first anywhere you want...

ServletContext ctx=getServletContext();
ctx.setAttribute( "count ",new Integer(1));

4) getting context attribute ....
ServletContext ctx=getServletContext();
Integer count=(Integer)ctx.getAttribute( "count ");

......





------解决方案--------------------
在 "问题 "的代码行里,直接context.getAttribute( "count ");这样可以的吗?
答:当然可以,如果没有 "count "这个属性,那就会得到一个null。正如代码下面的判断。
所谓的上下文指运行于整个服务器周期的生命周期。
整个服务器周期相当于一个程序,而servletContext就相当于c语言中的全局作用域,任何时间段都可以get这个作用域里的对象。
比如
ServletContext context=getServletContext();
你在一个servlet中context.setAttribute( "key ", "hello ");
然后你在另一个servlet中写String str = (String)context.getAttribute( "key ");
这个时候str的值就为 "hello ";
You can try it.