5 Replies - 348 Views - Last Post: 20 September 2017 - 12:33 AM

#1 Yevgeni Duvenage  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 15
  • Joined: 11-September 17

Servlet handling its own outputted HTML form

Posted 18 September 2017 - 12:27 PM

I am still new to Java and I find that by far the aspect taking longest to understand is servlets.

I am busy writing a servlet that must initially show an HTML form (if a FORM is actually needed here), in which
the user enters a monetary amount into a text field.

There are 3 buttons underneath the textfield: Balance, Deposit and Withdraw.

Deposit: adds the amount in the textfield to the total "bank account" of the user.
Withdraw: subtracts the amount in the textfield from the total "bank account" of the user.
Balance: displays the current remaining total of the "bank account" just under the textfield.

What is unusual is that in this task, they require me to only use a servlet to address all these things.

So the servlet HTMLBank.java must do the following:

- Display form with textfield for entering an amount, a line for showing the current remaining total of the bank
account, and the abovementioned buttons doing the said actions.

- Add entered amount to the account total, via appropriate button's input.

- Subtract entered amount from the total, via appropriate button's input.

- Show to the screen the current remaining total of bank account, via appropriate button's input.

So, where it's common to use a separate HTML document as the form page, and have its submission redirect the
browser to the separate servlet file for data processing, here I have to make the servlet write that form, as well
as take its input and then show the described output - all on the same Web page.

And this is where I am confused as to how to achieve this. Firstly, these buttons I coded and assigned methods to,
do not work. I click them but nothing happens. Help on the buttons would be also appreciated.

The following is the code of my HTMLBank.java servlet (this is nothing confidential as it's not actually linked
to any real bank account. Just a textbook task.):

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;
import java.text.DecimalFormat;

public class HTMLBank extends HttpServlet
{
	double balance;
	String formattedAmount;

