简体   繁体   中英

Connecting the Servlet to the jsp page

EDIT: When the accountview is shown I can not get the database to pull up the acctNo, Cust Id, account type and balance from the mini bank account project I was doing. I added the account business object there to make sure the SQL is connected to pull up, the name pulls up but the acctNo, Cust Id, account type and balance will not. It's all connected, therefore I added them all, all the pages work, but nothing pops in from the database

How do I connect this 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";
        }

    }

To connect to this jsp page to pull out the Customer ID, Account Number, Account Type, and Balance to appear in the table I created? The Servlet is working, the database is connected, I just need a way for the JSP page to read in the data and actually print it out.

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

Here is the account Business Object: want to make sure it is correct for hooking up the accountview.jsp to connect to the account to pull out the DB the account information.

public class Account implements 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.
}

}

Take a look at your EL for a moment, you have these lines right here:

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

You're saying to access the balance field of a variable called account , which is perfectly valid, however, in your servlet, you assign the account variable to a session attribute called a1 not account , therefore EL doesnt know what to put there

TL;DR change your ses1.setAttribute("a1", a1); to ses1.setAttribute("account", a1);

For more information about Expression Language (EL) see this

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