通过servlet从数据库获取信息

时间:2014-04-29 01:03:27

标签: java jsp servlets model-view-controller jdbc

当我加载index.jsp时,我想将所有客户加载到页面上。出于某种原因,我无法让客户从数据库中显示出来。我假设我的servlet中的某个地方出错了。

下面是索引页面和servlet。

INDEX

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.util.ArrayList" %>
     <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
     <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Add a Customer/Pet</title>
</head>
<body>
<h1>List of Customers</h1>
    <form action="fetchDataServlet" method="get">
    <c:forEach items="${sessionScope.customers}" var="customer"  >
        <ul>
            <li>${customer.getFirstName()}</li>
        </ul>           
    </c:forEach>

</form>
</body>
</html>

SERVLET

package edu.witc.Assignment05.controller;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;




import javax.servlet.http.HttpSession;

import edu.witc.Assignment05.model.Customer;
import edu.witc.Assignment05.model.CustomerDAO;




@WebServlet(description = "servlet to get act as controller between form and models", urlPatterns = { "/fetchDataServlet","/addCustomer","/addPet", "/customerManagement" })
public class FetchDataServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public FetchDataServlet() {
        super();
    }

    private List<edu.witc.Assignment05.model.Customer> customers = new ArrayList<Customer>();


    private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to form
            throws IOException, ServletException {
            String url = "/customerManagement.jsp";
            //processRequest(request, response);
            Customer customer = new Customer();
            HttpSession session = request.getSession();
            session.setAttribute("customer", customer);
            request.getRequestDispatcher(url).forward(request,response);
     }

    private void addPet(HttpServletResponse response, HttpServletRequest request)//redirect to pet page
         throws IOException, ServletException {
         String url = "/pets.jsp";
         request.getRequestDispatcher(url).forward(request,response);
    }

    public void doGet(HttpServletRequest request, 
        HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = request.getSession();
    request.setAttribute("customers", customers);
    String url = "/index.jsp";
 request.getRequestDispatcher(url).forward(request,response);

}
    public void doPost(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {

        int customerId = 0;
        Customer customer = new Customer();

        if (customer != null) {
            customerId = customers.size()+1;
            customer.setCustomerId(customerId);
            customer.setFirstName(request.getParameter("firstName"));
            customer.setLastName(request.getParameter("lastName"));
            customer.setEmailAddress(request.getParameter("email"));
            customer.setPhoneNumber(request.getParameter("phone"));
            customers.add(customer);



        }

    }
}

客户类

package edu.witc.Assignment05.model;

public class Customer {

    int customerId = 0;
    String firstName = ""; 
    String lastName = "";
    boolean customerIsActive = true;
    int emailId = 0;
    String emailAddress = "";
    int emailUnitId = 0;
    int phoneId = 0;
    int phoneUnitId = 0;
    String phoneNumber = "";

    public Customer(){

    }


    public Customer(int customerId, String firstName, String lastName,
                    boolean customerIsActive, int emailId, String emailAddress,
                    int emailUnitId, int phoneId, int phoneUnitId, String phoneNumber){
        this.customerId = customerId;
        this.firstName = firstName;
        this.lastName = lastName;
        this.customerIsActive = customerIsActive;
        this.emailId = emailId;
        this.emailAddress = emailAddress;
        this.emailUnitId = emailUnitId;
        this.phoneId = phoneId;
        this.phoneUnitId = phoneUnitId;
        this.phoneNumber = phoneNumber;
    }

    public int getCustomerId() {
        return customerId;
    }

