0

こんにちは私はデータベースのコンテンツをjspページに表示しようとしています。データの接続と処理をJavaファイルに入れたいのですが、データの表示のみがjspページに含まれます。

私はTomcatサーバーを使用しています。WEB-INF/libフォルダーにojdbc6.jarとjstl-1.2.jarがあります。

私が欠けているものを親切にアドバイスしてください。任意のアイデアをいただければ幸いです。ありがとうございました。

これがjavaファイルの内容です。

DBConn.java

public class DBConn extends HttpServlet {

    public void getData(HttpServletRequest request,
                        HttpServletResponse response) throws IOException,
                                                             ServletException {
        Connection connection = null;
        List dataList = new ArrayList();
        try {
            // Load the JDBC driver
            String driverName = "oracle.jdbc.driver.OracleDriver";
            Class.forName(driverName);

            // Create a connection to the database
            String serverName = "localhost";
            String portNumber = "1521";
            String sid = "xe";
            String url =
                "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" +
                sid;
            String username = "hr";
            String password = "hr";
            connection = DriverManager.getConnection(url, username, password);

            Statement stmt = connection.createStatement();
            ResultSet rset = stmt.executeQuery("select * from employees");
            while (rset.next()) {
                dataList.add(rset.getInt("employee_id"));
                dataList.add(rset.getString("first_name"));
            }
            stmt.close();

        } catch (ClassNotFoundException e) {
            // Could not find the database driver
        } catch (SQLException e) {
            // Could not connect to the database
        }

        request.setAttribute("data", dataList);
        String strViewPage = "index.jsp";
        RequestDispatcher dispatcher =
            request.getRequestDispatcher(strViewPage);
        if (dispatcher != null) {
            dispatcher.forward(request, response);
        }

    }
}

jspファイルの内容は次のとおりです。

index.jsp

<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%@page language="java" import="java.util.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <h1>Hello World!</h1>
    <table border="1" width="303">
        <tr>
            <td width="119"><b>Employee ID</b></td>
            <td width="168"><b>First Name</b></td>
        </tr>
        <%Iterator itr;%>
        <% List data = (List) request.getAttribute("data");
            for (itr = data.iterator(); itr.hasNext();) {
        %>
        <tr>
            <td width="119"><%=itr.next()%></td>
            <td width="168"><%=itr.next()%></td>
        </tr>
        <%}%>
    </table>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app 
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">

<!-- Config here. No taglibs! -->
<!--
To change this template, choose Tools | Templates
and open the template in the editor.
-->

<!--web.xml code -->
<servlet>
<servlet-name>DBConn</servlet-name> 
<servlet-class>DBConn</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>DBConn</servlet-name>
<url-pattern>/DBConn</url-pattern>
</servlet-mapping>
</web-app>

出力:

org.apache.jasper.JasperException: An exception occurred processing JSP page /index.jsp at line 26


23:             </tr>
24:             <%Iterator itr;%>
25:             <% List data = (List) request.getAttribute("data");
26:                 for (itr = data.iterator(); itr.hasNext();) {
27:             %>
28:             <tr>
29:                 <td width="119"><%=itr.next()%></td>


Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:568)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:470)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
 root cause

  java.lang.NullPointerException
org.apache.jsp.index_jsp._jspService(index_jsp.java:88)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393) 
4

1 に答える 1

1

Web ブラウザー (クライアント) からサーブレットdoGetのサービス メソッドを要求する必要があります -または.http://localhost:8084/DBConnhttp://localhost:8084/webapp_context/DBConn

POJOを作成し、

public class Employee{
   private Integer id;
   private String  name;
   //public constructors and
   //setter/getter
}

サーブレットコードを変更し、

public class DBConn extends HttpServlet{
  @Override
  public void doGet(HttpServletRequest request, 
                    HttpServletResponse response) 
                       throws IOException, ServletException {
    Connection connection = null;
    Statement stmt=null;
    ResultSet rset=null;
    List<Employee> dataList = new ArrayList<Employee>();
    try {
        // Load the JDBC driver
        String driverName = "oracle.jdbc.driver.OracleDriver";
        Class.forName(driverName);

        // Create a connection to the database
        String serverName = "localhost";
        String portNumber = "1521";
        String sid = "xe";
        String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
        String username = "hr";
        String password = "hr";
        connection = DriverManager.getConnection(url, username, password);

        stmt = connection.createStatement();
        rset = stmt.executeQuery("select * from employees");
        while (rset.next()) {
            dataList.add(new Employee(rset.getInt("employee_id"),
                                      rset.getString("first_name"));
        }
    } catch (ClassNotFoundException e) {
        // Could not find the database driver
    } catch (SQLException e) {
        // Could not connect to the database
    } finally{
        if(rs!=null){
            try{ 
              rs.close();
            }catch(Exception ex) { /* */ }
        }
        if(stmt!=null){
            try{ 
              stmt.close();
            }catch(Exception ex) { /* */ }
        }
        if(connection !=null){
            try{ 
              connection.close();
            }catch(Exception ex) { /* */ }
        }
     }

     request.setAttribute("data", dataList);
     String strViewPage = "index.jsp";
     RequestDispatcher dispatcher = request.getRequestDispatcher(strViewPage);
      if (dispatcher != null) {
         dispatcher.forward(request, response);
      }
   }
}

のマークアップindex.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:forEach var="employee" items="${data}">
  <br/> ${employee.id}  ${employee.name}
</c:forEach>

注:デフォルトのパッケージにタイプ (クラス)を作成しないでください。POJO および Servlet サブクラスのパッケージ名を指定する必要があります。

于 2012-09-04T07:37:03.100 に答える