简体   繁体   English

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

[英]java.lang.NullPointerException while trying to fetch data from database

I wanted to list the tags stored in the database in the following jsp page : 我想列出以下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 is GetTagsFromDatabase file : 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;
}  

} }

But when i run the jsp page i get the following exceptions : 但是当我运行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)
........

I tried both the lookup urls java:comp/env/jdbc/photog and jdbc/photog . 我尝试了两个查找网址java:comp/env/jdbc/photogjdbc/photog Though there are 48 items in the table,what could be the reason i get these exceptions ? 虽然表中有48个项目,但是我得到这些例外的原因是什么?

Your tags array is always null . 您的tags数组始终为null You need to initialize it. 你需要初始化它。 Better is using an ArrayList that can store a variable length of tags. 更好的是使用可以存储可变长度标签的ArrayList Instead of 代替

String tags[] = null;

do this 做这个

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

and later: 然后:

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

Then you need either to change your method signature from 然后,您需要更改方法签名

public String[] getTags() {

to

public ArrayList<String> getTags() {

or convert your ArrayList to an array again. 或者将ArrayList再次转换为数组。

If you know how many tag entries you have then you can just change that line: 如果您知道有多少标记条目,那么您可以更改该行:

String tags[] = new String[numberOfTagElements];

EDIT 编辑

In order to use an array you have to 为了使用你必须的阵列

  1. declare it 宣布它
  2. initialize it 初始化它
  3. add or set elements in that array. 在该数组中添加或设置元素。

Example: 例:

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

You missed step 2. No memory will be allocated if you init your array with null. 您错过了第2步。如果使用null初始化数组,则不会分配任何内存。 You have to tell the compiler how much memory you need. 你必须告诉编译器你需要多少内存。 If you want to use 10 elements for instance the array has to reserve that fist before you can use it. 例如,如果你想使用10个元素,那么在你可以使用它之前,数组必须保留这个元素。

My statement is generic but It helps you. 我的陈述是通用的,但它可以帮助你。

Whenever you encounter an Object,Why don't you check for null. 每当遇到Object时,为什么不检查null。

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

I mean to say incorporate defensive programming into your code that helps you everytime. 我的意思是说在你的代码中加入防御性编程 ,每次都能帮到你。

take care of what @juergen d told. 照顾@juergen所说的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试通过ID获取实体时出现java.lang.NullPointerException - java.lang.NullPointerException while trying to fetch entity by id 尝试查找Webelement时,Webdriver selenium,java.lang.NullPointerException - Webdriver selenium,java.lang.NullPointerException,while trying to locate a Webelement 尝试在Android中将数据添加到类的对象时出现java.lang.NullPointerException - java.lang.NullPointerException while trying to add data to object of class in Android Firebase数据库中已经存在的数据的java.lang.NullPointerException,我正在尝试检索它 - java.lang.NullPointerException for a data that already exists in Firebase database and I am trying to retrieve it 执行多线程数据库应用程序时出现java.lang.NullPointerException - java.lang.NullPointerException while executing multithreaded database application 从数据库中获取值时线程主java.lang.NullPointerException中的异常 - Exception in thread main java.lang.NullPointerException while fetching value from database java.lang.NullPointerException尝试从哈希图中获取特定值 - java.lang.NullPointerException trying to get specific values from hashmap 来自SQLite类的java.lang.NullPointerException而在android中访问数据库 - java.lang.NullPointerException from SQLite class while accessing database in android 从数组访问方法时发生java.lang.NullPointerException错误 - java.lang.NullPointerException error while accessing method from array 从控制器调用时java.lang.NullPointerException - java.lang.NullPointerException while calling from controller
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM