java jsp显示数据库中的数据

标签 java oracle jsp tomcat web.xml

<分区>

您好,我正在尝试在 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文件的内容。

索引.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) 

最佳答案

您必须从网络浏览器(客户端)请求 doGet servlet 服务方法 - http://localhost:8084/DBConnhttp://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 子类的包名称。

关于java jsp显示数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12258478/

相关文章:

java - 计算范围内的素数 RMI 版本与并发版本

java - 将自定义弹出窗口/ View 添加到 android 中的 Activity

java - org.springframework.ui.velocity.VelocityEngineFactoryBean 发生了什么?

oracle - 有谁有示例数据迁移脚本(Oracle 10g 到 Oracle 10g,但架构不同)?

在 WAN 上具有许多绑定(bind)变量的 oracle 插入非常慢

java - 使用标准在 hibernate 中对 varchar 类型的列应用数字和排序依据?

oracle - 如何等到查询返回行?

java - 找不到springframework的标签库描述符

javascript - 在 Jquery 中操作 java List<Object>

google-app-engine - App Engine 无缓存 JSP