jsp两种声明变量%,%和% %的区别

如题所述

先看代码,简单的投票统计页面:
<%@ page contentType="text/html;charset=GB2312"%>
<html>
<head>
<title>无标题文档</title>
</head>
<body>
<%
String cost =request.getParameter("cost");
<strong>int vote[] = new int [3];</strong>
synchronized(vote){
if(cost!=null){
if(cost.compareTo("0")==0)
vote[0]++;
if(cost.compareTo("1")==0)
vote[1]++;
if(cost.compareTo("2")==0)
vote[2]++;
}
}
%>
投票结果:<br />
候选人A:<%=vote[0]%><br>候选人B:<%=vote[1]%><br>候选人C:<%=vote[2]%><br>
</body>
<form method="get" action="notfirst.jsp">
<p>投票</p>
<input type="radio" value="0" checked name="cost">候选人A<br>
<input type="radio" value="1" checked name="cost">候选人B<br>
<input type="radio" value="2" checked name="cost">候选人C<br>
<input type="submit" value="投票" name="b1">
</form>
</html>
声明 int vote [] =new int [3] 在<% %>内,重复点击投票按钮,候选人票数不会增长。

<%@ page contentType="text/html;charset=GB2312"%>
<html>
<head>
<title>无标题文档</title>
</head>
<body>
<strong><%! int vote[] = new int [3];%></strong>
<%
String cost =request.getParameter("cost");
synchronized(vote){
if(cost!=null){
if(cost.compareTo("0")==0)
vote[0]++;
if(cost.compareTo("1")==0)
vote[1]++;
if(cost.compareTo("2")==0)
vote[2]++;
}
}
%>
投票结果:<br />
候选人A:<%=vote[0]%><br>候选人B:<%=vote[1]%><br>候选人C:<%=vote[2]%><br>
</body>
<form method="get" action="notfirst.jsp">
<p>投票</p>
<input type="radio" value="0" checked name="cost">候选人A<br>
<input type="radio" value="1" checked name="cost">候选人B<br>
<input type="radio" value="2" checked name="cost">候选人C<br>
<input type="submit" value="投票" name="b1">
</form>
</html>
声明<%! int vote[] = new int [3];%>在<%! %>内,重复点击投票按钮,候选人票数会加1.

通过执行对比,发现声明在<span style="font-family: Arial, Helvetica, sans-serif;"><%! %>内的变量,最后会被编译成java类里的一个成员变量,也就是全局变量,而声明在</span><span style="font-family: Arial, Helvetica, sans-serif;"><% %>内的变量,会被编译成Java类成员方法里的一个变量。</span>
<span style="font-family: Arial, Helvetica, sans-serif;"><span style="white-space:pre"> </span> 在执行第一段代码时,每按一次投票按钮,重新执行一遍</span>
<span style="white-space:pre"> </span><%
<span style="white-space:pre"> </span>String cost =request.getParameter("cost");
<strong><span style="white-space:pre"> </span>int vote[] = new int [3];</strong>
<span style="white-space:pre"> </span>synchronized(vote){
<span style="white-space:pre"> </span>if(cost!=null){
<span style="white-space:pre"> </span>if(cost.compareTo("0")==0)
<span style="white-space:pre"> </span>vote[0]++;
<span style="white-space:pre"> </span>if(cost.compareTo("1")==0)
<span style="white-space:pre"> </span>vote[1]++;
<span style="white-space:pre"> </span>if(cost.compareTo("2")==0)
<span style="white-space:pre"> </span>vote[2]++;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>%>
重新为vote分配空间,统计票数。而执行第二段代码,声明在<%! %>内的成员变量在执行成员方法后,通过vote++,则会不断累加。
温馨提示:答案为网友推荐,仅供参考
相似回答