dcsimg
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Thread: Servlet handling its own outputted HTML form

Threaded View

  1. #1
    Join Date
    Sep 2017
    Posts
    15

    Servlet handling its own outputted HTML form

    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 updated 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.):

    Code:
    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()
    	{
    
    	}
    }
    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.

    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.
    Last edited by Yevgeni Duvenage; September 19th, 2017 at 10:11 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width




On-Demand Webinars (sponsored)