尝试从数据库中获取数据时出现java.lang.NullPointerException

时间:2012-04-29 06:33:37

标签: java database jsp jdbc nullpointerexception

我想列出以下jsp页面中存储在数据库中的标签:

<div id="site_content"> <%-- Put the tags under this tag --%>
        <%! 
            GetTagsFromDatabase gtfd = new GetTagsFromDatabase();
            String tags[] = gtfd.getTags();
        %>

        <% 
            for(int i = 0 ; i <= tags.length ; ) {
        %>
        <table>
            <tr>
                <td> <%= tags[i++] %>   </td>
                <td> <%= tags[i++] %> </td>
                <td> <%= tags[i++] %> </td>
                <td> <%= tags[i++] %> </td>
            </tr>
        </table>
                <% } %>            
    </div>

Follwoing是GetTagsFromDatabase档案:

package NonServletFiles;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import javax.naming.*;

public class GetTagsFromDatabase {

public GetTagsFromDatabase() {

}

public String[] getTags() {

    String tags[] = null;
    try {
        Context context = new InitialContext();

        DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/photog");

        Connection connection = ds.getConnection();
        String sqlQuery = "select NAMEOFTHETAG from tagcollection";
        PreparedStatement statement = connection.prepareStatement(sqlQuery);
        ResultSet set = statement.executeQuery();

        int i = 0;
        while(set.next()) {
            tags[i] = set.getString("NameOfTheTag"); // <<--- line 33
            System.out.println(tags[i]);
            i++;
        }
    }catch(Exception exc) {
        exc.printStackTrace();
    }

    return tags;
}  

}

但是当我运行jsp页面时,我得到以下例外:

SEVERE: java.lang.NullPointerException
at NonServletFiles.GetTagsFromDatabase.getTags(GetTagsFromDatabase.java:33)
at org.apache.jsp.ListTags_jsp.<init>(ListTags_jsp.java:13)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:203)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:386)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)

SEVERE:     at NonServletFiles.GetTagsFromDatabase.getTags(GetTagsFromDatabase.java:33)
SEVERE:     at org.apache.jsp.ListTags_jsp.<init>(ListTags_jsp.java:13)
SEVERE:     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
SEVERE:     at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
SEVERE:     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
SEVERE:     at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
SEVERE:     at java.lang.Class.newInstance0(Class.java:372)
........

我尝试了查找网址java:comp/env/jdbc/photogjdbc/photog。虽然表中有48个项目,但是我得到这些例外的原因是什么?

2 个答案:

答案 0 :(得分:4)

您的tags数组始终为null。你需要初始化它。更好的是使用可以存储可变长度标签的ArrayList。而不是

String tags[] = null;

这样做

ArrayList<String> tags = new ArrayList<String>();

以后:

tags.add(set.getString("NameOfTheTag"));

然后您需要从

更改方法签名
public String[] getTags() {

public ArrayList<String> getTags() {

或将ArrayList再次转换为数组。

如果你知道有多少标签条目,那么你可以改变这一行:

String tags[] = new String[numberOfTagElements];

修改

为了使用数组,你必须

  1. 宣布
  2. 初始化
  3. 在该数组中添加或设置元素。
  4. 示例:

    String[] tags;  //declaration
    tags = new String[10]; //initialize array: max 10 elements can be used.
    tags[0] = "hello";  //set element 1 of your array
    

    您错过了第2步。如果使用null初始化数组,则不会分配内存。你必须告诉编译器你需要多少内存。例如,如果你想使用10个元素,那么数组必须先保留这个元素才能使用它。

答案 1 :(得分:0)

我的陈述是通用的但它可以帮助你。

每当遇到Object时,为什么不检查null。

if(object==null){
//dosomething
}else{
//dosomethingelse()
}

我的意思是说将defensive programming合并到您的代码中,每次都可以帮助您。

照顾@juergen所说的。