2015-07-12 1 views
-1

На моей странице JSP есть 2 поля ввода:Вызов методов сервлетов на основе ввода страницы jsp

1) Сумма для внесения депозита.

2) Сумма для снятия.

Из-за проверки Javascript, пользователь может ввести любой из этих окон:. Основываясь на входах страницы jsp, я пытаюсь вызвать соответствующий метод сервлета. Тем не менее, это был разочаровывающий опыт, до сих пор.

Задача, с которой я столкнулся, заключается в том, что если я ввожу сумму вклада, я получаю для снятия суммы и наоборот. Как я могу это устранить?

.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; 
} 
+0

NumberFormatException происходит, когда значение, передаваемое ParseInt не является числовым или не может иначе быть разобран. Перед вызовом метода убедитесь, что вы дезинфицируете свой ввод. Например, нарисуйте любые пробелы, удалите любые валютные знаки, например, $, £ и т. Д. –

+0

@ GilesThompson - ** Я убедился, что вход свободный от белых пробелов и любых знаков валюты, т.е. $, £ и т. Д., Но нет улучшения в выход. ** – mindfreak

ответ

2

Вы можете просто обернуть это в нуль проверки:

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

** Не помогает. Пробовал это, прежде чем публиковать вопрос. ** – mindfreak

+0

Возможно, это была пустая строка, которая изменила бы приведенный выше код на if (! StringUtils.isBlank ("request.getParameter (" depositAmt ")) {...} – Woot4Moo

0

использование REQ uest.getParameter ("removeAmount")! = null и request.getParameter ("depositAmt")! = null перед parseInt. , потому что возможно, что любой из вас получит null.

1

Вы должны использовать класс BigDecimal для проведения денежных расчетов. Просто очистите входные данные от ваших клиентов, затем вызовите новую передачу BigDecimal в количествах i.e BigDecimal depositAmt = new BigDecimal("22.50");. Чтобы гарантировать, что вы получаете действительную сумму для обработки журнала, суммы, переданные на экран. I 0e. Logger.getLogger(name.of.your.class).log(Level.info,"Amount passed in was {0}",amountPassedIn); Это было бы точно, если бы были указаны только числовые значения.

+0

Благодарим вас за предложение. Поскольку я новичок в Servlets и JSP, реализация вашего метода кажется немного сложной, если не из-за несоразмерности. – mindfreak

+1

Что это за вызов? Я просто предлагаю вам выводить/регистрировать данные, которые вы получаете от клиента, чтобы убедиться, что он фактически является числовым. И снова, повторяю, вы НЕ должны использовать int или Integer для выполнения денежных операций, так как могут возникнуть ошибки округления. Вы должны использовать класс BigDecimal - для чего он предназначен. –

Смежные вопросы