JWorld@TW the best professional Java site in Taiwan
      註冊 | 登入 | 全文檢索 | 排行榜  

» JWorld@TW » Java 新手區  

按列印兼容模式列印這個話題 列印話題    把這個話題寄給朋友 寄給朋友    訂閱主題
reply to topicthreaded modego to previous topicgo to next topic
本主題所含的標籤
無標籤
作者 java.lang.NullPointerException(已爬過文)
supper03





發文: 59
積分: 0
於 2011-11-24 21:46 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
各位大大
請教一個問題,一直找不出錯誤的原因在哪
環境 windows xp
IDE Intellij IDEA
application server:weblogic
從jsp的頁面傳入下拉式選選出的結果

上圖的部分程式碼(傳入的參數)

傳進modifySrc.java中要去sql撈資料出來(紅色部分),確定sql的寫法是有資料的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package tw.com.vibo.www.tag;
import java.io.IOException;
import java.sql.*;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import tw.com.vibo.www.singleton.connectionDB;
public class modifySrc extends BodyTagSupport {
  protected int pageRow;
    HttpServletRequest request;
    public modifySrc(){
        super();
    }
    public void setPageContext(PageContext pageContext)
  {
    this.pageContext = pageContext;
        request =(HttpServletRequest) pageContext.getRequest();
  }
  public int doAfterBody(){
        Hashtable rsHashtable;
 
        int countRec=0;
        //執行查詢
        try{
        //System.out.print("  test prepare to run getResult( );  ");
        Vector vector = this.getResult();
        //System.out.print("  test getResult( ) over, return ini_vector to doAfterBody( );...");
        JspWriter out = this.getPreviousOut();
 
        Iterator iterator = vector.iterator();
                if (vector.isEmpty()) out.print("<tr >\r\nNo Data Found !!\r\n</tr>");
                System.out.print("  test prepare to run while(iterator.hasNext( ))...  ");
 
                while (iterator.hasNext()){
 
                        rsHashtable = (Hashtable) iterator.next();
 
                        System.out.print("  test rsHashtable create...  ");
                       //計數record數並換色
                        countRec++;
 
                        if(countRec%2 == 0) out.print("<tr>\r\n");
 
                        else out.print("<tr bgcolor=\"#D1DAE9\">\r\n");
            out.print("<td width=\"73\"  height=\"20\"><div align=\"center\">"+countRec+"</div></td>\r\n");
                        out.print("<td width=\"111\"  height=\"20\"><div align=\"center\">"+rsHashtable.get("channel_type")+"</div></td>\r\n");
                        out.print("<td width=\"128\"  height=\"20\"><div align=\"center\">"+rsHashtable.get("src_id")+"</div></td>\r\n");
                        out.print("<td width=\"92\"  height=\"20\"><div align=\"center\">"+rsHashtable.get("src_desc")+"</div></td>\r\n");
                        out.print("<td width=\"109\"  height=\"20\"><div align=\"center\">"+rsHashtable.get("channel_desc")+"</div></td>\r\n");
                        out.print("<td width=\"109\"  height=\"20\"><div align=\"center\">"+rsHashtable.get("eng_name")+"</div></td>\r\n");
 
                        out.print("<td width=\"93\"  height=\"20\" valign=\"middle\"><div align=\"center\"><form name=\"form"+countRec+"\" method=\"post\" id=\"form"+countRec+"\" action=\"modifySrcResult.jsp\"> " +
                        " <input name=\"channel_type\" type=\"hidden\" id=\"channel_type["+countRec+"]\" value=\""+rsHashtable.get("channel_type")+"\"> " +
                        " <input name=\"src_id\" type=\"hidden\" id=\"src_id["+countRec+"]\" value=\""+rsHashtable.get("src_id")+"\"> " +
                        " <input name=\"src_desc\" type=\"hidden\" id=\"src_desc["+countRec+"]\" value=\""+rsHashtable.get("src_desc")+"\"> " +
                        " <input name=\"channel_desc\" type=\"hidden\" id=\"channel_desc["+countRec+"]\" value=\""+rsHashtable.get("channel_desc")+"\"> " +
                        " <input name=\"eng_name\" type=\"hidden\" id=\"eng_name["+countRec+"]\" value=\""+rsHashtable.get("eng_name")+"\"> " +
                        " <input name=\"submit1\" type=\"submit\" id=\"submit["+countRec+"]\" value=\" 修改 \" onClick=\"check('"+countRec+"');\" > "+
                        " </form></div></td> " );
            out.print("</tr>\r\n");
                }
              System.out.print("  test while( ) loop exit, countRec:  "+countRec+"  ");
             /* resp.sendRedirect(resp.encodeURL("import/modifyAccount.jsp?channel="+request.getParameter("channel")+
                        "&src_id="+request.getParameter("src_id")+"&bank_date="+request.getParameter("bank_date")));*/
        }catch (SQLException e) {
                System.out.print("  test SQL exception in doAfterBody();...   ");
          e.printStackTrace();
        }catch (IOException e) {
                System.out.print("  test IO exception in doAfterBody();...   ");
        e.printStackTrace();
      }
        return SKIP_BODY;
  }
     protected Vector getResult() throws SQLException
  {
       Vector ini_vector = new Vector();
    //Connect to DB
    Connection conn;
    PreparedStatement ps = null; //執行db sql command
    ResultSet rs;
        conn = connectionDB.getInstance().getConnection();
        //此為狀況查詢條件
        try {
                String queryString;               
          queryString = " select st.channel_type,st.src_id,st.src_desc,st.channel_desc,st.eng_name "+
                       " from src_tab st  " +
                     " where 1=1 " +
                                       ((request.getParameter("Channel").length()!=0) ? " and st.channel_type = "+request.getParameter("Channel") : "" ) +
                                        "order by st.src_id ";
             //執行SQL指令,Result Set放置 rs
       ps = conn.prepareStatement(queryString);
       rs = ps.executeQuery();
        if (rs != null)
        {
          while (rs.next())
          {
                    Hashtable ht = new Hashtable();
                    ht.put("channel_type", rs.getObject("channel_type"));
                    ht.put("src_id", rs.getObject("src_id"));
                    ht.put("src_desc", rs.getObject("src_desc"));
                    ht.put("channel_desc", rs.getObject("channel_desc"));
                    ht.put("eng_name", rs.getObject("eng_name"));
                    ini_vector.add(ht);
           }
        }
            if (ps != null) ps.close();    
}
        catch (SQLException e) {
            System.out.print("  test SQL exception in getResult( );  ");
      e.printStackTrace();
    }
    finally{
            try{
                  if (ps != null)  ps.close();
                  if (conn != null)  conn.close();
             }
             catch (Exception ex) {
                     System.out.print("  test exception in getResult( ) \"finally\"...  ");
                     ex.printStackTrace();
                }
      }
  return ini_vector;
  }
    public int getPageRow() {
    return pageRow;
  }
    public void setPageRow(int i) {
    pageRow = i;
  }
}

