通过servlet从数据库获取信息

时间:2014-02-10 09:13:55

标签: java eclipse jsp servlets derby

我正在尝试从servlet获取一些信息。这是我的jsp页面的代码。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    import="java.util.*, DB.DBServlet"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet">
<title>Lab4</title>
</head>
<body>
<div id='chekboxOfCompanies'>
 <%Iterator itr;%>
 <% List data= (List)request.getAttribute("country");
                for (itr=data.iterator(); itr.hasNext(); ) {
                    out.println("<input type='checkbox'>");
           }%>
</div>
<div id=''></div>
</body>
</html>

这是负责获取信息的servlet代码。

public class DBServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public String page = "main.jsp";   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DBServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        String protocol = "jdbc:derby:";
        Connection conn = null;
        ArrayList<Statement> statements = new ArrayList<Statement>(); 
        Statement s = null;
        ResultSet rs = null;
        String dbName = "Lab4DB";
        ArrayList<String> dataList = new ArrayList<String>();
        try {
            conn = DriverManager.getConnection(protocol + dbName);
            System.out.println("Connected to database " + dbName);
            conn.setAutoCommit(false);
            s = conn.createStatement();
            statements.add(s);
            s.executeQuery("SELECT company from companies");
            rs = s.getResultSet();
            while(rs.next()){
                dataList.add(rs.getString("country"));
            }
            rs.close();
            s.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        request.setAttribute("country", dataList);
        RequestDispatcher dispatcher = request.getRequestDispatcher(page);

        if (dispatcher != null) {

            dispatcher.forward(request, response);

        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

当我尝试运行此代码时,会出现一些Null指针异常。控制台的输出。

SEVERE: Servlet.service() for servlet [jsp] in context with path [/Lab4DWP] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at org.apache.jsp.main_jsp._jspService(main_jsp.java:80)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)
10.02.2014 15:11:12 org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Lab4DWP] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at org.apache.jsp.main_jsp._jspService(main_jsp.java:80)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:695)

什么变量得到空值?我怎么能避免它?

1 个答案:

答案 0 :(得分:1)

首先尝试打印出控制台中的国家/地区列表,这是确定无疑的。顺便说一下,你缺少对迭代器的itr.next()调用,它为你提供了复选框的元素和结束标记。我认为这就是给你空指针的东西。

P:S:我相信你连接数据库的方式不应该有效。 getConnection(协议+&#34; //&#34; +主机地址+&#34; /&#34; + dbName)应该是正确的方式

根据评论:

首先,请尝试使用正确的代码连接数据库并检索信息 有关优秀教程,请访问:Vogella tutorial
其次,请尝试关闭所有打开的标签。甚至输入标签也会使用&#34; /&gt;&#34;关闭,如果不是完整的结束标签&#34;&lt; /输入&GT;&#34 ;.
第三,在tomcat中,您可以在工作目录下找到生成的jsp代码(可能会根据配置隐藏)。跳转到第80行,在生成的jsp(main_jsp.java)中找到哪一行正好引发了该错误。