jsp两种声明变量<%! %>和<% %>的区别

来源:互联网 发布:汽车仿真教学软件 编辑:程序博客网 时间:2024/05/11 17:22

初学JSP,说一下自己对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++,则会不断累加。



0 0
原创粉丝点击