	public void init() throws ServletException
	{
		balance = 0;
		formattedAmount = "";
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		response.setHeader("Expires", "Tues, 01 Jan 1980 00:00:00 GMT");

		HttpSession session = request.getSession(true);

		formatBalance();

		out.println("<html>");
			out.println("<hr>");
			out.println("<title>Online Bank ATM Simulator</title>");
			out.println("<h1 align = \"center\">Bank ATM Simulation</h1>");
			out.println("<body>");
				out.println("<form name = \"moneyform\" method = \"POST\" action = \"HTMLBank\">");
					out.println("<center>");
					out.println("Amount: ");
					out.println("<input type = \"text\" name = \"amount\" id = \"amount\" size = \"20\"><br><br>");
					out.println("Balance: ");
					out.println(formattedAmount + "<br><br>");
					out.println("<button type = \"submit\" name = \"balButton\" id = \"balButton\">Balance</button>");
					out.println("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
					out.println("<button type = \"submit\" name = \"depButton\" id = \"depButton\">Deposit</button>");
					out.println("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
					out.println("<button type = \"submit\" name = \"withdrButton\" id = \"withdrButton\">Withdraw</button>");
					out.println("</center>");
				out.println("</form>");
			out.println("</body>");
			out.println("<br>");
			out.println("<hr>");
		out.println("</html>");

		if(request.getParameter("depButton") != null && request.getParameter("depButton").equals("Deposit"))
		{
			if(verifyAmount(request))
			{
				addToBalance(request);
			}
			else
			{
				out.println("<html>");
					out.println("<head>");
						out.println("<title>Amount Input Error</title>");
					out.println("</head>");

					out.println("<body>");
						out.println("<h1>Error processing the input.</h1><br><br>");
						out.println("Please ensure your input:<br><br>");
						out.println("- Is strictly a number.");
						out.println("- Is a positive, non-zero amount.");
					out.println("</body>");
				out.println("</html>");
			}
		}

		if(request.getParameter("withdrButton") != null && request.getParameter("withdrButton").equals("Withdraw"))
		{
			if(verifyAmount(request))
			{
				subtractFromBalance(request);
			}
			else
			{
				out.println("<html>");
					out.println("<head>");
						out.println("<title>Amount Input Error</title>");
					out.println("</head>");

					out.println("<body>");
						out.println("<h1>Error processing the input.</h1><br><br>");
						out.println("Please ensure your input:<br><br>");
						out.println("- Is strictly a number.");
						out.println("- Is a positive, non-zero amount.");
					out.println("</body>");
				out.println("</html>");
			}
		}

		if(request.getParameter("balButton") != null && request.getParameter("balButton").equals("Balance"))
		{
			showBalance(request, response);
		}

		session.setAttribute("forwardTo", "HTMLBank");

		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/" + (String)session.getAttribute("forwardTo"));
		dispatcher.forward(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		doPost(request, response);
	}

	public boolean verifyAmount(HttpServletRequest request)
	{
		boolean amountValid = false;

		if(request.getParameter("amount") != "" && Double.parseDouble(request.getParameter("amount")) > 0)
			amountValid = true;
		else
			amountValid = false;

		return amountValid;
	}

	public void addToBalance(HttpServletRequest request) throws IOException
	{
		double userAmount = Double.parseDouble(request.getParameter("amount"));
		balance = balance + userAmount;

		formatBalance();
	}

	public void subtractFromBalance(HttpServletRequest request) throws IOException
	{
		double userAmount = Double.parseDouble(request.getParameter("amount"));
		balance = balance + userAmount;

		formatBalance();
	}

	public void showBalance(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		response.sendRedirect(".");
	}

	public void formatBalance()
	{
		DecimalFormat dollars = new DecimalFormat("$###,###.###");
		formattedAmount = dollars.format(balance);
	}

	public void destroy()
	{

	}
}


The part I'm unsure of is how to code the same servlet to create a form, then use its own form's input and respond
back to that same Web page. The operations - deposit, withdraw, balance display - are to run as many times as the
user desires.

Any fixes, help and suggestions are hugely appreciated! Thanks.

Is This A Good Question/Topic? 0
  • +

Replies To: Servlet handling its own outputted HTML form

#2 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1571
  • View blog
  • Posts: 3,529
  • Joined: 05-April 11

Re: Servlet handling its own outputted HTML form

Posted 18 September 2017 - 12:37 PM

Aren't you supposed to add a value attribute to your buttons?
<button name="depButton"  value="Deposit">Deposit</button>

This post has been edited by CasiOo: 18 September 2017 - 12:38 PM

Was This Post Helpful? 0
  • +
  • -

#3 Yevgeni Duvenage  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 15
  • Joined: 11-September 17

Re: Servlet handling its own outputted HTML form

Posted 19 September 2017 - 02:28 AM

Hey, CasiOo.

I will correct the button coding to try the suggestion, thank you.
Was This Post Helpful? 0
  • +
  • -

#4 Yevgeni Duvenage  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 15
  • Joined: 11-September 17

Re: Servlet handling its own outputted HTML form

Posted 19 September 2017 - 08:07 AM

Guys, I insert below the updated code of this servlet and after it describe how the servlet must perform. Please point me in the right direction.

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;
import java.util.*;
import java.text.DecimalFormat;

public class HTMLBank extends HttpServlet
{
	double balance;

	public void init() throws ServletException
	{
		balance = 0;
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		PrintWriter out = response.getWriter();

		request.setAttribute("formattedBal", formatBalance());

		out.println("<html>");
			out.println("<hr>");
			out.println("<title>Online Bank ATM Simulator</title>");
			out.println("<h1 align = \"center\">Bank ATM Simulation</h1>");
			out.println("<body>");
				out.println("<form method = \"GET\" action = \"HTMLBank\">");
					out.println("<center>");
					out.println("Amount: ");
					out.println("<input type = \"text\" name = \"amount\" id = \"amount\" size = \"20\"><br><br>");
					out.println("Balance: ");
					out.println((String)request.getAttribute("formattedBal") + "<br><br>");
					out.println("<button name = \"balButton\" value = \"Balance\">Balance</button>");
					out.println("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
					out.println("<button name = \"depButton\" value = \"Deposit\">Deposit</button>");
					out.println("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
					out.println("<button name = \"withdrButton\" value = \"Withdraw\">Withdraw</button>");
					out.println("</center>");
				out.println("</form>");
			out.println("</body>");
			out.println("<br>");
			out.println("<hr>");
		out.println("</html>");
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/html");
		response.setHeader("Expires", "Tues, 01 Jan 1980 00:00:00 GMT");

		PrintWriter out = response.getWriter();

		if(request.getParameter("depButton") != null && request.getParameter("depButton").equals("Deposit"))
		{
			if(verifyAmount(request))
			{
				addToBalance(request);
				clearDisplay(request);

				request.setAttribute("formattedBal", formatBalance());

				out.println("<html>");
					out.println("<hr>");
					out.println("<title>Online Bank ATM Simulator</title>");
					out.println("<h1 align = \"center\">Bank ATM Simulation</h1>");
					out.println("<body>");
						out.println("<form method = \"GET\" action = \"HTMLBank\">");
							out.println("<center>");
							out.println("Amount: ");
							out.println("<input type = \"text\" name = \"amount\" id = \"amount\" size = \"20\"><br><br>");
							out.println("Balance: ");
							out.println((String)request.getAttribute("formattedBal") + "<br><br>");
							out.println("<button name = \"balButton\" value = \"Balance\">Balance</button>");
							out.println("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
							out.println("<button name = \"depButton\" value = \"Deposit\">Deposit</button>");
							out.println("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;");
							out.println("<button name = \"withdrButton\" value = \"Withdraw\">Withdraw</button>");
							out.println("</center>");
						out.println("</form>");
					out.println("</body>");
					out.println("<br>");
					out.println("<hr>");
				out.println("</html>");
			}
			else
			{
				out.println("<html>");
					out.println("<head>");
						out.println("<title>Amount Input Error</title>");
					out.println("</head>");

					out.println("<body>");
						out.println("<h1>Error processing the input.</h1><br><br>");
						out.println("Please ensure your input:<br><br>");
						out.println("- Is strictly a number.");
						out.println("- Is a positive, non-zero amount.");
					out.println("</body>");
				out.println("</html>");
			}
		}

		if(request.getParameter("withdrButton") != null && request.getParameter("withdrButton").equals("Withdraw"))
		{
			if(verifyAmount(request))
			{
				subtractFromBalance(request);
			}
			else
			{
				out.println("<html>");
					out.println("<head>");
						out.println("<title>Amount Input Error</title>");
					out.println("</head>");

					out.println("<body>");
						out.println("<h1>Error processing the input.</h1><br><br>");
						out.println("Please ensure your input:<br><br>");
						out.println("- Is strictly a number.");
						out.println("- Is a positive, non-zero amount.");
					out.println("</body>");
				out.println("</html>");
			}
		}

		if(request.getParameter("balButton") != null && request.getParameter("balButton").equals("Balance"))
		{
			showBalance(request, response);
		}
	}

	public boolean verifyAmount(HttpServletRequest request)
	{
		boolean amountValid = false;

		if(request.getParameter("amount") != "" && Double.parseDouble(request.getParameter("amount")) > 0)
			amountValid = true;
		else
			amountValid = false;

		return amountValid;
	}

	public void addToBalance(HttpServletRequest request) throws IOException
	{
		double userAmount = Double.parseDouble(request.getParameter("amount"));
		balance = balance + userAmount;
	}

	public void subtractFromBalance(HttpServletRequest request) throws IOException
	{
		double userAmount = Double.parseDouble(request.getParameter("amount"));
		balance = balance + userAmount;
	}

	public void showBalance(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{

	}

	public String formatBalance()
	{
		DecimalFormat dollars = new DecimalFormat("$###,###.###");
		String formattedAmount = dollars.format(balance);
		return formattedAmount;
	}

	public void clearDisplay(HttpServletRequest request)
	{
		request.setAttribute("amount", "");
		request.setAttribute("formattedBal", "");
	}

	public void destroy()
	{

	}
}


For now ignore all custom-defined methods and only look at addToBalance() (and if needed, the methods it calls), as I
am first trying to get this one function to work as needed. When I succeed, I'll code other functions similarly,
except the difference in the arithmetic operations.

To explain what needs to happen, using the function I'm trying to get to work right now:

1) Initially form appears with "Balance: $0" displayed and and empty textbox labeled "Amount:".
2) The user enters money amount and clicks "Deposit". The servlet must redisplay the form, but
the "$0" and the textfield must be cleared. Invisible to user, the entered amount is added to the balance.
3) If the user clicks "Balance", the page must redisplay, showing the current balance as "Balance: $xxx" and the
textfield must once again be cleared.

The problem is that when I run the servlet per above code, enter an amount and click "Deposit", the only thing that
happens is the textfield clears, but the "$0" remains shown. I.e. the button does not work as intended.

I appreciate your help a lot! Thanks.
Was This Post Helpful? 0
  • +
  • -

#5 CasiOo  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1571
  • View blog
  • Posts: 3,529
  • Joined: 05-April 11

Re: Servlet handling its own outputted HTML form

Posted 19 September 2017 - 01:24 PM

Is your HttpServlet a singleton, or is it a new instance on each http request?

You'll need to step through your code with the debugger, or add some logging hints, so we know where it starts misbehaving.

Also you could change the line
out.println((String)request.getAttribute("formattedBal") + "<br><br>");


to
String balance = formatBalance();
out.println(balance + "<br><br>");


No need to set an attribute on the request object?
Was This Post Helpful? 0
  • +
  • -

#6 Yevgeni Duvenage  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 15
  • Joined: 11-September 17

Re: Servlet handling its own outputted HTML form

Posted 20 September 2017 - 12:33 AM

Hey CasiOo.

I don't know what you mean by singleton or new instance per each request, but the servlet must:

- Initially show blank textfield and "$0" at the balance label.
- Add the inputted amount to the current balance (initially 0), or subtract it from current balance.
- After the operation of addition or subtraction the textfield must be cleared and the balance amount under it too. So must read "Balance: " without the "$XXX".
- Only if user clicks the "Balance" button must the current balance appear as "Balance: $XXX".

The reason I set that attribute on the request object is I needed to define the current balance as an attribute, so that I can refer to it subsequently when needing to re-display its value.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1