    public String getFirstName() {
        return firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public boolean getCustomerIsActive(){
        return customerIsActive;
    }
    public int getEmailId(){
        return emailId;
    }
    public String getEmailAddress(){
        return emailAddress;
    }
    public int getEmailUnitId(){
        return emailUnitId;
    }
    public int getPhoneId(){
        return phoneId;
    }
    public int getPhoneUnitId(){
        return phoneUnitId;
    }
    public String getPhoneNumber(){
        return phoneNumber;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public void setCustomerIsActive(boolean customerIsActive) {
        this.customerIsActive = customerIsActive;
    }

    public void setEmailId(int emailId) {
        this.emailId = emailId;
    }

    public void setEmailAddress(String emailAddress) {
        this.emailAddress = emailAddress;
    }

    public void setEmailUnitId(int emailUnitId) {
        this.emailUnitId = emailUnitId;
    }

    public void setPhoneId(int phoneId) {
        this.phoneId = phoneId;
    }

    public void setPhoneUnitId(int phoneUnitId) {
        this.phoneUnitId = phoneUnitId;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }


    public void setCustomerId(int customerId) {
        this.customerId = customerId;

    }

}

客户DAO

package edu.witc.Assignment05.model;


import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;


public class CustomerDAO<T> {

    static final String DATABASE_URL = 
            "jdbc:jtds:sqlserver://localhost/A1Kennel;instance=sqlexpress";


   private GenericClass<Customer>myCustomers = new GenericClass<>();

   public CustomerDAO() throws ClassNotFoundException
   {}

   public Collection<T> getData() throws ClassNotFoundException
   {   //Public method that can be called from the controller to get data
       Collection<T> customerList = null;
       customerList = fetchData();
       return customerList;
   }

   @SuppressWarnings("unchecked")
   private Collection<T> fetchData() throws ClassNotFoundException
   {   //With a little tweaking, this method could be used to return any
       //collection from the database
       //ResultSet rs = null;
       String myProc = "{Call FetchCustomer_All()}";
       Customer customer = null;

       Collection<T>allCustomers = new ArrayList<>();
       CallableStatement procCall = null;
       Connection conn = null;

       try 
       {
           Class.forName("net.sourceforge.jtds.jdbc.Driver");
           conn = DriverManager.getConnection(DATABASE_URL,"","");
           procCall = conn.prepareCall(myProc); 
           ResultSet rs = procCall.executeQuery();

           if(rs != null)
           {
               while(rs.next())
               {
                   //build an object
                   customer = new Customer(rs.getInt("customerId"), rs.getString("firstName"), rs.getString("lastName"),
                                           rs.getBoolean("customerIsActive"), rs.getInt("emailId"), rs.getString("emailAddress"), 
                                           rs.getInt("emailUnitId"), rs.getInt("phoneId"), rs.getInt("phoneUnitId"), rs.getString("phoneNumber"));
                   myCustomers.addItem(customer);
               }

               allCustomers = (Collection<T>) myCustomers.getCollection();
           }
       }
       catch(SQLException badSQL)
       {
           System.out.print(badSQL.getMessage());
       }
       finally{
           try
           {
               procCall.close();
               conn.close();
           }
           catch(Exception ex)
           {
               ex.getMessage();
           }
       }
       return allCustomers;
   }

}

1 个答案:

答案 0 :(得分:0)

你需要:

  • 访问servlet而不是URL中的JSP视图,这意味着您将使用GET请求。
  • 在servlet的doGet方法中:
    • 检索要显示给用户的所有所需数据。
    • 将此数据存储在请求属性中。
    • 转发到所需的视图(JSP)。

这是如何实施doGet方法的框架:

public void doGet(HttpServletRequest request, 
        HttpServletResponse response)
        throws ServletException, IOException {
    CustomerService customerService = new CustomerService();
    //assuming this method connects to database using a database connection pool
    //and retrieves the results through JDBC using ResultSet
    List<Customer> customers = customerService.findAllCustomers();
    //store the data in request attribute
    request.setAttribute("customers", customers);       
    //forward to the desired view:
    String url = "/customerManagement.jsp";
    request.getRequestDispatcher(url).forward(request,response);
}

除此之外,您应该知道 Servlet上没有任何状态。这将导致并发问题,如下所述:How do servlets work? Instantiation, sessions, shared variables and multithreading。这意味着,从Servlet(以及任何非List<edu.witc.Assignment05.model.Customer> customers字段或任何非托管资源)中删除final static字段。