但執行結果卻跑出null pointer,請問是寫法出錯了嗎?煩請指導一下!!


reply to postreply to post
作者 Re:java.lang.NullPointerException(已爬過文) [Re:supper03]
jimwayne





發文: 220
積分: 0
於 2011-11-24 22:47 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
看錯誤訊息顯示錯誤是出在 getResult() 裡面的 Hashtable.put()
所以大概會落在這一段吧:
1
2
3
4
5
6
Hashtable ht = new Hashtable();
ht.put("channel_type", rs.getObject("channel_type"));
ht.put("src_id", rs.getObject("src_id"));
ht.put("src_desc", rs.getObject("src_desc"));
ht.put("channel_desc", rs.getObject("channel_desc"));
ht.put("eng_name", rs.getObject("eng_name"));

不過從 code 裡面就看不出這一段哪裡會出錯了
建議您先試試把每一個 rs.getObject() 全都印出來,應該就會發現其中哪一個是 null 了。


reply to postreply to post
Java 工作者,但仍然是個初心者.....
作者 Re:java.lang.NullPointerException(已爬過文) [Re:jimwayne]
supper03





發文: 59
積分: 0
於 2011-11-24 23:07 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
謝謝您的說明,我資料庫某幾個欄位值可以是空值,會不會就是被這影響呢?

reply to postreply to post
作者 Re:java.lang.NullPointerException(已爬過文) [Re:supper03]
jimwayne





發文: 220
積分: 0
於 2011-11-24 23:23 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
http://docs.oracle.com/javase/6/docs/api/java/util/Hashtable.html#put(K, V)

