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.
-
Right-click on the src folder, select New→Package. Name it as calculation.basic.
Right-click on the calculation.basic package, select New→Class. Name it Calculation and click Finish.
Insert the following simple function to the Calculation class:
public double square(double x){
return Math.pow(x, 2);
}
Save the file.
Now, right click on the WebContent folder, select New→JSP file.
Name it class.jsp and click Finish.
Insert the following codes between the
<body> tags.
<%@ page import="calculation.basic.*" %>
<% Calculation c=new Calculation(); %>
2 square is <%= c.square(2) %>
Save the file.
Run it by right clicking on it then selecting Run→Run on Server. Select Finish.
-
Exercises
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”.
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”;
Back to top