jsp中的宣告是用來在jsp頁面中宣告變數、方法及呼叫類別的。聲明是以【<%!】開頭,以【%>】結束的一對標籤,標籤中可以包含任意數量的、合法的Java聲明語句。
![jsp中的聲明用來做什麼](https://img.php.cn/upload/article/202009/15/2020091511520644135.jpg)
聲明(declaration)用來在JSP頁面中宣告變數與定義方法。聲明是以<%!
開頭,以%>
結束的標籤,其中可以包含任意數量的合法的Java聲明語句。以下是JSP宣告的一個範例:
上面程式碼宣告了一個名為count的變數並將其初始化為0。宣告的變數僅在頁面第一次載入時由容器初始化一次,初始化後在後面的請求中一直保持該值。
在 JSP 頁面中可以宣告變數、方法和類,其宣告格式如下:
特別要注意,在「<%「與「!」之間不要有空格。宣告的語法與在 Java 語言中宣告變數和方法時的語法是一樣的。
宣告變數
1 2 3 4 5 | <%!
int x,y=100,z;
String tom=null,jery= "Love JSP" ;
Date date ;
%>
|
登入後複製
聲明方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <%@
page contentType= "text/html; charset=utf-8" %><%!int num = 0;
synchronized void add(){
num++;
}
%>
<% add(); %>
<html>
<body>
<center>您是第<%=num%>位访问该页面的游客!</center>
</body>
</html>
|
登入後複製
![jsp中的聲明用來做什麼](https://img.php.cn/upload/article/000/000/032/5cce9b1897638580.png)
# #宣告類別
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | <%@
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>
|
登入後複製
![jsp中的聲明用來做什麼](https://img.php.cn/upload/article/000/000/032/5cce9b2055044198.png)
以上是jsp中的聲明用來做什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!