jsp 写一个简单的每次刷新页面时变量的值都会在原来的基础上加1.

如题所述

jsp简单的页面访问计数器的实现方法如下:
下面是两个文件的详细程序代码。
1. test.jsp文件代码
该文件要放到web目录下。
//test.jsp
<%@ page contentType="text/html;charset=gb2312"%>
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<META NAME="GENERATOR" CONTENT="Oracle JDeveloper">
<TITLE>计数器演示程序</TITLE>
</HEAD>
<BODY>
<!--创建并调用bean(counter)-->
<jsp:useBean id="counter" class="counter" scope="request">
</jsp:useBean>
<%
//调用counter对象的ReadFile方法来读取文件lyfcount.txt中的计数
String cont=counter.ReadFile("/lyfcount.txt");
//调用counter对象的ReadFile方法来将计数器加一后写入到文件lyfcount.txt中
counter.WriteFile("/lyfcount.txt",cont);%>
您是第<font color="red"><%=cont%></font>位访问者
</BODY>
</HTML>

2. counter.java文件代码
文件放到class目录下。
//counter.java 读写文件的一个bean
import java.io.*;

public class counter extends Object {
private String currentRecord = null;//保存文本的变量
private BufferedReader file; //BufferedReader对象,用于读取文件数据
private String path;//文件完整路径名
public counter() {
}
//ReadFile方法用来读取文件filePath中的数据,并返回这个数据
public String ReadFile(String filePath) throws FileNotFoundException
{
path = filePath;
//创建新的BufferedReader对象
file = new BufferedReader(new FileReader(path));
String returnStr =null;
try
{
//读取一行数据并保存到currentRecord变量中
currentRecord = file.readLine();
}
catch (IOException e)
{//错误处理
System.out.println("读取数据错误.");
}
if (currentRecord == null)
//如果文件为空
returnStr = "没有任何记录";
else
{//文件不为空
returnStr =currentRecord;
}
//返回读取文件的数据
return returnStr;
}
//ReadFile方法用来将数据counter+1后写入到文本文件filePath中
//以实现计数增长的功能
public void WriteFile(String filePath,String counter) throws FileNotFoundException
{
path = filePath;
//将counter转换为int类型并加一
int Writestr = Integer.parseInt(counter)+1;
try {
//创建PrintWriter对象,用于写入数据到文件中
PrintWriter pw = new PrintWriter(new FileOutputStream(filePath));
//用文本格式打印整数Writestr
pw.println(Writestr);
//清除PrintWriter对象
pw.close();
} catch(IOException e) {
//错误处理
System.out.println("写入文件错误"+e.getMessage());
}
}
}
温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2017-09-24
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<%
int i;
if(null != application.getAttribute("n1")){
String s = (String)application.getAttribute("n1");
out.println(s);
i = Integer.parseInt(s) + 1;
application.setAttribute("n1", i + "");
}else{
out.print("0");
i = 0;
application.setAttribute("n1", i + "");
}
%>
</head>
<body>

</body>
</html>本回答被提问者采纳
相似回答