根据jsp页面的输入调用Servlet方法

时间:2015-07-12 11:13:10

标签: java jsp servlets

我的JSP页面有2个输入框:

1)存款金额。

2)退出金额。

由于Javascript验证,用户可以在任一方框中输入。根据jsp页面的输入,我试图调用适当的servlet方法。然而,到目前为止,这是一次令人沮丧的经历。

我面临的挑战是,如果我输入存款金额,我会获得提款金额NumberFormatException,反之亦然。我该如何消除这个?

.jsp页面

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!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>Insert title here</title>

    <link rel="stylesheet" href="colorShades.css">

    <script type="text/javascript"> 

        function myfunc1(){
            var deposit = document.getElementById("deposit");
            if(deposit.value.length >0){
                document.getElementById("withdraw").disabled = true;
            }

            else{
                document.getElementById("deposit").disabled = false;
            }
        }


    function myfunc2(){
            var withdraw = document.getElementById("withdraw");
            if(withdraw.value.length >0){
                document.getElementById("deposit").disabled = true;
            }

            else{
                document.getElementById("withdraw").disabled = false;
            }
        }


    </script>

    </head>
    <body>

    <form action="DepositWithdrawServlet" method="post"> 

        <div>
            <label>Account No:</label>
            <input type="text" name="accountNo" class="input_boxAdj"  id="account" />
        </div>
        <div style="clear:both;">&nbsp;</div>


            <div>
                <label>Enter amount to deposit:</label>
                <input type="text" name ="depositAmt" values="deposit" class="input_boxAdj" id="deposit" onblur="myfunc1()" />

            </div>  
        <div style="clear:both;">&nbsp;</div>


            <div>
                <label>Enter amount to withdraw:</label>
                <input type="text" name ="withdrawAmt" values="withdraw" class="input_boxAdj" id="withdraw" onblur="myfunc2()"/>
            </div>
            <div style="clear:both;">&nbsp;</div>



        <div> 
                <button class="button">Submit &raquo;</button>     
                <span><button class="button">Reset &raquo;</button></span>
        </div>


    </form>

    </body>
    </html>

Servlet代码:

package com.banking.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.banking.dao.WebBankProjectDao;
import com.banking.dao.WebBankProjectDaoImpl;
import com.banking.pojo.WebBankTemporaryPojo;

/**
 * Servlet implementation class DepositWithdrawServlet
 */
@WebServlet("/DepositWithdrawServlet")
public class DepositWithdrawServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public DepositWithdrawServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        out.println("Reached inside servlet");

        WebBankTemporaryPojo tempPojo = new WebBankTemporaryPojo();         
        WebBankProjectDao bankdao = new WebBankProjectDaoImpl();

        int initialBalance = 0; 
        int finalBalance = 0;

        int depositAmt = Integer.parseInt(request.getParameter("depositAmt"));
        System.out.println("Deposit Amt: " +depositAmt);

        System.out.println("Value" + (depositAmt>=0));


        if((depositAmt>=0 && request.getParameter("withdrawAmt")==null)){

                if(initialBalance==0){
                    out.print("<body style='color:red; font-family:Times New Roman; font-style:italic; font-size:25px'>");
                    initialBalance = depositAmt - 1000;
                    out.print("Amount of Rs.1000 will go as MINIMUM BALANCE to be maintained");
                }

                else{
                    finalBalance = depositAmt + initialBalance;

            }
        }

        tempPojo.setDepositAmt(request.getParameter("depositAmount"));
        bankdao.depositAmt(finalBalance);



        int withdrawAmt = 0;        
        int withdrawAmount = Integer.parseInt(request.getParameter("withdrawAmt"));
        System.out.println("Withdraw Amt: " +withdrawAmount);

        if(withdrawAmount>0 && request.getParameter("depositAmt")==null){


            if(Integer.parseInt(request.getParameter("withdrawAmount"))>finalBalance){
                out.print("<body style='color:red; font-family:Times New Roman; font-style:italic; font-size:25px'>");
                out.print("Oops !! Please deposit some funds before you can withdraw"); }

            else if(Integer.parseInt(request.getParameter("withdrawAmount"))<0 || Integer.parseInt(request.getParameter("withdrawAmount"))==0){
                out.print("<body style='color:red; font-family:Times New Roman; font-style:italic; font-size:25px'>");
                out.print("The minimum amount you can withdraw is Rs. 100");
            }

            else if(Integer.parseInt(request.getParameter("withdrawAmount"))%100==0){
                out.print("<body style='color:red; font-family:Times New Roman; font-style:italic; font-size:25px'>");
                out.print("You should enter in the multiples of 100 to withdraw money"); 
            }
            else if(Integer.parseInt(request.getParameter("withdrawAmount"))>finalBalance){
                out.print("Sorry, you have insufficient funds !!"); }
            else{
                withdrawAmt = finalBalance - Integer.parseInt(request.getParameter("withdrawAmount"));
            }

        }


        tempPojo.setWithdrawAmt(request.getParameter("withdrawAmount"));
        bankdao.depositAmt(withdrawAmt);


    }

}

DAOImpl.java

@Override
public boolean withdrawAmt(int accountNo) {
    Connection con = DBUtility.getConnection();
    String sql="update temporarytransaction  set withdrawAmt=? where 
    accountNo=?";

    WebBankTemporaryPojo tempPojo = new WebBankTemporaryPojo();

    try {
        PreparedStatement stmt=con.prepareStatement(sql);
        stmt.setString(1, tempPojo.getWithdrawAmt());
        stmt.setString(2, tempPojo.getAccountNo());

        int no=stmt.executeUpdate();

        if(no>0){
            System.out.println("amount withdraw successfull");
        }

    }catch (Exception e){
        e.printStackTrace();
    }

    return false;
}


@Override
public boolean depositAmt(int accountNo) {
    Connection con = DBUtility.getConnection();
    String sql="update temporarytransaction set depositAmt =? where accountNo=?";

    WebBankTemporaryPojo tempPojo = new WebBankTemporaryPojo();
    try {
        PreparedStatement stmt=con.prepareStatement(sql);
        stmt.setString(1, tempPojo.getDepositAmt());
        stmt.setString(2, tempPojo.getAccountNo());


        int no=stmt.executeUpdate();

        if(no>0){
            System.out.println("amount deposit successful");
        }

    }catch (Exception e){
        e.printStackTrace();
    }       return false;
}

3 个答案:

答案 0 :(得分:2)

您可以简单地将其包装在空检查中:

int depostAmt = 0;
if(request.getParameter("depositAmt") != null){
        depositAmt = Integer.parseInt(request.getParameter("depositAmt"));
}

答案 1 :(得分:1)

您应该使用BigDecimal类进行货币计算。只需清理客户端的输入,然后调用新的BigDecimal传递金额,即BigDecimal depositAmt = new BigDecimal("22.50");确保您收到有效金额处理日志传入屏幕的金额,即Logger.getLogger(name.of.your.class).log(Level.info,"Amount passed in was {0}",amountPassedIn);这是您可以确定的只提供数值。

答案 2 :(得分:0)

使用request.getParameter(“withdrawAmount”)!= null和  request.getParameter(“depositAmt”)!= parseInt之前的null。 因为你们中的任何一个都可能会变空。