本文讨论jsp中生成的servlet代码中全局变量和局部变量的问题:
请看下面一段代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>Hello World</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> This is my first JSP page. <br> <%! //有感叹号的语法声明的count表示为servlet的全局变量, //由于servlet整个生命周期只有一个实例,因此这个count的值会增加 int count = 0; %> <% //没有感叹号语法声明的count2表示为servlet的局部变量,每次调用service方法都会初始化 int count2 = 0; %> access count times : <%=++count %><br/> access times : <%=++count2 %><br/> </body> </html>
针对这两种语法:
1.<%! //有叹号
//这个在servlet代码中生成的是全局变量,由于servlet整个生命周期只有一个实例,因此这个count的值会增加
int count = 0;
%>
那么也就是说,能够在这个叹号的语法中声明方法,理论上是这样,没试验过,而在第二种语法中声明方法是会报错的
2.
<%//无叹号
//这个在servlet代码中生成的是局部变量
int count2 = 0;
%>