论坛首页 入门技术论坛

config对象的一个例子出错

浏览 1605 次
该帖已经被评为新手帖
作者 正文
   发表时间:2007-05-09  

   在《JSP应用开发详解》中,讲解config对象时给出了一个计数器的例子,在实现的过程中希望计数器从1000开始计数。书中给出的代码是这样的:

xml 代码
  1. <%@ page contentType="text/html; charset=GBK" %>  
  2. <html>  
  3.   <head>  
  4.     <title>  
  5.       config   
  6.     </title>  
  7.   </head>  
  8.   <body bgcolor="#ffffff">  
  9.     <h1>  
  10.       Test config   
  11.     </h1>  
  12.     <%   
  13.     int org=0;   
  14.     int count=0;   
  15.     try{   
  16.       org=Integer.parseInt(config.getInitParameter("counter"));   
  17.     }catch(Exception e)   
  18.     {   
  19.       out.println("org:"+e);   
  20.     }   
  21.    try{     
  22.     count=Integer.parseInt((application.getAttribute("config_counter").toString()));   
  23.    }   
  24.     catch(Exception e)   
  25.     {   
  26.       out.println("count:"+e);   
  27.     }   
  28.          
  29.       if(count<org)   
  30.       {   
  31.         count=org;   
  32.       }   
  33.       out.println("此页面已经访问了"+count+"次");   
  34.       count++;   
  35.       application.setAttribute("config_counter",new Integer(count));   
  36.        
  37.       
  38.     %>  
  39.   </body>  
  40. </html>  

运行的结果倒也正常,没有抛出任何异常。不过我在敲这个例子的时候偷了点懒,写成了这个样子:

xml 代码

  1. <%@ page contentType="text/html; charset=GBK" errorPage=""%>  
  2. <html>  
  3.   <head>  
  4.     <title>  
  5.       config   
  6.     </title>  
  7.   </head>  
  8.   <body bgcolor="#ffffff">  
  9.     <h1>  
  10.       Test config   
  11.     </h1>  
  12.     <%   
  13.     int org=0;   
  14.     int count=0;   
  15.     try{   
  16.       org=Integer.parseInt(config.getInitParameter("counter"));   
  17.       count=Integer.parseInt((application.getAttribute("config_counter").toString()));   
  18.       if(count<org)   
  19.       {   
  20.         count=org;   
  21.       }   
  22.       out.println("此页面已经访问了"+count+"次");   
  23.       count++;   
  24.       application.setAttribute("config_counter",new Integer(count));   
  25.     }catch(Exception e)   
  26.     {   
  27.       out.println("org:"+e);   
  28.     }   
  29.     %>  
  30.   </body>  
  31. </html>  

把异常处理放在一起了 ,结果程序运行起来就出错了,报的异常是:org:java.lang.NullPointerException 。

不明白的就是这两种写法为什么不一样呢?如果第一次通过application.getAttribute()读取变量会出错的话,为什么第一种写法就没有打印出任何异常呢?请教了,谢谢。

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics