介紹JSP HTTP服務(wù)器實(shí)現(xiàn)的以下特性
JSP HTTP服務(wù)器對(duì)常規(guī)請(qǐng)求的支持
這里的常規(guī)請(qǐng)求是指請(qǐng)求的資源為文件類型,不需要進(jìn)行解釋,編譯,執(zhí)行等處理。例如:文本文件(*.TXT),超文本文件(*.HTM,*.HTML),腳本文件(*.JS,*.VBS等),圖片文件(*.JPG,*.PNG,*.GIF,*.BMP)。
處理基于文件流的請(qǐng)求較為簡(jiǎn)單。只需要讀取本地的文件資源,再發(fā)送給客戶端即可。
1.JSP HTTP服務(wù)器文件流請(qǐng)求的處理示例代碼
- //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();
- }
以上是處理基于文本流的請(qǐng)求,以下是處理基于二進(jìn)制流的請(qǐng)求實(shí)例代碼。
2.JSP HTTP服務(wù)器二進(jìn)制流文件的處理示例代碼
- //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();
從以上代碼可以看出,處理文本流和二進(jìn)制流的請(qǐng)求的方式是不相同的,文本流的文件是按照行進(jìn)行處理,而二進(jìn)制流的文件是以批量讀取。
其中關(guān)鍵的是,對(duì)于不同的文件類型,發(fā)送數(shù)據(jù)給客戶端時(shí)必須指明服務(wù)器端應(yīng)答的媒體類型,即MIME(Multipurpose Internet Mail Extensions),這樣應(yīng)答給客戶端的資源才能被客戶端瀏覽器所識(shí)別,并調(diào)用相應(yīng)的應(yīng)用程序?qū)Y源進(jìn)行讀取。
文件類型 擴(kuò)展名 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
【編輯推薦】