java jsp显示来自数据库的数据

时间:2012-09-04 07:14:10

标签: java oracle jsp tomcat web.xml

您好我正在尝试在jsp页面中显示数据库的内容。我希望数据的连接和处理在java文件中,并且只有数据的显示将包含在jsp页面中。< / p>

我正在使用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) 

1 个答案:

答案 0 :(得分:1)

您必须从网络浏览器(客户端)doGethttp://localhost:8084/DBConn请求 servlet http://localhost:8084/webapp_context/DBConn服务方法。

创建POJO,

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

并更改您的servlet代码,

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子类指定包名。