为什么用的servlet不能统计次数啊???????
package My;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
*
* @author Administrator
* @version
*/
public class Count extends HttpServlet {
/** Processes requests for both HTTP <code> GET </code> and <code> POST </code> methods.
* @param request servlet request
* @param response servlet response
*/
int count = 1;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException,
IOException {
response.setContentType( "text/html;charset=gbk ");
response.setCharacterEncoding( "gbk ");
String num=(String)request.getAttribute( "C ");
if(request.getAttribute( "C ")!=null)
count +=1;
request.setAttribute( "C ",String.valueOf(count));
PrintWriter out = response.getWriter();
out.print( " <html> <head> <title> test </title> </head> <body> 已经被访问 "+ request.getAttribute( "C ") + "次 </body> </html> ");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
------解决方案--------------------肯定是1啊,你的请求是放在request里面的,你把他放在session里面试试
HttpSession session=request.getSession();
session.setAttribute( "C ",String.valueOf(count));
------解决方案--------------------对于客户端的每一个请求, 都会new一个request, 因此你每次取C值的时候都会是0, 加一后, 显示即为一, 没有变化.
对于这个问题, 你可以看看 PageContext, ServletRequest, HttpSess