简体   繁体   中英

Display data from database in jsp - MVC

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.

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

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.

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

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

<%@ 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

<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$1.<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)

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.

JSP

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

</form>

web.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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM