⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 cruiselist.java

📁 j2ee技术内幕源码包括了这本书的所有代码
💻 JAVA
字号:
package unleashed.ch4.cruise;

import javax.servlet.*;
import javax.servlet.http.*;
import unleashed.*;
import java.io.*;
import java.sql.*;
import java.util.*;

public class CruiseList extends HttpServlet
{
    private java.sql.Connection dbConn = null;
    private CustomerListBean custList = null;
    private CruiseListBean cruiseList = null;
    public void init(ServletConfig config) throws ServletException
    {
        super.init();
        // now we'll get the connection to the database.
        try
        {
            // ==== Make connection to database =======

            //load the driver class
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");       

            //Specify the ODBC data source
            String sourceURL = "jdbc:odbc:CruiseTicket";
                
            //get a connection to the database
            dbConn =DriverManager.getConnection(sourceURL);
            custList = buildCustomerList();
            cruiseList = buildCruiseList();
            }
            catch (Exception e)
            {
                throw new ServletException(
                    "Could not create database " +
                    "connection in init(): "+e);
            }
    }
    public void destroy()
    {
        try
        {
            if(dbConn!=null)
                dbConn.close();
        }
        catch(Exception e)
        {
            System.out.println(
                "error while closing down DB connection.");
        }
    }


    public String getServletInfo()
    {
        return "Cruise List booking controller servlet.";
    }

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

    public void doPost( HttpServletRequest request,
            HttpServletResponse response)
        throws ServletException, IOException
    {
        System.out.println(
            "CruiseList servlet got a request...");		
        ResponseMessage msg;
        String command = request.getParameter("command");
        HttpSession session = request.getSession();

        System.out.println("command is: "+command);
        if(command == null || command.equals(""))
        {
            try
            {
                //build up the CustomerList and CruiseLists from DB
            
                session.setAttribute("custList",custList);
                session.setAttribute("cruiseList",cruiseList);
            }
            catch(Exception e)
            {
                throw new ServletException(e);
            }
        
            response.sendRedirect("/ch4cruise/Cruises.jsp");
        }
        
        else if (command.equals("book"))
        {
            String custid = request.getParameter("custid");
            String cruiseid = request.getParameter("cruiseid");
            String tickets = request.getParameter("numbertickets");

            System.out.println("Got parameters");
            try
            {
                if(custid.equals("") || cruiseid.equals(""))
                {
                    System.out.println("Missing a parameter!");
                    throw new Exception("Missing parameter");
                }
                else
                {
                    int numtickets = Integer.parseInt(tickets);
                    if(numtickets<=0)
                        throw new NumberFormatException();
                    try
                    {
                        if(makeReservation(custid,
                                cruiseid,
                                numtickets))
                            msg=new ResponseMessage(0,
                                "Cruise successfully booked.");
                        else
                            msg=new ResponseMessage(2,
                                "Problem booking cruise.");
                    }
                    catch (InvalidCCException cce)
                    {
                        msg = new ResponseMessage(2, 
                            "That customer's credit card is"+
                            " invalid");
                    }
                }
                
            }
            catch(Exception e)
            {
                msg = new ResponseMessage(2,
                    "You must select a customer, "+ 
                    "a cruise and enter a valid number "+
                    "of tickets");
            }
            System.out.println(
                "Setting ResponseMessageBean for JSP use.");
            session.setAttribute("message",msg);
            System.out.println("Redirecting to JSP for output");
            response.sendRedirect("/ch4cruise/Results.jsp");

        } // if command
        
    } // doPost()


