晚上好,
我发现这是用Java编写的非常基本的http服务器。

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class Test {

public static void main(String[] args) throws Exception {
    HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
    server.createContext("/test", new MyHandler());
    server.setExecutor(null); // creates a default executor
    server.start();
}

static class MyHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange t) throws IOException {
        String response = "This is the response";
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
}

}


现在,我正在尝试在网站上添加一个简单的计数器,该计数器会统计该站点的每次访问。我刚刚找到了需要Java EE库的代码。
在这里像这样:

import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class PageHitCounter extends HttpServlet{

private int hitCount;

public void init()
{
 // Reset hit counter.
 hitCount = 0;
 }

public void doGet(HttpServletRequest request,
                HttpServletResponse response)
        throws ServletException, IOException
 {
  // Set response content type
  response.setContentType("text/html");
  // This method executes whenever the servlet is hit
  // increment hitCount
  hitCount++;
  PrintWriter out = response.getWriter();
  String title = "Total Number of Hits";
  String docType =
  "<!doctype html public \"-//w3c//dtd html 4.0 " +
  "transitional//en\">\n";
  out.println(docType +
    "<html>\n" +
    "<head><title>" + title + "</title></head>\n" +
    "<body bgcolor=\"#f0f0f0\">\n" +
    "<h1 align=\"center\">" + title + "</h1>\n" +
    "<h2 align=\"center\">" + hitCount + "</h2>\n" +
    "</body></html>");

  }
   public void destroy()
  {
  // This is optional step but if you like you
  // can write hitCount value in your database.
  }
  }


可以使用Java SE Development Kit编写此代码吗?如何?

最佳答案

如果我理解您的问题,那就可以。最简单的方法可能是在counter中添加Handler。将该counter添加到您的response中,然后对其进行递增。就像是,

static class MyHandler implements HttpHandler {
    static int counter = 0;
    @Override
    public void handle(HttpExchange t) throws IOException {
        String response = String.format("This is response %d%n", counter++);
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
}

07-24 09:38
查看更多