晚上好, 我发现这是用Java编写的非常基本的http服务器。
npm config get proxy
npm config rm proxy
npm config rm https-proxy
现在我试图在网站上添加一个简单的计数器,计算每次访问。我刚刚找到了需要Java EE liabraries的代码。 像这样:
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 SE Development Kit编写此代码?怎么样?
答案 0 :(得分:1)
如果我理解你的问题,那么是的。最简单的方法可能是向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();
}
}
,然后将其递增。像,
<link href="{{!!asset('/assets/global/plugins/font-awesome/css/font-awesome.min.css') !!}}" rel="stylesheet" type="text/css" />
<link href="{{ asset('/assets/global/plugins/font-awesome/css/font-awesome.min.css') }}" rel="stylesheet" type="text/css" />
答案 1 :(得分:1)
我的建议是不要使用int,因为它不是线程安全的,而是你应该使用AtomicInteger
AtomicInteger atomicInteger = new AtomicInteger(123); // initialize it with a value or empty
int theValue = atomicInteger.get(); // this is how you get it
atomicInteger.addAndGet(1); // to add a value to it, you can also getAndAdd(x)