我正在使用Jetty 9,並試圖在所有正文到達服務器之前處理PUT請求的標頭。下面是我做了什麼:Jetty嵌入式 - PUT動詞 - 正文到達之前的處理標頭
Server.java:
public class SimplestServer
{
public static void main(String[] args) throws Exception
{
Server server = new Server(9080);
ServletHandler handler = new ServletHandler();
server.setHandler(handler);
handler.addServletWithMapping(HelloServlet.class, "/*");
handler.addFilterWithMapping(HelloPrintingFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
server.start();
server.dumpStdErr();
server.join();
}
public static class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(System.currentTimeMillis() + ": Hello from HelloServlet GET");
}
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println(System.currentTimeMillis() + ": Hello from HelloServlet PUT");
}
}
public static class HelloPrintingFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println(System.currentTimeMillis() + ": Hello from filter");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
System.out.println(System.currentTimeMillis() + ": Init from filter");
}
@Override
public void destroy() {
System.out.println(System.currentTimeMillis() + ": Destroy from filter");
}
}
}
Client.java
public class SimplestClient
{
public static void main(String[] args) throws Exception
{
URL url = new URL("http://localhost:9080/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStream out = httpCon.getOutputStream();
byte[] b = new byte[65536];
Random r = new Random();
r.nextBytes(b);
for (int i = 0; i < 1024; i++) {
out.write(b);
}
System.out.println(System.currentTimeMillis() + ": Data sent. Waiting 5 seconds...");
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
out.close();
System.out.println(System.currentTimeMillis() + ": Done!");
httpCon.getInputStream();
}
}
簡而言之,服務器程序監聽端口9080
連接,當一個請求到達過濾器HelloPrintingFilter
得到執行,然後請求由HelloServlet
處理。客戶端連接到服務器,發送一堆數據,然後休眠5秒鐘,最後關閉與服務器的連接。
兩個程序的運行產生以下結果:
客戶:
1469613522350: Data sent. Waiting 5 seconds...
1469613527351: Done!
服務器:
1469613527373: Hello from filter
1469613527373: Hello from HelloServlet PUT
看着我只能讓我的過濾代碼執行後,所有的時間戳身體已經抵達。任何人都可以解釋我該怎麼做?一個典型的用例是:客戶端嘗試上傳5GB文件。只要標題到達,我想檢查它們是否正常(例如,通過檢查是否存在Content-MD5標題或任何需要檢查的自定義標題)。如果請求正確,則開始處理正文。如果請求不正確,請關閉連接。
謝謝。
錯誤的假設。發送請求和/或響應正文內容時沒有「Content-Length」標頭是完全有效/合法的,也就是所謂的[分塊傳輸編碼](https://en.wikipedia.org/wiki/Chunked_transfer_encoding),它Jetty作爲客戶端和/或服務器支持開箱即用。 –