CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8
  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.

  2. #2
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,877

    Re: Servlet handling its own outputted HTML form

    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.
    The URL passed back to the servlet from the form or the POST values could have a value saying what values are being returned and what to do with them.
    Norm

  3. #3
    Join Date
    Sep 2017
    Posts
    15

    Re: Servlet handling its own outputted HTML form

    Guys, I've modified the code trying to get it to work. If you can go through it (I also describe how the servlet must perform in the post), I'll be infinitely obliged to you. Thanks.

  4. #4
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,877

    Re: Servlet handling its own outputted HTML form

    I've modified the code
    What happens now when the code executes?

    How are you debugging the code to see what it is doing?
    Norm

  5. #5
    Join Date
    Sep 2017
    Posts
    15

    Re: Servlet handling its own outputted HTML form

    Hey, Norm.

    All that happens is the initial form shows on the screen, with blank textfield and "Balance: $0" shown below it.

    When I click the "Deposit" button, the textfield clears, I see on the URL the button and textfield names and values passed, but other than that the same screen/form remains, except the "$0" is not cleared, as I am trying to code and achieve.

    As for debugging, firstly I ensure the code compiles w/o errors and there are no run-time errors. Which in the code as currently given there are none of. Then, I logically follow what the code execution will do from starting the servlet, through user clicking the "Deposit" button, and follow it like that. I don't know how to make it go back to the initial page to let the user click other buttons.

    I just need the balance variable to update based on whether "Deposit" or "Withdraw" is clicked by the user, and balance to display if he clicks "Balance", so pretty much it's the same form that needs to be shown the whole time, just with the balance variable displayed when its buttons are clicked, otherwise just add/subtract from current balance.
    Last edited by Yevgeni Duvenage; September 20th, 2017 at 02:46 AM.

  6. #6
    Join Date
    May 2009
    Location
    Lincs, UK
    Posts
    298

    Re: Servlet handling its own outputted HTML form

    You keep the balance in an instance variable, so every time the servlet is instanciated a new variable is created (and initialised to 0.0).

    If you changed the balance to a static variable then all instances would use the same value; thus all users will share the same balance.

    What you need to do is save the balance as a session attribute, so it is always available, no matter how the servlet instances are created and destroyed, and the value is unique per session (ie, per user).

  7. #7
    Join Date
    Jun 1999
    Location
    Eastern Florida
    Posts
    3,877

    Re: Servlet handling its own outputted HTML form

    Last edited by Norm; September 23rd, 2017 at 05:47 PM.
    Norm

  8. #8
    Join Date
    Aug 2017
    Posts
    36

    Re: Servlet handling its own outputted HTML form

    Servlet API provides support for custom Exception and Error Handler servlets that we can configure in deployment descriptor. The whole purpose of these servlets are to handle the Exception or Error raised by application and send useful HTML response to user. We can provide link to application home page or some details to let user know what went wrong.

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
  •  





Click Here to Expand Forum to Full Width

Featured