将Servlet连接到jsp页面

时间:2014-10-23 23:16:46

标签: java jsp servlets

编辑:当显示帐户视图时,我无法让数据库从我正在进行的迷你银行帐户项目中提取acctNo,Cust Id,帐户类型和余额。我在那里添加了帐户业务对象以确保SQL连接到拉起,名称拉起但是acctNo,Cust Id,帐户类型和余额不会。它全部连接在一起,因此我将它们全部添加,所有页面都可以工作,但没有任何内容从数据库中弹出

如何连接此servlet:

   @WebServlet(urlPatterns = {"/AccountLookupServlet"})
    public class AccountLookupServlet extends HttpServlet {


        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            try (PrintWriter out = response.getWriter()) {
                /* TODO output your page here. You may use following sample code. */


                 String id = request.getParameter("id");
                String pw = request.getParameter("pw");
                System.out.println(id);
                System.out.println(pw);


                Account a1=new Account();
                a1.findDB(id);
                String an=a1.getAcctNo();
                System.out.println(an);

                String ln=a1.getCustId();
                System.out.println(ln);

                String at=a1.getType();
                System.out.println(at);


                  double bal=a1.getBalance();
                System.out.println(bal);


                HttpSession ses1=request.getSession();
                ses1.setAttribute("a1", a1);
            }
        }


        /**
         * Handles the HTTP <code>GET</code> method.
        */
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            doPost(request,response);

        }

        /**
         * Handles the HTTP <code>POST</code> method.
         */
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            String action = request.getParameter("action");

            if (action.equals(null)) {

                request.getRequestDispatcher("/index.jsp").forward(request, response);

            } 
            /* Gets single searched account from the accountLookup.jsp */
            else if (action.equals("getAcct")) {

                String acctNo = request.getParameter("accountNo");

                try {

                    /* Instantiates a new Account class and sets it as a request attribute
                    for use in the accountView.jsp */
                    Account account = new Account(acctNo);
                    request.setAttribute("account", account);
                    request.getRequestDispatcher("/accountView.jsp").forward(request, response);

                } catch (SQLException ex) {
                    Logger.getLogger(AccountLookupServlet.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        /**
         * Returns a short description of the servlet.
         *
         * @return a String containing servlet description
         */
        @Override
        public String getServletInfo() {
            return "Short description";
        }

    }

要连接到此jsp页面以提取出现在我创建的表格中的客户ID,帐号,帐户类型和余额? Servlet正在工作,数据库已连接,我只需要一种方法让JSP页面读入数据并实际打印出来。

<%@page import="Business.Account"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Your Account</title>
        <link rel="stylesheet" href="chattBank.css" type="text/css">
        <style>
                #image{
                    text-align: center;
                }
                #acctForm{
                    text-align: center;
                }
                #acctTable{
                    margin-left: 645px;
                }
                #submitTable{
                    margin-left: 755px;
                }
                table{
                    margin-left: auto;
                    margin-right: auto;
                }
                h4{
                    text-align: center;
                }
            </style>
    </head>
    <body>
        <div id = "image">
            <img src="bankpic.jpg" />
        </div>
        <h4>Here Is The Account You Requested</h4>
        <table border="1" width="75%" cellspacing="5" cellpadding="2">
            <thead>
                <tr>
                    <th colspan="10">Your Chatt Accounts</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td colspan="2"></td>
                    <td colspan="2">Customer Id</td>
                    <td colspan="2">Account Number</td>
                    <td colspan="2">Account Type</td>
                    <td colspan="2">Account Balance</td>
                </tr>
                <tr>
                    <td colspan="2">Account: </td>
                    <td colspan="2">${account.custId}</td>
                    <td colspan="2">${account.acctNo}</td>
                    <td colspan="2">${account.type}</td>
                    <td colspan="2">${account.balance}</td>

                </tr>
            </tbody>
        </table>
                <table width="50%" cellspacing="5" cellpadding="2">
            <thead>
                <tr>

                    <td></td>
                    <td>Click Here To Navigate To A New Page</td>
                    <td></td>

                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><a href="AccountServlet?action=view&id=${customer.custId}">View All Accounts</a></td>
                    <td><a href="ManageAccounts?action=manage&id=${customer.custId}">Manage Accounts</a></td>
                    <td><a href="Logout?action=logout">Log Out</a></td>
                </tr>
            </tbody>
        </table>        
    </body>
