На моей странице 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;"> </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;"> </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;"> </div>
<div>
<button class="button">Submit »</button>
<span><button class="button">Reset »</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);
}
}
@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;
}
NumberFormatException происходит, когда значение, передаваемое ParseInt не является числовым или не может иначе быть разобран. Перед вызовом метода убедитесь, что вы дезинфицируете свой ввод. Например, нарисуйте любые пробелы, удалите любые валютные знаки, например, $, £ и т. Д. –
@ GilesThompson - ** Я убедился, что вход свободный от белых пробелов и любых знаков валюты, т.е. $, £ и т. Д., Но нет улучшения в выход. ** – mindfreak