gpt4 book ai didi

java - Java http 服务器上的访问者计数器

转载 作者:行者123 更新时间:2023-12-02 04:16:37 25 4
gpt4 key购买 nike

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

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 开发工具包来编写这个吗?又如何?

最佳答案

如果我理解你的问题,那么是的。最简单的方法可能是向您的处理程序添加一个计数器。将该计数器添加到您的响应中,然后递增它。比如,

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();
}
}

关于java - Java http 服务器上的访问者计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33246718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com