这段代码有几个不懂的地方,请教下。
//创建session
HttpSession session = request.getSession();
Object count = session.getAttribute("COUNTER");
int counter = 0;
if (count == null) {
counter = 1;
//将第一次技术存入session
session.setAttribute("COUNTER",new Integer(1)); ===========这里为什么要用new Integer(1),直接用1可以吗?
}else{
counter = (Interger) count).intValue(); ===========不明白这里为什么要来个(Integer)count).int..
//计数加一
counter++;
//将技术存入session
session.setAttribute("COUNTER".new Integer(counter));
}
PrinterWriter out = response.getWriter();
//输出信息
out.println(counter);
out.flush(); ============
out.close(); ============这两个方法有什么用啊,记得以前jsp页面时不用 的。这里是写在Servlet里的
1.[code="java"]
session.setAttribute("COUNTER",new Integer(1)); ===========这里为什么要用new Integer(1),直接用1可以吗?
[/code]
不能直接用1,
[code="java"]setAttribute(String name, Object value) [/code]
这个方法中第二个参数Object,而1是基本类型所以不能用1.
2.[code="java"]counter = (Interger) count).intValue(); ===========不明白这里为什么要来个(Integer)count).int..
[/code]
这个我觉得应该有错..应该是这样(去掉count的右括号)
[code="java"]counter = (Interger) count.intValue(); ===========不明白这里为什么要来个(Integer)count).int..
[/code]
因为count是个Object,所以用(Interget)对其进行转型,然后调用Interger类的intValue()返回int类型,API如下:
[code="java"] int intValue()
以 int 类型返回该 Integer 的值。
[/code]
3.[code="java"]out.flush(); ============
out.close(); ============这两个方法有什么用啊,记得以前jsp页面时不用 的。这里是写在Servlet里的 [/code]
在JDK API中:
[code="java"]
void flush()
刷新该流的缓冲。
void close()
关闭该流并释放与之关联的所有系统资源。
[/code]
其实close()一般都要写上,IO流占资源的,你操作完了关上才是正确的做法,跟操作数据库时关闭链接差不多.