您好,登錄后才能下訂單哦!
這篇文章主要介紹JSP HTTP服務(wù)器如何實現(xiàn)對常規(guī)請求的支持,文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!
JSP HTTP服務(wù)器對常規(guī)請求的支持
這里的常規(guī)請求是指請求的資源為文件類型,不需要進行解釋,編譯,執(zhí)行等處理。例如:文本文件(*.TXT),超文本文件(*.HTM,*.HTML),腳本文件(*.JS,*.VBS等),圖片文件(*.JPG,*.PNG,*.GIF,*.BMP)。
處理基于文件流的請求較為簡單。只需要讀取本地的文件資源,再發(fā)送給客戶端即可。
1.JSP HTTP服務(wù)器文件流請求的處理示例代碼
//Create client socket output stream m_sout = new PrintWriter(m_s.getOutputStream(), true); m_soutx = null; m_sout.println("HTTP/1.0 200 OK\nMIME-Version:1.0\nContent-Type:text/html\n\n"); File file = new File(fileName); if(file.exists() == true) { //Create local file input stream BufferedReader fin = new BufferedReader(new FileReader(file) ); String line = null; String response = ""; //Read file by lines while( (line = fin.readLine() ) != null) { responseresponse = response + line + "\n"; } //Send the content to client socket m_sout.println(response); //Close local file handle fin.close(); }
以上是處理基于文本流的請求,以下是處理基于二進制流的請求實例代碼。
2.JSP HTTP服務(wù)器二進制流文件的處理示例代碼
//Create client socket output stream m_sm_soutx = m_s.getOutputStream(); m_sout = null; String header = "HTTP/1.0 200 OK\nMIME-Version:1.0\n"; //Send content to client socket m_soutx.write(header.getBytes() ); String mime = ""; //Get MIME by file type switch(typeFlag) { case TYPE_JPEG: //jpeg file { mime = "image/jpeg"; break; } case TYPE_GIF: //gif file { mime = "image/gif"; break; } case TYPE_BMP: //bmp file { mime = "image/bmp"; break; } case TYPE_PNG: //png file { mime = "image/png"; break; } } mime = "Content-Type:" + mime + "\n\n"; m_soutx.write(mime.getBytes() ); File file = new File(fileName); if(file.exists() == true) //Read image files and send to client socket { //Create local file input stream RandomAccessFile fin = new RandomAccessFile(fileName, "r"); final long size = fin.length(); byte [] buffer = new byte[(int)size]; fin.readFully(buffer); fin.close(); //Send data to client socket m_soutx.write(buffer); } //Close client socket output stream m_soutx.close();
從以上代碼可以看出,處理文本流和二進制流的請求的方式是不相同的,文本流的文件是按照行進行處理,而二進制流的文件是以批量讀取。
其中關(guān)鍵的是,對于不同的文件類型,發(fā)送數(shù)據(jù)給客戶端時必須指明服務(wù)器端應(yīng)答的媒體類型,即MIME(Multipurpose Internet Mail Extensions),這樣應(yīng)答給客戶端的資源才能被客戶端瀏覽器所識別,并調(diào)用相應(yīng)的應(yīng)用程序?qū)Y源進行讀取。
文件類型 擴展名 MIME
文本文件 .TXT text/plain
HTML(HyperText Markup Language)文件 .HTML,.HTM text/html
JPEG(Joint Photographic Experts Group)文件 .JPG,.JPEG image/jpeg
PNG(Portable Network Graphic Format)文件 .PNG image/png
BMP(Bitmap)文件 .BMP application/x-MS-bmp
GIF(Graphics Interchange Format)文件 .GIF image/gif
XML(EXtensible Markup Language)文件 .XML text/xml
常用類型文件的MIME
以上是“JSP HTTP服務(wù)器如何實現(xiàn)對常規(guī)請求的支持”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。