Declarations in jsp are used to declare variables, methods and calling classes in jsp pages. A declaration is a pair of tags starting with [<%!] and ending with [%>]. The tags can contain any number of legal Java declaration statements.
Declaration (declaration) is used to declare variables and define methods in JSP pages. A declaration is a tag starting with <%!
and ending with %>
, which can contain any number of legal Java declaration statements. The following is an example of a JSP declaration:
<%! int count = 0; %>
The above code declares a variable named count and initializes it to 0. The declared variable is initialized by the container only once when the page is first loaded. After initialization, the value is maintained in subsequent requests.
Variables, methods and classes can be declared in JSP pages. The declaration format is as follows:
<%!声明变量、方法和类的代码%>
Pay special attention to the fact that there should be no spaces between "<%" and "!". The syntax for declaration is the same as when declaring variables and methods in the Java language.
Declare variables
<%! int x,y=100,z; String tom=null,jery="Love JSP"; Date date; %>
Declare methods
<%@ page contentType="text/html; charset=utf-8" %><%!int num = 0; //声明一个计数变量 synchronized void add(){ //该方法实现访问次数的累加操作 num++; } %> <% add(); %> <html> <body> <center>您是第<%=num%>位访问该页面的游客!</center> </body> </html>
Declaration class
<%@ page contentType="text/html; charset=utf-8" %> <html> <head> <title></title> </head> <body> <p><font size="4">请输入圆的半径:<br></font></p> <form action="" method="get" name="form" id="form"> <font size="4"><input type="text" name="cat" value="1"> <input type="submit" value="送出" name="submit"></font> </form> <%! public class Circle{ double r; Circle(double r){ this.r = r; } double 求面积(){ return Math.PI*r*r;}} %> <% String str = request.getParameter("cat"); double r; if(str != null){ r = Double.parseDouble(str); }else{ r = 1; } Circle circle = new Circle(r); %> <p><font size="4"> 圆的面积是: <%=circle.求面积()%> </font></p> </body> </html>
The above is the detailed content of What are the declarations in jsp used for?. For more information, please follow other related articles on the PHP Chinese website!