根據官方文件顯示,Hashtable 的 key 跟 value 都不允許空值,所以這樣是會有問題沒錯~
您可以用一些替代的方式來存放,例如資料庫為空值時填個 -1 之類的,正常不該出現的值
之後存取時只要從 Hashtable 裡取出來是 -1 就可以知道是表示資料庫內沒有值。


reply to postreply to post
Java 工作者,但仍然是個初心者.....
作者 Re:java.lang.NullPointerException(已爬過文) [Re:jimwayne]
supper03





發文: 59
積分: 0
於 2011-11-24 23:51 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
謝謝您的說明 我了解了 感謝您的用心!!!

reply to postreply to post
作者 Re:java.lang.NullPointerException(已爬過文) [Re:supper03]
anlick





發文: 2
積分: 0
於 2011-11-25 21:18 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
題外話

你的sql語法不要直接在string裡組條件,
PreparedStatement ps已經接到connection回傳的物件,
請用setString這類的method去帶參數,
即便程式執行起來不會有問題,但會有sql injection的問題。

還有jsp上別直接使用<%= %>,會有xss問題,
有jstl就用c:out,不過在jsp的javascript部份這樣用也會有點問題,<,>,',",&這五個字元encode後,你用alert秀就知道了

比較好的解決方式是用Apache common-lang裡的StringEscapeUtils去encode


reply to postreply to post
作者 Re:java.lang.NullPointerException(已爬過文) [Re:supper03]
pclevin





發文: 322
積分: 0
於 2011-11-25 23:02 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
1
((request.getParameter("Channel").length()!=0) ? " and st.channel_type = "+request.getParameter("Channel") : "" ) 

你這句code,只能用在request.getParameter("Channel")不是null時,才可以用。
如果request.getParameter("Channel")是null會發生NullPointerException

你需加入不等於null的判斷
1
((null != request.getParameter("Channel") && request.getParameter("Channel").length()!=0) ? " and st.channel_type = "+request.getParameter("Channel") : "" )


reply to postreply to post
我的網誌
http://pclevin.blogspot.com
作者 Re:java.lang.NullPointerException(已爬過文) [Re:anlick]
supper03





發文: 59
積分: 0
於 2011-11-26 09:02 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
jstl我還不太熟 既然有這方式我會去研究看看如何改善!!但您說setstring的方式來帶參數 可以舉個簡單的例子嗎 我看網路上
例子1
1
2
3
4
PreparedStatement pst = null;
pst = con.prepareStatement("insert into test(t1,t2)values('"+str1+"','"+str2+"')");
pst.setString(1,str1);
pst.setString(2,str2);

那我是改成這樣?
1
2
3
4
5
6
7
8
9
PreparedStatement ps = null;
Str1 = request.getParameter("Channel").toString();
String queryString = "select st.channel_type,st.src_id,st.src_desc,st.channel_desc,st.eng_name "+
                       " from src_tab st  " +
                     " where 1=1 " +
                     "     and st.channel_type ='"+str1+"' "+
                                        "order by st.src_id ";
ps = conn.prepareStatement(queryString);
ps.setString(1,str1);

大概是這樣嗎?? 我這沒辦法執行,想確認一下做法而已~~


reply to postreply to post
作者 Re:java.lang.NullPointerException(已爬過文) [Re:pclevin]
supper03





發文: 59
積分: 0
於 2011-11-26 09:02 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
謝謝 我有將加入null判斷加在hashtable那裡,謝謝您寶貴的意見

reply to postreply to post
作者 Re:java.lang.NullPointerException(已爬過文) [Re:supper03]
anlick





發文: 2
積分: 0
於 2011-11-26 09:12 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
1
2
3
4
5
String queryString = "select st.channel_type,st.src_id,st.src_desc,st.channel_desc,st.eng_name "+
                       " from src_tab st  " +
                     " where 1=1 " +
                     "     and st.channel_type =? "+
                                        "order by st.src_id ";


像這樣 Smile


reply to postreply to post
» JWorld@TW »  Java 新手區

reply to topicthreaded modego to previous topicgo to next topic
  已讀文章
  新的文章
  被刪除的文章
Jump to the top of page

JWorld@TW 本站商標資訊

Powered by Powerful JuteForum® Version Jute 1.5.8