【问题标题】:Getting information from database through servlet通过servlet从数据库中获取信息
【发布时间】:2014-06-14 17:57:30
【问题描述】:

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

下面是索引页和servlet。

索引

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

伺服器

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;
   }

}

【问题讨论】:

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


    【解决方案1】:

    你需要:

    • 访问 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&lt;edu.witc.Assignment05.model.Customer&gt; customers 字段(以及任何非 final static 字段或任何非托管资源)。

    【讨论】:

    • 也许这会有所帮助。我添加了连接数据库并调用存储过程的客户类和客户dao
    • 我是新手,Java 对我来说有点难以掌握。无法弄清楚我哪里出错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 2017-01-02
    相关资源
    最近更新 更多