JSP and Java class

A JSP not only can interact with a JavaBean (previous tutorial) but also can interact with a normal Java class. To do so, we use JSP page directives. In this tutorial, we will see how a JSP interacts with a Java class.

  1. Open the jsplabs project created in previous tutorial.
  2. Right-click on the src folder, select New→Package. Name it as calculation.basic.
  3. Right-click on the calculation.basic package, select New→Class. Name it Calculation and click Finish.
  4. Insert the following simple function to the Calculation class:

    	public double square(double x){
    		return Math.pow(x, 2);
    	}
  5. Save the file.
  6. Now, right click on the WebContent folder, select New→JSP file.
  7. Name it class.jsp and click Finish.
  8. Insert the following codes between the <body> tags.

    <%@ page import="calculation.basic.*" %>
    <% Calculation c=new Calculation(); %>
    2 square is <%= c.square(2) %>
  9. Save the file.
  10. Run it by right clicking on it then selecting Run→Run on Server. Select Finish.
  11. You will see the result on your web browser at the URL: http://localhost:8080/jsplabs/class.jsp


Exercises

  1. Modify the class.jsp file to compute the square of a number input from the URL. For example, the request class.jsp?num=3 will have a response: “3 square is 9.0”.
  2. Add another function called cube to compute the cube of a number. Then modify the class.jsp to compute the square or cube of a number according to the input from the URL. For example, if the request is : class.jsp?num=3&cal=cube, the response will be: “3 cube is 27.0”; if the request is : class.jsp?num=4&cal=square, the response will be: “4 square is 16.0”;