Jsp--(使用声明标识)

xiaoxiao2021-02-28  36

声明标识的语法如下:

<%!  声明变量或者方法的代码 %>

说明:由于使用声明标识声明的变量是全局的,所以在多个用户并访问时会产生线程安全的问题,此种方式应用很少。

index.jsp代码如下:(在index.jsp页面中通过声明标识定义一成员变量count用于保存来访的人数,并调用getCount()方法来获取当前来访人数,最后通过JSP表达式来调用getCount()方法将来访的人数的值输出到页面之中。

由于使用声明标识并不能确保线程的安全,所以实例中通过page指令将isThreadSafe的值设置为false。)

<%@ page language="java" import="java.util.*" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"isThreadSafe="false"%> <% 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>My JSP 'index.jsp' starting page</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"> --> <title>来访统计</title> </head> <body> <%! int count=0; public int getCount(){ count++; return count; } %> 您好,您是本站的第 <%=getCount() %> 位来访者! <% %> </body> </html>

反思:

1.在使用JSP表达式时,格式使用错误,争取的格式应该是<%=  表达式%>

2.在使用线程安全问题时,正确的应该是:pageEncoding="UTF-8"isThreadSafe="false"%>

转载请注明原文地址: https://www.6miu.com/read-2400005.html

最新回复(0)