This is the second example in my lesson on Java Server Pages or JSP. This is a basic example on how to get the user input from a form. The interface is composed of two labels and two textboxes that will be used for the input, then a button that will be used to get the two parameter input from the form and send it to the Java Server Pages program and the JSP program will compute the sum of the two parameters from the form and it will display it on the web browser.
The machine problem for this example is: Create a program that will accept two numbers as input (data type integer), then the program will compute and display the sum of the numbers to web browser.
The algorithm for this example machine problem is: to input first number and second number compute the sum of the numbers using the formula: sum = first number + second number, and display or print the sum.
After having an algorithm for the machine problem, it is now time to create the user interface wherein the user can input the two numbers. To create the interface, HTML code will be used. Below is the code for the interface. Note in this example the filename for the said interface will be “frmSum.jsp”
<form action="computesum.jsp" method="post">
<table border="0" bgcolor="green">
<input type="text" name="txtnum1" size="20">
<input type="text" name="txtnum2" size="20">
<input type="submit" value="Compute">
After the code have been save, it is now time to create another code that will get the two input from form and it will compute and display the sum. This time the filename should be “computesum.jsp” because it is declared in the form particularly in the action of the form that whenever the button in the form is click, it will look for the filename “computesum.jsp”. If the program cannot locate that filename, it will cause an error. The JSP code to get the input from form and compute the sum is shown below.
String strnum1= request.getParameter("txtnum1");
String strnum2= request.getParameter("txtnum2");
int intnum1 = Integer.parseInt(strnum1);
int intnum2 = Integer.parseInt(strnum2);
int intsum = intnum1 + intnum2;
out.println("Sum:" + sum);
In the code above, we declared two string variables, the strnum1 and strnum2. These variables will store temporarily the input from a form particularly the input from textboxes in the form namely txtnum1 and txtnum2. We can get the parameters using the request.getParameter(). Another two variables is declare the intnum1 and intnum2 of type integer, this variables will store the numbers which is converted from string to integer using the Integer.parseInt(). We need to convert string to integer in order to do arithmetic operation. The variable that will be used to store the sum in the variable intsum and it is assigned with the formula: intsum = intnum1 + intnum2. And last line of the code is the ouput.println command that will be used to display the sum in web browser.