</html>

以下是帐户业务对象:要确保连接到accountview.jsp以连接到帐户以提取帐户信息的数据库是正确的。

公共类帐户实现Serializable {

private String acctNo;
private String custId;
private String type;
private double balance;
private String message;

/**
 * No-Arg Constructor
 */
public Account() {

}

/**
 * Single Arg constructor accepts one parameter
 * connects to database and builds the customers 
 * account object 
 * @param acct
 */
public Account(String acct) throws SQLException {

    Connection connect = null;
    Statement statement = null;
    ResultSet result = null;
    String sql = "SELECT * FROM Accounts WHERE acctNo = '" + acct + "';";

    try {
        /*establishes connection and creates statement */
        connect = acctConnect();
        statement = connect.createStatement();
        result = statement.executeQuery(sql);

        /*loops through the database row containing the information
        and builds the row*/
        while (result.next()) {
            this.acctNo = result.getString("acctNo");
            this.custId = result.getString("Cid");
            this.type = result.getString("Type");
            this.balance = result.getDouble("Balance");
        }
    } catch (SQLException e) {
        System.out.println("Error: " + e);
    } finally {
        connect.close();
    }
}

/**
*sets account number 
*@param acctNo
*/
public void setAcctNo(String acctNo) {
    this.acctNo = acctNo;
}

/**
 *sets customer id
 * @param custId
 */
public void setCustId(String custId) {
    this.custId = custId;
}

/**
 * sets account type 
 * @param acctType
 */
public void type(String type) {
    this.type = type;
}

/**
 * sets balance for the account
 * @param balance
 */
public void setBalance(double balance) {
    this.balance = balance;
}

/**
 * returns account number
 * @return String
 */
public String getAcctNo() {
    return acctNo;
}

/**
 * returns customer id
 * @return String
 */
public String getCustId() {
    return custId;
}

/**
 * returns account type
 * @return String
 */
public String getType() {
    return type;
}

/**
 * returns account balance
 * @return double
 */
public double getBalance() {
    return balance;
}

/**
 * returns account information into string form
 * @return String 
 */
public String getAcct() {
    return this.acctNo + " " + this.custId + " " + this.type + " " + this.balance;
}

/**
 * returns message set by other methods in class
 * @return String
 */
public String getMessage(){
    return this.message;
};

/**
 * Establishes connection to database
 * @return Connection
 */
public static Connection acctConnect() {
    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch (ClassNotFoundException e) {
        System.out.println("Errors: " + e);
    }

    /*Declare new connection*/
    Connection con = null;
    try {

        /*Define connection*/
        con = DriverManager.getConnection("jdbc:odbc:ChattDB");

    } catch (SQLException e) {

        System.out.println("Error: " + e);

    }

    /*Returns connection con*/
    return con;
}

/**
 * Uses object account number to get all information from the database
 * where the account number is valid
 */
public void findDB()  {
    Connection connect = null;
    Statement statement = null;
    ResultSet result = null;
    String sql = "SELECT * FROM Accounts WHERE acctNo = '" + acctNo + "';";

    try {

        connect = acctConnect();
        statement = connect.createStatement();
        result = statement.executeQuery(sql);

        /*Loop through the result to gather all of the information from the 
        row in the database*/
        while (result.next()) {
            this.acctNo = result.getString("acctNo");
            this.custId = result.getString("Cid");
            this.type = result.getString("Type");
            this.balance = result.getDouble("Balance");
        }
        connect.close();
    } catch (SQLException e) {

        System.out.println("Error: " + e);

    }
}

/**
 * Connects to the database accesses the desired account and deposits to that 
 * account. Updates the database. and finally closes the connection. This
 * method throws the sql exception.
 * @param acctNo
 * @param depAmount
 * @throws SQLException
 */
public void deposit(String acctNo, double depAmount) throws SQLException {

    Connection connect = acctConnect();
    Statement statement = connect.createStatement();
    ResultSet result = null;
    String sql = "Select balance From Accounts Where acctNO = '" + acctNo + "';";
    String update = null;
    int updateSet = 0;
    double balance = 0.00;
    double newBalance;

    result = statement.executeQuery(sql);

    /* retrieves the balance of the current account */
    while (result.next()) {
        balance = result.getDouble("Balance");
    }

    /* updates the balance in this object and the database */
    newBalance = balance + depAmount;
    update = "Update Accounts Set Balance = '" + newBalance + "' Where acctNO = '" + acctNo + "';";
    updateSet = statement.executeUpdate(update);
    this.balance = newBalance;

    /* closes connection */
    connect.close();
}

/**
 * Withdraws funds from the current account. Throws an exception 
 * for insufficient funds
 * @param acctNo
 * @param withdrawal
 * @throws SQLException
 * @throws Exception
 */
public void withdraw(String acctNo, double withdrawal) throws SQLException, Exception {

    Connection connect = acctConnect();
    Statement statement = connect.createStatement();
    ResultSet result = null;
    String sql = "Select balance From Accounts Where acctNO = '" + acctNo + "';";
    String update = null;
    int updateSet = 0;
    double balance = 0.00;
    double newBalance;

    result = statement.executeQuery(sql);

    /* gets balance of the current account from the database */
    while (result.next()) {
        balance = result.getDouble("Balance");
    }

    /* checks to see if the withdrawal amount is more than the balance
    and if so the exception is thrown and an insufficient funds message is 
    set */
    if (balance < withdrawal){
        this.message = "Insufficcient Funds";
        throw new Exception();
    }else{

    /* sets new balance and updates the current database account balance */
    newBalance = balance - withdrawal;
    update = "Update Accounts Set Balance = '" + newBalance + "' Where acctNo = '" + acctNo + "';";
    updateSet = statement.executeUpdate(update);
    this.balance = newBalance;

    }

    /* closes connection to database */
    connect.close();
}

/**
 * Transfers funds from one account to another by calling the withdrawal 
 * and deposit methods.
 * @param fromAcct
 * @param toAcct
 * @param transfer
 * @throws SQLException
 * @throws Exception
 */
public void transfer(String fromAcct, String toAcct, double transfer) throws SQLException, Exception {

    /* Call withdraw method on from account */
    withdraw(fromAcct, transfer);

    /* deposit to to account */
    deposit(toAcct, transfer);

    /* both methods close their own database connection so it is not necessary to do so here */
}

/**
 * Sets up new account for existing customers 
 * @param acctNo
 * @param custID
 * @param type
 * @param balance
 * @throws SQLException
 */
public void estabAccount(String custID, String type, double balance) throws SQLException {
    System.out.println(custID + " " + type + " " + balance);
    /* Establish connection and update the database with a new row containing the new account info */
    Connection connect = acctConnect();
    Statement statement = connect.createStatement();
    String sql = "Insert Into accounts (Cid, Type, Balance) Values ('" + custID + "', '" + type + "', " + balance + ");";
    System.out.println(sql);
    /* Execute Query and close connection */
    statement.executeUpdate(sql);
    connect.close();

}

public void findDB(String id) {
    throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}

}

1 个答案:

答案 0 :(得分:0)

看看你的EL片刻,你有这些线路:

<td colspan="2">${account.custId}</td>
<td colspan="2">${account.acctNo}</td>
<td colspan="2">${account.type}</td>
<td colspan="2">${account.balance}</td>

您说要访问名为balance的变量的account字段,这是完全有效的,但是,在您的servlet中,您将帐户变量分配给名为{的会话属性{1}} a1,因此EL不知道该放什么

TL; DR将您的account更改为ses1.setAttribute("a1", a1);

有关表达式语言(EL)see this

的更多信息