    private CruiseListBean buildCruiseList() throws Exception
    {
        CruiseBean aCruise = null;
        CruiseListBean cruiselist = new CruiseListBean();
        Statement statement = null;

        statement = dbConn.createStatement();

        String query = "SELECT CRUISEID, DESTINATION,PORT, "+
            "SAILING FROM CRUISES";
        ResultSet rs = statement.executeQuery(query);
        while(rs.next())
        {
            aCruise = new CruiseBean(
                rs.getInt(1),
                rs.getString(2),
                rs.getString(3),
                rs.getString(4));
            cruiselist.addCruise(aCruise);
            System.out.println("added :"+aCruise.toString());
        }
        statement.close();
        return cruiselist;
    } // buildCruiseList

    private CustomerListBean buildCustomerList() throws Exception
    {
        CustomerBean aCustomer = null;
        CustomerListBean customerlist = new CustomerListBean();
        Statement statement = null;

        statement = dbConn.createStatement();

        String query = "SELECT CUSTOMERID, LASTNAME, FIRSTNAME "+
            "FROM CRUISECUSTOMER";
        ResultSet rs = statement.executeQuery(query);
        while(rs.next())
        {
            aCustomer = new CustomerBean(
                rs.getInt(1),
                rs.getString(2),
                rs.getString(3)
                );
            customerlist.addCustomer(aCustomer);
            System.out.println("added :"+aCustomer.toString());
        }
        statement.close();
        return customerlist;
    } //buildCustomerList


    // for simplicity sake we'll do the processing here.
    // in a real application this work should be done in 
    // it's own class
    private boolean makeReservation(String custId, 
        String cruiseId, int tickets) throws InvalidCCException
    {
        System.out.println(
            "Attempting to make reservation for custid: "+custId);
        //first fetch the cc number of the customer
        Statement statement = null;
        String ccnum =null;
        boolean status = false;
        try
        {
            statement = dbConn.createStatement();

            String query = "SELECT CREDITCARDNUMBER "+ 
                "FROM CRUISECUSTOMER "+
                "WHERE (CUSTOMERID ="+custId+")";
            ResultSet rs = statement.executeQuery(query);
            while(rs.next())
            {
                ccnum = rs.getString(1);
            }
            statement.close();
            System.out.println(
                "Credit card number for customer: "+
                custId+" is: "+ccnum);
            if(!verifyCreditCard(ccnum))
                throw new InvalidCCException();


            //Ok, valid CC number. Get the cruise info next
            
            String destination = null;
            String port=null;
            String date=null;

            statement = dbConn.createStatement();
            
            query = "SELECT DESTINATION, PORT, SAILING "+
                "FROM CRUISES WHERE (CRUISEID="+cruiseId+")";
            rs = statement.executeQuery(query);
            while(rs.next())
            {
                destination = rs.getString(1);
                port = rs.getString(2);
                date = rs.getString(3);
            }
            statement.close();
            System.out.println("Got the cruise information. ");

            // find the max ticketID in the system, 
            // if it's null, set to 1
            statement = dbConn.createStatement();
            
            int ticketID=0;
            query = "SELECT MAX (TICKETID) FROM CRUISETICKET";
            rs = statement.executeQuery(query);
            while(rs.next())
            {
                ticketID = rs.getInt(1);
            }
            statement.close();
            ticketID++;

            System.out.println("Next ticket ID is: "+ticketID);

            System.out.println("Building reservation");
            // ok, now build the reservation in the ticket table
            
            statement=dbConn.createStatement();
            query = "INSERT INTO CRUISETICKET VALUES("+
                ticketID+","+custId+", 'Unleashed Cruise Line' , "+
                "'USS SeaBuscuit', '"+port+"','" +
                date+"',999.99,0,0,'CH4Servlet')";
            statement.executeUpdate(query);
            statement.close();
        }
        catch(SQLException sqle)
        {
            System.out.println("Had an SQL exception: "+sqle);
            status = false;
            return status;
        }
        status = true;
        return status;
    }
    private boolean verifyCreditCard(String ccnum)
    {
        int firstnum = Integer.parseInt(ccnum.substring(0,1));
        if(firstnum > 4)
            return false;
        else
            return true;
    }
	

	

} //class

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -