oracle 在jsp-MVC中显示数据库中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12291866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 01:05:47  来源:igfitidea点击:

Display data from database in jsp - MVC

javaoraclemodel-view-controllerjsptomcat

提问by mysticfalls

I am trying to come up with a code that complies with the mvc architecture and display the content of a database in the jsp page.. The connection and processing of data to be in java files and only the display of the data will be included in the jsp page.
I am using tomcat server. I have ojdbc6.jar and jstl-1.2.jar on my WEB-INF/lib folder.

我试图想出一个符合mvc架构的代码,在jsp页面中显示一个数据库的内容。。数据的连接和处理要在java文件中,只有数据的显示才会包含在jsp 页面。
我正在使用tomcat服务器。我的 WEB-INF/lib 文件夹中有 ojdbc6.jar 和 jstl-1.2.jar。

(Update) After changing my web.xml to point to index I got java.lang.StackOverflowError error.

(更新)将我的 web.xml 更改为指向索引后,我收到了 java.lang.StackOverflowError 错误。

Is there something missing/wrong with the code? Also if I am not complying with the MVC design, let me know. Any idea would be appreciated. Thank you.

代码是否有遗漏/错误?另外,如果我不遵守 MVC 设计,请告诉我。任何想法将不胜感激。谢谢你。

Here is the code I am trying to run.

这是我试图运行的代码。

DBConn.java

数据库连接器

    public class DBConn extends HttpServlet{
      @Override
      public void doGet(HttpServletRequest request, 
                        HttpServletResponse response) 
                           throws IOException, ServletException {
        Connection connection = null;
        Statement stmt=null;
        ResultSet rs=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();
            rs = stmt.executeQuery("select employee_id, first_name from employees");
            while (rs.next()) {
                dataList.add(new Employee(rs.getInt("employee_id"),
                                          rs.getString("first_name")));
            }
        } catch (ClassNotFoundException e) {
            // Could not find the database driver
            e.printStackTrace();
        } catch (SQLException e) {
            // Could not connect to the database
            e.printStackTrace();
        } finally{
            if(rs!=null){
                try{ 
                  rs.close();
                }catch(Exception ex) { /* */ ex.printStackTrace();}
            }
            if(stmt!=null){
                try{ 
                  stmt.close();
                }catch(Exception ex) { /* */ ex.printStackTrace();}
            }
            if(connection !=null){
                try{ 
                  connection.close();
                }catch(Exception ex) { /* */ ex.printStackTrace();}
            }
         }

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

Employee.java

雇员.java

public class Employee {

    private Integer id;
    private String name;
    //public constructors and
    //setter/getter

    public Employee(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

index.jsp

索引.jsp

<%@ 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>Emp ID</b></td>
                <td width="168"><b>First Name</b></td>
            <tr
        <form action="post">
            <c:forEach var="employee" items="${data}">
                <br/> ${employee.id}  ${employee.name}
            </c:forEach>
        </form>
        </tr>    
    </table>
</body>
</html>

web.xml

网页.xml

<servlet>
    <servlet-name>DBConn</servlet-name>
    <servlet-class>DB.DBConn</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>DBConn</servlet-name>
    <url-pattern>/index</url-pattern>
</servlet-mapping>

Error

错误

    09 6, 12 10:09:00 AM org.apache.catalina.core.ApplicationDispatcher invoke
    SEVERE: Servlet.service() for servlet DBConn threw exception
    java.lang.StackOverflowError
        at java.util.HashMap$KeySet.<init>(HashMap.java:872)
        at java.util.HashMap$KeySet.<init>(HashMap.java:872)
        at java.util.HashMap.keySet(HashMap.java:869)
        at java.util.HashSet.iterator(HashSet.java:153)
        at java.util.Collections.<init>(Collections.java:3382)
        at java.util.Collections.enumeration(Collections.java:3381)
        at org.apache.catalina.connector.Request.getAttributeNames(Request.java:1027)
        at org.apache.catalina.connector.RequestFacade.getAttributeNames(RequestFacade.java:300)
        at org.apache.catalina.core.ApplicationHttpRequest$AttributeNamesEnumerator.<init>(ApplicationHttpRequest.java:927)
        at org.apache.catalina.core.ApplicationHttpRequest.getAttributeNames(ApplicationHttpRequest.java:243)
        at org.apache.catalina.core.ApplicationHttpRequest$AttributeNamesEnumerator.<init>(ApplicationHttpRequest.java:927)
        at org.apache.catalina.core.ApplicationHttpRequest.getAttributeNames(ApplicationHttpRequest.java:243)

回答by Arun Manivannan

While you are configuring your servlet and the servlet-mappings, you might want to configure the url-pattern that you mentioned in the servlet-mapping in your jsp too.

当您配置 servlet 和 servlet-mappings 时,您可能还想配置您在 jsp 中的 servlet-mapping 中提到的 url-pattern。

JSP

JSP

<form action="post" action="/dbconn">
...

</form>

web.xml

网页.xml

<servlet>
<servlet-name>dbconn</servlet-name>
<servlet-class>com.xx.xx.DBConn</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dbconn</servlet-name>
<url-pattern>/dbconn</url-pattern>
</servlet-mapping>

Also, you might want to consider using a Data Access Object pattern. (Ignore if you are just trying to understand servlets)

此外,您可能需要考虑使用数据访问对象模式。(如果您只是想了解 servlet,请忽略)

回答by Vishvesh Phadnis

use dispatcher.include(request, response)method.

使用 dispatcher.include(request, response)方法。